#!/usr/bin/env python3 """Root-only Stage principal intent journal. No generic command/container inputs.""" import fcntl import json import os from pathlib import Path import re import subprocess import sys import time import uuid ROOT = Path('/opt/services/canina/stage-principal-cleanup') APPROVAL = 'owner-authorized-stage-editorial' def validate(i): if set(i) != {'sha','session','ttl','generation','due'} or not re.fullmatch('[a-f0-9]{40}', i['sha']) or not re.fullmatch('[a-z0-9-]{8,64}', i['session']) or not re.fullmatch('[a-f0-9-]{36}', i['generation']) or not isinstance(i['ttl'],int) or not 60 <= i['ttl'] <= 3600 or not isinstance(i['due'],int): raise ValueError('Invalid cleanup intent') class Worker: def __init__(self, root, run): self.root, self.run = root, run def save(self, intent): validate(intent) p = self.root / (intent['session']+'.json') # Exclusive creation forbids reusing a session or extending its deadline. fd = os.open(p, os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW, 0o600) with os.fdopen(fd,'w') as f: json.dump(intent,f); f.flush(); os.fsync(f.fileno()) self.sync() def sync(self): fd=os.open(self.root,os.O_RDONLY|os.O_DIRECTORY) try: os.fsync(fd) finally: os.close(fd) def sweep(self, now): with open(self.root/'lock','a') as lock: try: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) except BlockingIOError: return for p in sorted(self.root.glob('*.json')): try: fd=os.open(p,os.O_RDONLY|os.O_NOFOLLOW) with os.fdopen(fd) as f: i=json.load(f) validate(i) if p.name != i['session']+'.json': raise ValueError('Intent name mismatch') if i['due'] <= now and self.run(i,'close'): p.unlink(); self.sync() except Exception: # Keep intent through DB/container/redeploy failures; next tick retries. print('Stage cleanup pending',file=sys.stderr) def run(i, action): # Opens remain SHA pinned; cleanup only uses the CURRENT artifact's narrow CLI. # Original ownership is the session plus unpredictable account generation. container=subprocess.check_output(['docker','inspect','--format','{{.Id}}','canino_backend_stage'],text=True,timeout=30).strip() if not re.fullmatch('[a-f0-9]{64}',container): return False sha=subprocess.check_output(['docker','exec',container,'cat','/app/STAGE_TEST_ARTIFACT_SHA'],text=True,timeout=30).strip() if not re.fullmatch('[a-f0-9]{40}',sha) or (action=='open' and sha!=i['sha']): return False env={'APP_ENV':'stage','CI':'true','STAGE_TEST_PRINCIPAL_ENABLED':'true','STAGE_TEST_APPROVAL':APPROVAL,'STAGE_TEST_SHA':sha,'STAGE_TEST_SESSION':i['session'],'STAGE_TEST_TTL_SECONDS':str(i['ttl']),'STAGE_TEST_GENERATION':i['generation']} cmd=['docker','exec'] for k,v in env.items(): cmd+=['-e',k+'='+v] cli=cmd+[container,'node','dist/auth/stage-test-principal.cli.js'] # Never send a generation-fenced cleanup to an older CLI that ignores fences. capability=subprocess.check_output(cli+['cleanup-capability'],text=True,timeout=30) if capability!='stage-generation-cleanup-v1': return False return subprocess.run(cli+[action],timeout=90).returncode==0 def main(): if os.getuid()!=0 or Path('/.dockerenv').exists(): raise ValueError('Host root only') os.umask(0o077) ROOT.mkdir(mode=0o700,exist_ok=True) st=ROOT.lstat() if ROOT.is_symlink() or st.st_uid!=0 or st.st_mode & 0o777 != 0o700: raise ValueError('Unsafe journal') worker=Worker(ROOT,run) if sys.argv[1:]==['sweep']: worker.sweep(int(time.time())); return if len(sys.argv)!=5 or os.environ.get('CI')!='true' or os.environ.get('STAGE_TEST_APPROVAL')!=APPROVAL: raise ValueError('CI grant required') sha,session,ttl,action=sys.argv[1:] i={'sha':sha,'session':session,'ttl':int(ttl),'generation':str(uuid.uuid4()),'due':int(time.time())+int(ttl)} validate(i) if action not in ('open','close'): raise ValueError('Action denied') with open(ROOT/'lock','a') as lock: fcntl.flock(lock,fcntl.LOCK_EX) # contention waits, never discards intent if action=='open': # Repeated opens cannot mint a new generation or renew TTL. worker.save(i) # Journal is durable before the first possible DB mutation. if not run(i,'open'): raise ValueError('Open failed; cleanup remains pending') else: p=ROOT/(session+'.json') fd=os.open(p,os.O_RDONLY|os.O_NOFOLLOW) with os.fdopen(fd) as f: i=json.load(f) validate(i) if run(i,'close'): p.unlink(); worker.sync() else: raise ValueError('Cleanup pending') if __name__=='__main__': try: main() except Exception: print('Stage principal denied or pending cleanup',file=sys.stderr); sys.exit(1)