"""Build and verify an exact review snapshot of public working-tree files.""" import argparse import base64 import hashlib import json import re import subprocess import tempfile import zipfile from pathlib import Path from bao_operator import RECOVERY, protect ROOT = Path(__file__).resolve().parents[1] EVIDENCE = ROOT / "evidence" / "grade3" OMIT = {"PR_GRADE3_DRAFT.md"} PRIVATE_DIRS = {".git", "secrets", "certs", "volumes", "data", "backups", ".venv", "__pycache__", "dist", "build", "node_modules"} PRIVATE_SUFFIXES = {".key", ".pem", ".crt", ".p12", ".pfx", ".dpapi", ".zip", ".pyc", ".log"} SECRET_PATTERNS = re.compile(rb"-----BEGIN [A-Z ]*PRIVATE KEY-----|(?i:Bearer )[A-Za-z0-9_-]{43}\b") MODES = {".sh": 0o100755} def git(*args): return subprocess.check_output(["git", *args], cwd=ROOT) def names(*args): return {p.decode("utf-8") for p in git(*args).split(b"\0") if p} def public_files(): paths = names("ls-files", "--cached", "--others", "--exclude-standard", "-z") - OMIT for path in sorted(paths): relative = Path(path) file = ROOT / relative if set(relative.parts) & PRIVATE_DIRS or relative.suffix.lower() in PRIVATE_SUFFIXES: raise RuntimeError(f"Private/build candidate in archive list: {path}") if relative.name.startswith(".env") and relative.name != ".env.example": raise RuntimeError(f"Private environment file selected: {path}") if file.is_symlink() or not file.is_file() or not file.resolve().is_relative_to(ROOT): raise RuntimeError(f"Unexpected filesystem path: {path}") yield path, file def runtime_secrets(): private = ROOT / "secrets" paths = [*private.glob("postgres/pg_*"), *private.glob("s3/*"), *private.glob("broker/*"), *private.glob("telemetry/*"), private / "s3-admin/password", private / "grafana/password"] values = {p.read_bytes().strip() for p in paths if p.is_file() and p.suffix != ".json"} for role in ("api", "worker", "collector", "grafana"): value = (private / "telemetry" / role).read_bytes().strip() values.add(base64.b64encode(role.encode() + b":" + value)) if RECOVERY.exists(): recovery = json.loads(protect(RECOVERY.read_bytes(), "Unprotect")) values.update(s.encode() for s in (*recovery["keys"], *recovery["keys_base64"], recovery["root_token"])) return {value for value in values if len(value) >= 20} def scan(files, secrets): for name, data in files: if SECRET_PATTERNS.search(data) or any(secret in data for secret in secrets): raise RuntimeError(f"Secret signature in {name} (value withheld)") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) output = parser.parse_args().archive.resolve() if output.is_relative_to(ROOT): raise SystemExit("Choose an archive destination outside the checkout") secrets = runtime_secrets() files = list(public_files()) scan(((name, path.read_bytes()) for name, path in files), secrets) runtime = subprocess.check_output(["docker", "compose", "--project-name", "mtusi-lab7-grade3", "logs", "--no-color"], cwd=ROOT, stderr=subprocess.STDOUT) scan([("Compose logs", runtime)], secrets) (EVIDENCE / "secrets-scan.txt").write_text( f"PASS: public artifact bytes and project Compose logs checked against {len(secrets)} local secret literals " "and private-key/Bearer patterns. No matches.\n", encoding="utf-8", ) files = list(public_files()) metadata = [] output.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=8) as archive: for name, path in files: data = path.read_bytes() spec = zipfile.ZipInfo(name) spec.create_system = 3 mode = MODES.get(path.suffix, 0o100644) spec.external_attr = mode << 16 spec.compress_type = zipfile.ZIP_DEFLATED if mode == 0o100755 and ".example." not in name: assert b"\r" not in data and data.startswith(b"#!/"), name archive.writestr(spec, data, compresslevel=8) metadata.append({"file": name, "sha256": hashlib.sha256(data).hexdigest(), "mode": oct(mode)[2:]}) with zipfile.ZipFile(output) as archive, tempfile.TemporaryDirectory(prefix="lab7-zip-") as directory: assert archive.testzip() is None archive.extractall(directory) assert sorted(archive.namelist()) == sorted(name for name, _ in files) for name, path in files: assert (Path(directory) / name).read_bytes() == path.read_bytes() assert archive.getinfo(name).external_attr >> 16 == MODES.get(path.suffix, 0o100644) changes = (names("diff", "--name-only", "-z") | names("ls-files", "--others", "--exclude-standard", "-z")) - OMIT payload = {"archive": output.name, "sha256": hashlib.sha256(output.read_bytes()).hexdigest(), "files": len(files), "crc": "PASS", "unzip_byte_comparison": "PASS", "manifest": metadata} output.with_suffix(".manifest.json").write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") output.with_suffix(".staging.txt").write_text("\n".join(sorted(changes)) + "\n", encoding="utf-8") print(json.dumps({k: v for k, v in payload.items() if k != "manifest"})) if __name__ == "__main__": main()