Files
mtusi2026lab2/evidence/grade5/package_review.py
T

44 lines
3.1 KiB
Python

#!/usr/bin/env python3
"""Create a review ZIP entirely under the repo; never stages or publishes anything."""
import datetime, hashlib, json, stat, zipfile
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2];E=ROOT/'evidence/grade5'
EXCLUDE={'.git','.grade5-work','.env','secrets','cache','volumes','.venv','__pycache__','node_modules','data','backups'}
RECORD='evidence/grade5/review-archive.json';INVENTORY='evidence/grade5/review-inventory.json'
def allowed(p):
rel=p.relative_to(ROOT)
return p.is_file() and not any(v in EXCLUDE for v in rel.parts) and not p.name.startswith('review-grade5') and p.suffix not in ['.pyc','.pyo','.log','.key','.pem','.p12','.pfx'] and not (p.name.startswith('.env.') and p.name!='.env.example') and rel.as_posix() not in [RECORD,INVENTORY]
def sha(data):return hashlib.sha256(data).hexdigest()
def main():
files=sorted(p for p in ROOT.rglob('*') if allowed(p));manifest={p.relative_to(ROOT).as_posix():sha(p.read_bytes()) for p in files}
(ROOT/INVENTORY).write_text(json.dumps({'files_sha256':manifest,'excluded_metadata':[RECORD,INVENTORY],'note':'Inventory omits its own hash and external archive checksum record to avoid self-reference. All source/raw bytes preserved.'},indent=2),encoding='utf-8')
files.append(ROOT/INVENTORY)
target=ROOT/'review-grade5-2026-10-25.zip'
with zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED,compresslevel=6) as archive:
for f in files:
info=zipfile.ZipInfo.from_file(f,f.relative_to(ROOT).as_posix());info.create_system=3
mode=0o755 if f.suffix=='.sh' else 0o644
info.external_attr=(stat.S_IFREG|mode)<<16
info.compress_type=zipfile.ZIP_DEFLATED
archive.writestr(info,f.read_bytes())
configured=[]
for folder in [ROOT/'secrets',*(ROOT/'.grade5-work').glob('*/secrets')]:
if folder.exists():
for f in folder.iterdir():
if f.is_file():
value=f.read_bytes().strip()
if len(value)>=24:configured.append(value)
with zipfile.ZipFile(target) as archive:
assert archive.testzip() is None
for entry in archive.infolist():
assert not any(p in EXCLUDE for p in Path(entry.filename).parts),entry.filename
content=archive.read(entry)
assert not any(v in content for v in configured),'private value in '+entry.filename
if entry.filename in manifest:assert sha(content)==manifest[entry.filename]
modes={n:oct((archive.getinfo(n).external_attr>>16)&0o777) for n in ['scripts/init-env.sh','scripts/restart.sh','scripts/run-checks.sh']}
assert all(v=='0o755' for v in modes.values())
record={'archive':target.name,'sha256':sha(target.read_bytes()),'bytes':target.stat().st_size,'file_count':len(files),'scripts_modes':modes,'verified':'CRC, every source/raw SHA, exclusions and configured secrets checked; no Git writes','metadata_outside_zip':RECORD}
(ROOT/RECORD).write_text(json.dumps(record,indent=2),encoding='utf-8')
print(json.dumps(record,indent=2))
if __name__=='__main__':main()