#!/usr/bin/env python3 """Verify the complete repository payload against PACKAGE_MANIFEST.json.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path, PurePosixPath import re import sys def verify(root: Path) -> int: root = root.resolve() manifest = root / "PACKAGE_MANIFEST.json" if manifest.is_symlink() or not manifest.is_file(): raise ValueError("PACKAGE_MANIFEST.json must be a regular file") data = json.loads(manifest.read_text(encoding="utf-8")) if not isinstance(data, dict) or type(data.get("schema_version")) is not int or data.get("schema_version") != 1 or not isinstance(data.get("files"), list): raise ValueError("Unsupported manifest schema") expected = {} for record in data["files"]: if not isinstance(record, dict): raise ValueError("Invalid manifest file record") name = record.get("path") if not isinstance(name, str) or not name or "\\" in name: raise ValueError("Invalid manifest path") path = PurePosixPath(name) if path.is_absolute() or any(p in (".", "..") for p in path.parts) or str(path) != name: raise ValueError("Unsafe or noncanonical manifest path: " + name) if name == "PACKAGE_MANIFEST.json" or name in expected: raise ValueError("Duplicate or self-referencing manifest entry: " + name) if not re.fullmatch(r"[0-9a-f]{64}", str(record.get("sha256", ""))): raise ValueError("Invalid SHA-256 entry: " + name) size = record.get("size_bytes") if not isinstance(size, int) or isinstance(size, bool) or size < 0: raise ValueError("Invalid size entry: " + name) expected[name] = record actual = set() for path in root.rglob("*"): name = path.relative_to(root).as_posix() if path.is_symlink(): raise ValueError("Symlinks are not permitted: " + name) if path.is_file() and name != "PACKAGE_MANIFEST.json": actual.add(name) elif not path.is_file() and not path.is_dir(): raise ValueError("Nonregular filesystem entry: " + name) if actual != set(expected): raise ValueError("Payload mismatch; missing=" + repr(sorted(set(expected) - actual)) + "; unexpected=" + repr(sorted(actual - set(expected)))) for name, record in sorted(expected.items()): path = root / name if not path.resolve().is_relative_to(root): raise ValueError("Path escapes repository: " + name) if path.stat().st_size != record["size_bytes"]: raise ValueError("Size mismatch: " + name) digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) if digest.hexdigest() != record["sha256"]: raise ValueError("SHA-256 mismatch: " + name) print(f"Integrity verified: {len(expected)} payload files; no unexpected files or symlinks.") return len(expected) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) args = parser.parse_args() try: verify(args.root) except (OSError, ValueError, TypeError, KeyError) as exc: print("Integrity verification failed: " + str(exc), file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())