#!/usr/bin/env python3 """Bounded Stage-only SEO operation; no generic Prisma migration execution.""" import argparse import hashlib import json import os from pathlib import Path import re import shlex import shutil import subprocess import time import uuid from catalog import CATALOG_SQL, validate ROOT = Path(__file__).resolve().parents[2] SQL_PATH = 'backend/prisma/migrations/20261028120000_add_seo_tracking_contract/migration.sql' SQL_DIGEST = 'de1386398026c6373ce8692fb165b904e189f830d7b20914d8a4b512a47f9d16' IMAGE = 'sha256:de3a4eab8fdfa507ea92aac488b916b08089e515db49b055fe71dfa271ba3a28' STAGE = 'canino_db_stage' def check_binding(sha, source, mode, reviewed): if not re.fullmatch('[0-9a-f]{40}', sha) or sha != source: raise ValueError('Exact source/event SHA binding required') if mode == 'apply' and reviewed != sha: raise ValueError('Independent reviewed operation SHA required') def check_database(name): if name.strip() != 'caninodb_stage': raise ValueError('Not Stage database') class Docker: def __init__(self, remote=False): self.remote = remote def run(self, args, data=None, timeout=180): cmd = ['docker'] + args if self.remote: cmd = ['ssh', '-F', '/opt/data/.ssh/config', '-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=/opt/data/.ssh/known_hosts', 'parsa-host', shlex.join(cmd)] return subprocess.run(cmd, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout, check=True).stdout def sql(self, container, query): # Live identity and credentials are never read into Python or printed. if container == STAGE: args = ['exec', '-i', STAGE, 'sh', '-c', 'exec psql -X -qAt -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"'] else: args = ['exec', '-i', container, 'psql', '-h', '127.0.0.1', '-U', 'postgres', '-d', 'rehearsal', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1'] return self.run(args, query.encode()).decode().strip() def catalog(docker, name): return json.loads(docker.sql(name, 'SET search_path=public;\n' + CATALOG_SQL)) def transaction(sql): return ("BEGIN; SET LOCAL lock_timeout='5s'; SET LOCAL statement_timeout='60s'; " "SELECT pg_advisory_xact_lock(731920260); SET LOCAL search_path=public;\n" + sql + '\nCOMMIT;') def main(): ap = argparse.ArgumentParser() ap.add_argument('mode', choices=['rehearse', 'apply']) ap.add_argument('--sha', required=True) ap.add_argument('--ssh-rehearsal', action='store_true') ap.add_argument('--evidence', required=True) a = ap.parse_args() source = subprocess.check_output(['git', '-C', str(ROOT), 'rev-parse', 'HEAD'], text=True).strip() check_binding(a.sha, source, a.mode, os.environ.get('STAGE_SCHEMA_REVIEWED_SHA', '')) if a.mode == 'apply' or not a.ssh_rehearsal: if os.environ.get('GITHUB_ACTIONS') != 'true' or os.environ.get('GITHUB_SHA') != a.sha: raise ValueError('CI exact SHA required') if os.environ.get('GITHUB_REF') != 'refs/heads/ops/seo-schema-stage-' + a.mode: raise ValueError('Dedicated Stage operation ref required') if a.ssh_rehearsal and a.mode != 'rehearse': raise ValueError('SSH transport permits rehearsal only') sql_bytes = (ROOT / SQL_PATH).read_bytes() if hashlib.sha256(sql_bytes).hexdigest() != SQL_DIGEST: raise ValueError('Reviewed SQL digest mismatch') if subprocess.check_output(['git','-C',str(ROOT),'show',a.sha+':'+SQL_PATH]) != sql_bytes: raise ValueError('Dirty SQL refused') # A local read-only rehearsal may exercise pending tooling. CI must execute # only committed operation and catalog sources from the event SHA. if not a.ssh_rehearsal: for rel in ('scripts/stage-schema/operation.py', 'scripts/stage-schema/catalog.py'): if subprocess.check_output(['git','-C',str(ROOT),'show',a.sha+':'+rel]) != (ROOT/rel).read_bytes(): raise ValueError('Dirty operation source refused') if a.mode == 'apply' and a.ssh_rehearsal: raise ValueError('Live apply cannot use SSH rehearsal transport') evidence = Path(a.evidence) evidence.mkdir(mode=0o700, parents=True, exist_ok=False) os.chmod(evidence, 0o700) d = Docker(a.ssh_rehearsal) owned = [] try: # Share application deployment lock; never chmod operational lock/config. runner = d.run(['inspect','-f','{{.Config.Image}}','gitea_runner']).decode().strip() lock = d.run(['create','--name','canina-stage-deploy-lock','--pull=never', '--network','none','--cap-drop=ALL','--security-opt=no-new-privileges', '--mount','type=bind,src=/opt/services/canina,dst=/host-canina,readonly', '--entrypoint','/bin/sh',runner,'-c', 'exec 9