import importlib.util import tempfile import unittest from pathlib import Path SPEC = importlib.util.spec_from_file_location('production', Path(__file__).with_name('production-release.py')) m = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(m) class ProductionGuards(unittest.TestCase): def receipt(self): return dict(sha='a'*40, baseline='b'*40, stage_run_url='https://git.parsaaghayi.ir/parsa/canina/actions/runs/123', reviewer='CEO delegated acceptance', accepted=True, scope='reliability-only', paths=['nginx.conf']) def test_exact_six_baseline_gate_repairs_allowed_not_frontend_wildcard(self): files = { 'frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx', 'frontend/admin-panel/src/pages/selectionSafety.test.tsx', 'frontend/admin-panel/src/pages/workflowSafety.test.tsx', 'frontend/admin-panel/src/test/setup.ts', 'frontend/admin-panel/src/test/storage.test.ts', 'frontend/application/components/AnalyticsDeferred.tsx', } r=self.receipt();r['paths']=sorted(files) m.validate_receipt(r,'a'*40,'b'*40,sorted(files)) for path in ['frontend/admin-panel/src/pages/Other.tsx', 'frontend/application/components/Other.tsx']: r['paths']=[path] with self.assertRaises(ValueError): m.validate_receipt(r,'a'*40,'b'*40,[path]) def test_exact_stage_sha(self): r=self.receipt() m.validate_receipt(r, 'a'*40, 'b'*40, ['nginx.conf']) with self.assertRaises(ValueError): m.validate_receipt(r, 'c'*40, 'b'*40, ['nginx.conf']) def test_scope_and_baseline_fail_closed(self): r=self.receipt() for baseline, paths in [('c'*40, ['nginx.conf']), ('b'*40, ['backend/prisma/schema.prisma']), ('b'*40, ['nginx.conf','backend/src/other.ts'])]: with self.assertRaises(ValueError): m.validate_receipt(r, 'a'*40, baseline, paths) r['accepted']=False with self.assertRaises(ValueError): m.validate_receipt(r,'a'*40,'b'*40,['nginx.conf']) def test_receipt_rejects_non_gitea_evidence(self): r=self.receipt();r['stage_run_url']='https://evil.test/run/1' with self.assertRaises(ValueError): m.validate_receipt(r,'a'*40,'b'*40,['nginx.conf']) def test_snapshot_preserves_runtime_and_immutable_image(self): x={'Name':'/canino_backend_prod','Image':'sha256:'+'a'*64,'Config':{'Env':['DATABASE_URL=private'], 'Labels':{'com.docker.compose.project':'prod','com.docker.compose.service':'backend_prod','traefik.enable':'true'},'User':'node','WorkingDir':'/app','Entrypoint':['node'],'Cmd':['dist/main']},'Mounts':[{'Type':'volume','Name':'prod_canina_prod_uploads','Destination':'/app/uploads','RW':True},{'Type':'bind','Source':'/opt/services/proxy/certs/canina','Destination':'/app/ssl_certs','RW':True}],'NetworkSettings':{'Networks':{'traefik_public':{}}},'HostConfig':{'RestartPolicy':{'Name':'always'},'PortBindings':{},'Privileged':False}} c=m.snapshot([x]); s=c['services']['backend_prod'] self.assertEqual(s['image'],x['Image']) self.assertEqual(s['environment'],['DATABASE_URL=private']) self.assertTrue(c['volumes']['prod_canina_prod_uploads']['external']) self.assertNotIn('com.docker.compose.project',s['labels']) x['Mounts'][0]['Name']='stage_canina_stage_uploads' with self.assertRaises(ValueError): m.snapshot([x]) def test_production_snapshot_forces_direct_next_url(self): import os, json from unittest.mock import patch c={'services':{n:{'environment':['FRONTEND_INTERNAL_URL=http://legacy:8080','REVALIDATION_SECRET=old'], 'labels':{}} for n in ['backend_prod','frontend_prod']}} with tempfile.TemporaryDirectory() as d: old=os.getcwd() try: os.chdir(d) with patch.object(m.sys,'argv',['production-release.py','snapshot']), patch.dict(os.environ,DEPLOY_SHA='a'*40), patch.object(m.subprocess,'check_output',return_value=b'[]'), patch.object(m,'snapshot',return_value=c): m.main() services=json.loads(Path('.prod-compose.json').read_text())['services'] self.assertIn('FRONTEND_INTERNAL_URL=http://frontend_prod:3000',services['backend_prod']['environment']) for s in services.values(): self.assertFalse(any(v.startswith('REVALIDATION_SECRET=') for v in s['environment'])) self.assertTrue(s['env_file'][0]['required']) finally: os.chdir(old) def test_private_receipt_permissions(self): import os with tempfile.TemporaryDirectory() as d: p=Path(d)/'receipt.json';p.write_text('{}');p.chmod(0o644) with self.assertRaises(ValueError): m.private_json(p) p.unlink();p.symlink_to('/dev/null') with self.assertRaises(ValueError): m.private_json(p) def test_no_schema_or_orphan_mutations_in_production(self): text=Path(__file__).with_name('rollout-production.sh').read_text() for dangerous in ['migrate deploy','db push','--remove-orphans','docker compose down','git reset']: self.assertNotIn(dangerous,text) self.assertIn('trap rollback EXIT',text) self.assertIn('x-revalidate-secret',text) self.assertIn('prod_canina_prod_db prod_canina_prod_uploads',text) def test_ci_and_nonsha_refused_before_effects(self): import subprocess, os for script,args in [('deploy.sh',['main']),('ci-host-deploy.sh',[]) ,('rollout-production.sh',[])]: p=subprocess.run(['bash',str(Path(__file__).with_name(script)),*args],env={'PATH':os.environ['PATH']},capture_output=True) self.assertEqual(p.returncode,2, p.stderr) if __name__=='__main__': unittest.main()