105 lines
8.7 KiB
Python
105 lines
8.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Preserve a reviewed static payload across CI; never assert full restoration."""
|
|
from pathlib import Path,PurePosixPath
|
|
import argparse,gzip,hashlib,json,os,re,shutil,subprocess,sys,tarfile,tempfile
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
ROLES={'designer','creative_director','content_manager','illustrator','programmer_expert'}
|
|
DEPLOY_FILES=['Dockerfile','deploy/nginx.conf','deploy/legacy-map.conf','deploy/legacy-matchers.json','deploy/legacy-routes.json','deploy/serve-local.py','deploy/stack.yml','deploy/release-artifact.py','.gitea/workflows/master.yml']
|
|
def sha(b):return hashlib.sha256(b).hexdigest()
|
|
def hash_manifest(rows):return sha(json.dumps(rows,ensure_ascii=False,sort_keys=True,separators=(',',':')).encode())
|
|
def require(ok,message):
|
|
if not ok:raise ValueError(message)
|
|
def relative(name):
|
|
require(isinstance(name,str) and '\\' not in name,'Invalid path')
|
|
path=PurePosixPath(name)
|
|
require(not path.is_absolute() and '..' not in path.parts and str(path) not in ('','.'),'Unsafe path: '+name)
|
|
return path.as_posix()
|
|
def rooted(name):
|
|
path=ROOT/relative(name);require(not path.is_symlink(),'Symlink not allowed')
|
|
path.resolve().relative_to(ROOT.resolve());return path
|
|
def files(root):
|
|
rows=[]
|
|
for file in sorted(root.rglob('*')):
|
|
require(not file.is_symlink(),'Export symlink is forbidden')
|
|
if file.is_file():rows.append(dict(path=file.relative_to(root).as_posix(),sha256=sha(file.read_bytes()),bytes=file.stat().st_size))
|
|
require(rows and len(rows)<=10000,'Invalid export size/count');return rows
|
|
def checked_manifest(path,approvals):
|
|
m=json.loads(rooted(path).read_text());require(m.get('scope')=='reviewed-corpus-only' and m.get('historicalRestorationComplete') is False,'Incorrect release scope')
|
|
for field in ['sourceCommit','appSourceManifestSha256','exportManifestSha256','archiveSha256']:
|
|
require(bool(re.fullmatch('[0-9a-f]{'+('40' if field=='sourceCommit' else '64')+'}',m.get(field,''))),'Invalid '+field)
|
|
require(hash_manifest(m['files'])==m['exportManifestSha256'],'Export manifest mismatch')
|
|
require(hash_manifest(m['appSourceFiles'])==m['appSourceManifestSha256'],'App manifest mismatch')
|
|
for field in ['appSourceFiles','deploymentFiles']:
|
|
for row in m[field]:
|
|
f=rooted(row['path']);require(f.is_file() and sha(f.read_bytes())==row['sha256'],'Working source changed: '+row['path'])
|
|
revision=m['sourceCommit'] if field=='appSourceFiles' else m.get('deploymentSourceCommit',m['sourceCommit'])
|
|
r=subprocess.run(['git','show',revision+':'+row['path']],cwd=ROOT,capture_output=True)
|
|
require(r.returncode==0 and sha(r.stdout)==row['sha256'],'Built source unavailable/different: '+row['path'])
|
|
if approvals:
|
|
require(m.get('publicationDecision')=='ALLOW_LIMITED_PUBLICATION','Limited publication not approved')
|
|
found=set();agents=set()
|
|
for ref in m.get('roleApprovals',[]):
|
|
f=rooted(ref['path']);require(sha(f.read_bytes())==ref['sha256'],'Changed role approval');a=json.loads(f.read_text());role=a.get('role')
|
|
require(role in ROLES and role not in found,'Missing/duplicate/unknown role');found.add(role);agents.add(a.get('agent'))
|
|
require(a.get('decision')=='ALLOW_LIMITED_PUBLICATION' and a.get('fullHistoricalRestorationAccepted') is False,'Role veto or wrong scope: '+str(role))
|
|
require(a.get('candidateSourceCommit')==m['sourceCommit'] and a.get('exportManifestSha256')==m['exportManifestSha256'],'Role reviewed another artifact')
|
|
report=rooted(a['reportPath']);require(sha(report.read_bytes())==a['reportSha256'],'Changed role report')
|
|
require(found==ROLES and len(agents)==5 and None not in agents,'Five distinct actual role decisions required')
|
|
return m
|
|
def tar_rows(stream,expected,extract=None):
|
|
result=[];seen=set();total=0
|
|
with tarfile.open(fileobj=stream,mode='r|*') as archive:
|
|
for member in archive:
|
|
name=member.name
|
|
while name.startswith('./'):name=name[2:]
|
|
if member.isdir():
|
|
if name not in ('','.'):relative(name)
|
|
continue
|
|
require(member.isfile(),'Only regular export files allowed')
|
|
name=relative(name);require(name not in seen,'Duplicate file');seen.add(name)
|
|
require(name in expected,'Unexpected file: '+name)
|
|
total+=member.size;require(len(seen)<=10000 and 0<=member.size<=25*1024*1024 and total<=100*1024*1024,'Oversized export')
|
|
data=archive.extractfile(member).read();row=dict(path=name,sha256=sha(data),bytes=len(data));require(row==expected[name],'File mismatch: '+name);result.append(row)
|
|
if extract:
|
|
dest=extract/name;dest.parent.mkdir(parents=True,exist_ok=True);dest.write_bytes(data)
|
|
require(seen==set(expected),'Missing export files');return sorted(result,key=lambda r:r['path'])
|
|
def pack(args):
|
|
report=json.loads(rooted(args.report).read_text());require(report['summary']['errors']==0 and report['summary']['technicalStatus']=='passed','Technical verification required')
|
|
out=ROOT/'web-front/out';rows=files(out);require(hash_manifest(rows)==report['exportManifestSha256'],'Export differs from checked candidate')
|
|
revision=report['sourceCommit'];archive=rooted(args.archive);archive.parent.mkdir(parents=True,exist_ok=True)
|
|
with archive.open('wb') as raw,gzip.GzipFile(filename='',mode='wb',fileobj=raw,mtime=0) as zipped,tarfile.open(fileobj=zipped,mode='w|',format=tarfile.PAX_FORMAT) as tar:
|
|
for row in rows:
|
|
file=out/row['path'];info=tarfile.TarInfo(row['path']);info.size=row['bytes'];info.mode=0o644;info.mtime=0
|
|
with file.open('rb') as stream:tar.addfile(info,stream)
|
|
m=dict(schemaVersion=1,scope='reviewed-corpus-only',historicalRestorationComplete=False,publicationDecision='PENDING_FIVE_SCOPED_DECISIONS',sourceCommit=revision,appSourceManifestSha256=report['sourceManifestSha256'],appSourceFiles=report['sourceFiles'],deploymentSourceCommit=revision,deploymentFiles=[dict(path=f,sha256=sha(rooted(f).read_bytes())) for f in DEPLOY_FILES],exportManifestSha256=report['exportManifestSha256'],files=rows,archivePath=archive.relative_to(ROOT).as_posix(),archiveSha256=sha(archive.read_bytes()),roleApprovals=[],inventoryAtPack=report['summary']['inventoryItems'],unresolvedAtPack=report['summary']['unresolvedInventoryItems'])
|
|
rooted(args.manifest).parent.mkdir(parents=True,exist_ok=True);rooted(args.manifest).write_text(json.dumps(m,ensure_ascii=False,indent=2)+'\n');print(json.dumps(dict(source=revision,export=m['exportManifestSha256'],archiveBytes=archive.stat().st_size,files=len(rows),publicationDecision=m['publicationDecision'])))
|
|
def verify(args):
|
|
m=checked_manifest(args.manifest,not args.prepare_only);archive=rooted(m['archivePath']);require(sha(archive.read_bytes())==m['archiveSha256'],'Archive SHA mismatch');expected={r['path']:r for r in m['files']};require(len(expected)==len(m['files']),'Duplicate manifest path')
|
|
for path in expected:relative(path)
|
|
if args.restore:
|
|
out=ROOT/'web-front/out';out.parent.mkdir(exist_ok=True)
|
|
with tempfile.TemporaryDirectory(prefix='.reviewed-export-',dir=out.parent) as d:
|
|
dest=Path(d)
|
|
with archive.open('rb') as stream:rows=tar_rows(stream,expected,dest)
|
|
require(hash_manifest(rows)==m['exportManifestSha256'],'Payload hash mismatch');require(not out.is_symlink(),'Refuse symlink output')
|
|
if out.exists():shutil.rmtree(out)
|
|
shutil.copytree(dest,out)
|
|
else:
|
|
with archive.open('rb') as stream:rows=tar_rows(stream,expected)
|
|
require(hash_manifest(rows)==m['exportManifestSha256'],'Payload differs')
|
|
if args.tree:require(files(rooted(args.tree))==m['files'],'Public tree contains missing/extra/changed files')
|
|
print(json.dumps(dict(status='verified',scope=m['scope'],sourceCommit=m['sourceCommit'],exportManifestSha256=m['exportManifestSha256'],fullHistoricalRestorationAccepted=False,roleApprovals=len(m['roleApprovals']))))
|
|
def image_tar(args):
|
|
m=checked_manifest(args.manifest,not args.prepare_only);rows=tar_rows(sys.stdin.buffer,{r['path']:r for r in m['files']});require(hash_manifest(rows)==m['exportManifestSha256'],'Image public tree mismatch');print(json.dumps(dict(status='image-public-tree-identical',exportManifestSha256=m['exportManifestSha256'],files=len(rows))))
|
|
def main():
|
|
p=argparse.ArgumentParser();sub=p.add_subparsers(dest='action',required=True)
|
|
s=sub.add_parser('pack');s.add_argument('--report',required=True);s.add_argument('--manifest',required=True);s.add_argument('--archive',required=True)
|
|
for action in ['verify','image-tar']:
|
|
s=sub.add_parser(action);s.add_argument('--manifest',required=True);s.add_argument('--prepare-only',action='store_true',help='Candidate preparation only, forbidden for publication');
|
|
if action=='verify':s.add_argument('--restore',action='store_true');s.add_argument('--tree')
|
|
args=p.parse_args()
|
|
try:{'pack':pack,'verify':verify,'image-tar':image_tar}[args.action](args)
|
|
except (ValueError,OSError,KeyError,tarfile.TarError) as e:print(str(e),file=sys.stderr);return 1
|
|
return 0
|
|
if __name__=='__main__':sys.exit(main())
|