Files
canina/scripts/production-release.py
T
2026-10-25 07:18:30 +00:00

110 lines
6.9 KiB
Python

#!/usr/bin/env python3
"""Private production acceptance and runtime snapshot helpers. Never log config."""
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import sys
ALLOWED = {'nginx.conf', 'Dockerfile', 'backend/Dockerfile', '.dockerignore',
'.gitea/workflows/deploy.yml', 'scripts/deploy.sh', 'scripts/ci-host-deploy.sh',
'scripts/rollout-production.sh', 'scripts/production-release.py', 'scripts/test_production_release.py',
'scripts/compose.stage.yml', 'scripts/rollout-stage.sh', 'scripts/revalidation-runtime.py',
'scripts/provision-revalidation-env.py', 'scripts/tests/test_revalidation_runtime.py',
'scripts/tests/test_ci_host_boundary.py', 'scripts/tests/test_stage_provision_wiring.py',
'scripts/tests/test_stage_rollout.py',
'backend/src/common/revalidation/revalidation.service.ts',
'backend/src/common/revalidation/revalidation.service.spec.ts',
'backend/src/orchestration-worker/worker-registration.spec.ts',
'backend/src/support-chat/support-chat.http.spec.ts',
# Exact baseline gate repairs reviewed in 1bb6274; never a frontend wildcard.
'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',
'frontend/application/components/BlogPage.tsx',
'frontend/application/components/__tests__/BlogPage.sorting.test.tsx'}
def validate_receipt(r, sha, baseline, paths):
if not (r.get('accepted') is True and r.get('scope') == 'reliability-only'
and r.get('sha') == sha and r.get('baseline') == baseline
and re.fullmatch(r'https://git\.parsaaghayi\.ir/parsa/canina/actions/runs/[0-9]+', r.get('stage_run_url',''))
and isinstance(r.get('reviewer'), str) and r['reviewer'].strip()
and sorted(r.get('paths',[])) == sorted(paths)
and paths and set(paths) <= ALLOWED):
raise ValueError('Exact SHA, audited Stage acceptance and narrow reviewed diff required')
def private_json(path):
p=Path(path); s=p.lstat()
if not stat.S_ISREG(s.st_mode) or s.st_uid != 0 or s.st_mode & 0o077 or s.st_nlink != 1:
raise ValueError('Root-owned private regular acceptance receipt required')
return json.loads(p.read_text())
def snapshot(items):
c={'services':{},'volumes':{},'networks':{'traefik_public':{'external':True,'name':'traefik_public'}}}
for x in items:
cfg=x['Config']; labels=cfg.get('Labels') or {}; name=labels.get('com.docker.compose.service')
if name not in {'backend_prod','frontend_prod'} or labels.get('com.docker.compose.project')!='prod' or x['Name']!='/canino_'+name:
raise ValueError('Unexpected production identity')
if set(x['NetworkSettings']['Networks']) != {'traefik_public'} or x['HostConfig'].get('Privileged') or x['HostConfig'].get('PortBindings'):
raise ValueError('Unexpected production isolation')
s={'image':x['Image'],'container_name':x['Name'][1:],'restart':x['HostConfig']['RestartPolicy']['Name'],
'environment':cfg['Env'],'labels':{k:v for k,v in labels.items() if not k.startswith('com.docker.compose.')},
'networks':['traefik_public'],'volumes':[]}
for key, source in [('user','User'),('working_dir','WorkingDir'),('entrypoint','Entrypoint'),('command','Cmd')]:
if cfg.get(source): s[key]=cfg[source]
for m in x['Mounts']:
if m['Type']=='volume' and m.get('Name')=='prod_canina_prod_uploads' and m['Destination']=='/app/uploads':
c['volumes'][m['Name']]={'external':True,'name':m['Name']}
source=m['Name']
elif m['Type']=='bind' and m['Source']=='/opt/services/proxy/certs/canina' and m['Destination']=='/app/ssl_certs': source=m['Source']
else: raise ValueError('Unreviewed production mount')
s['volumes'].append({'type':m['Type'],'source':source,'target':m['Destination'],'read_only':not m['RW']})
if name=='backend_prod' and not any(v['target']=='/app/uploads' for v in s['volumes']): raise ValueError('Missing uploads')
c['services'][name]=s
return c
def main():
action=sys.argv[1]
if action=='receipt':
sha=os.environ['DEPLOY_SHA']; base=subprocess.check_output(['git','-C','/opt/services/canina/prod','rev-parse','HEAD'],text=True).strip()
paths=subprocess.check_output(['git','diff','--name-only',base,sha],text=True).splitlines()
r=private_json('/opt/services/canina/production-acceptance/'+sha+'.json')
validate_receipt(r,sha,base,paths)
# Bind audited evidence to the two currently running Stage artifacts.
stage=json.loads(subprocess.check_output(['docker','inspect','canino_backend_stage','canino_frontend_stage']))
actual={x['Name'][1:]:x['Image'] for x in stage}
if r.get('stage_images') != actual or not all(x['State']['Running'] for x in stage):
raise ValueError('Audited Stage artifacts no longer running')
for x in stage:
wd=x['Config']['Labels'].get('com.docker.compose.project.working_dir')
if wd != '/opt/services/canina/releases/'+sha:
raise ValueError('Stage source SHA mismatch')
marker=subprocess.check_output(['docker','exec','canino_backend_stage','cat','/app/STAGE_TEST_ARTIFACT_SHA'],text=True)
if marker != sha: raise ValueError('Stage backend artifact SHA mismatch')
elif action=='snapshot':
items=json.loads(subprocess.check_output(['docker','inspect','canino_backend_prod','canino_frontend_prod']))
c=snapshot(items)
Path('.prod-rollback.json').write_text(json.dumps(c))
sha=os.environ['DEPLOY_SHA']
for name,s in c['services'].items():
# Keep operational environment, labels, mounts and networks, not dirty checkout compose.
s['image']='canina-production-'+name+':'+sha
s.pop('entrypoint',None); s.pop('command',None)
s.setdefault('labels',{})['ir.canina.release.sha']=sha
s['env_file']=[{'path':str(Path.cwd()/'.revalidation.env'),'required':True}]
s['environment']=[v for v in s['environment'] if not v.startswith('REVALIDATION_SECRET=')]
if name=='backend_prod':
s['environment']=[v for v in s['environment'] if not v.startswith('FRONTEND_INTERNAL_URL=')]
s['environment'].append('FRONTEND_INTERNAL_URL=http://frontend_prod:3000')
s['build']={'context':str(Path.cwd() / ('backend' if name=='backend_prod' else '.')),'dockerfile':'Dockerfile'}
if name=='frontend_prod': s['build']['args']={'NEXT_PUBLIC_API_URL':'https://api.canina.ir/api','VITE_API_URL':'https://api.canina.ir'}
Path('.prod-compose.json').write_text(json.dumps(c))
else: raise ValueError('Unknown action')
if __name__=='__main__': main()