#!/usr/bin/env python3 """CI-only exact editorial ownership migration; run inside container UID namespace. No profiles, general caches, provider credentials or mode changes are permitted. Caller must serialize with deployment; never run alongside an editorial runner. """ import json import os from pathlib import Path import stat PROFILES=('pmo','canina-competitor-worker','canina-seo-worker','canina-content-worker','canina-vet-review-worker','canina-qa-worker') PACKAGE={'bundle.json','installer.py','client.py','runner.py','model-policy.json','payload/editorial-v4/status.json'} | {f'payload/profiles/{p}/skills/canina-editorial-v4/{f}' for p in PROFILES for f in ('SKILL.md','references/policy.md','references/role.json')} LEAVES={'editorial-v4/owner-proposal.json','editorial-v4/status.json','editorial-v4/deployment.json','editorial-v4/credentials/editorial-pmo-token','editorial-v4/.installer/lock','editorial-v4/.installer/transaction.json'} | {'editorial-v4/runtime-package/'+f for f in PACKAGE} | {f'profiles/{p}/skills/canina-editorial-v4/{f}' for p in PROFILES for f in ('SKILL.md','references/policy.md','references/role.json')} # State names are taken from the reviewed clients, not arbitrary directory trees. STATE_ROOTS={'editorial-v4/runner-state','editorial-v4/client-state'} | {f'profiles/{p}/cache/editorial-runner' for p in PROFILES} DIRS={str(p) for f in LEAVES for p in Path(f).parents if str(p)!='.' and (str(p).startswith('editorial-v4') or '/skills/canina-editorial-v4' in str(p))} | STATE_ROOTS def allowed(relative,isdir): if relative in DIRS if isdir else relative in LEAVES:return True # Runner-created state is limited to immediate regular files, never subtrees. p=Path(relative) return not isdir and str(p.parent) in STATE_ROOTS and p.name in ('lock','proposal.json') def scan(home,uid,gid): if not home.is_absolute() or home.is_symlink():raise ValueError('Canonical home required') result=[] roots=[home/'editorial-v4']+[home/f'profiles/{p}/skills/canina-editorial-v4' for p in PROFILES]+[home/r for r in STATE_ROOTS if r.startswith('profiles/')] for root in roots: for ancestor in root.parents: if ancestor.is_symlink():raise ValueError('Symlink ancestor') if not root.exists() and not root.is_symlink():continue for p in [root,*sorted(root.rglob('*'))]: s=p.lstat();r=str(p.relative_to(home));directory=stat.S_ISDIR(s.st_mode) if not (directory or stat.S_ISREG(s.st_mode)) or not allowed(r,directory) or (not directory and s.st_nlink!=1):raise ValueError('Unreviewed editorial path') mode=stat.S_IMODE(s.st_mode) if (s.st_uid,s.st_gid) not in ((0,0),(uid,gid)) or mode & 0o7022:raise ValueError('Unexpected owner or writable mode') if '/credentials/' in r and mode!=0o400:raise ValueError('Private credential required') result.append({'path':r,'uid':s.st_uid,'gid':s.st_gid,'mode':mode,'dev':s.st_dev,'ino':s.st_ino}) return result def check(home,row): p=home/row['path'];s=p.lstat() if (s.st_dev,s.st_ino,stat.S_IMODE(s.st_mode))!=(row['dev'],row['ino'],row['mode']):raise ValueError('Ownership migration conflict') return p def rollback(home,journal): s=journal.lstat() if not stat.S_ISREG(s.st_mode) or s.st_uid!=0 or stat.S_IMODE(s.st_mode)!=0o600 or s.st_nlink!=1:raise ValueError('Private journal required') state=json.loads(journal.read_text()) if state['home']!=str(home):raise ValueError('Journal home mismatch') rows=state['before'] # Full preflight before restoring; never follow changed paths. current=scan(home,state['uid'],state['gid']) if {r['path'] for r in current}!={r['path'] for r in rows}:raise ValueError('Rollback path conflict') for row in rows:check(home,row) for row in reversed(rows):os.chown(check(home,row),row['uid'],row['gid'],follow_symlinks=False) journal.unlink() def migrate(home,uid,gid,journal): if os.getuid()!=0 or (uid,gid)!=(10000,10000):raise ValueError('Container root and canonical hermes identity required') rows=scan(home,uid,gid) if journal.exists(): s=journal.lstat() if not stat.S_ISREG(s.st_mode) or s.st_uid!=0 or stat.S_IMODE(s.st_mode)!=0o600 or s.st_nlink!=1:raise ValueError('Private journal required') old=json.loads(journal.read_text()) if old['home']!=str(home) or old['uid']!=uid or old['gid']!=gid:raise ValueError('Journal mismatch') if all((r['uid'],r['gid'])==(uid,gid) for r in rows):return raise ValueError('Incomplete migration: rollback first') state={'home':str(home),'uid':uid,'gid':gid,'before':rows} fd=os.open(journal,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600) with os.fdopen(fd,'w') as f:json.dump(state,f);f.flush();os.fsync(f.fileno()) try: for row in rows:os.chown(check(home,row),uid,gid,follow_symlinks=False) except BaseException: rollback(home,journal) raise