#!/usr/bin/env python3 """Independent review-ZIP exact inventory + detached-replay semantic digest. Sidecar nested ``status: pass`` is not evidence. Final claimed PASS requires exact VOLUME-MANIFEST inventory, a canonical ``replay_semantic`` object, and ``replay_semantic_sha256``. Inventory/path failures skip actual extract/replay. Dummy unit-test ZIPs without a source tree still run exact inventory and object/digest checks; they skip only the software rerun. """ from __future__ import annotations import hashlib import json import shutil import stat import tempfile import zipfile from pathlib import Path from typing import Any VOLUME_MANIFEST_MEMBERS = ( "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", "HANDOFF-METADATA/VOLUME-MANIFEST.json", ) OFFICIAL_MANIFEST_SCHEMA = "cpld-agent-analysis-volume-v1" COMPAT_MANIFEST_SCHEMA = "prod2u-volume-manifest-v1" ALLOWED_MANIFEST_SCHEMAS = frozenset({OFFICIAL_MANIFEST_SCHEMA, COMPAT_MANIFEST_SCHEMA}) SHA256_HEX = 64 class ArchivePathError(ValueError): """Unsafe or non-canonical ZIP member path.""" def parse_archive_member(name: str, *, directory: bool = False) -> str: """Canonical relative path. Reject rather than silently rewrite.""" raw = str(name or "") if not raw: raise ArchivePathError("empty") if "\x00" in raw: raise ArchivePathError("nul") if any(ord(ch) < 32 for ch in raw): raise ArchivePathError("control_char") if "\\" in raw: raise ArchivePathError("backslash") if raw.startswith("/") or raw.startswith("//"): raise ArchivePathError("absolute") if raw.startswith("\\\\") or raw.startswith("//"): raise ArchivePathError("unc") if len(raw) >= 2 and raw[1] == ":" and raw[0].isalpha(): raise ArchivePathError("windows_drive") trailing_dir = raw.endswith("/") body = raw[:-1] if trailing_dir else raw while body.startswith("./"): body = body[2:] if not body: raise ArchivePathError("empty") parts = body.split("/") if any(part in ("", ".", "..") for part in parts): raise ArchivePathError("dot_segment") if directory or trailing_dir: return body + "/" return body def _zip_info_is_symlink(info: zipfile.ZipInfo) -> bool: mode = (info.external_attr >> 16) & 0xFFFF if mode and stat.S_IFMT(mode) == stat.S_IFLNK: return True return False def _zip_info_is_special(info: zipfile.ZipInfo) -> bool: mode = (info.external_attr >> 16) & 0xFFFF if not mode: return False kind = stat.S_IFMT(mode) return kind not in (0, stat.S_IFREG, stat.S_IFDIR) def review_zip_has_source_tree(zip_path: Path) -> bool: try: with zipfile.ZipFile(zip_path) as zf: for raw in zf.namelist(): if raw.endswith("/"): continue try: name = parse_archive_member(raw) except ArchivePathError: continue if name.startswith("source/") or "/source/" in f"/{name}": return True except (OSError, zipfile.BadZipFile): return False return False def read_volume_manifest(zip_path: Path) -> dict[str, Any] | None: try: with zipfile.ZipFile(zip_path) as zf: names = list(zf.namelist()) hits = [member for member in VOLUME_MANIFEST_MEMBERS if member in names] if len(hits) != 1: return None doc = json.loads(zf.read(hits[0]).decode("utf-8")) if isinstance(doc, dict): return doc except (OSError, zipfile.BadZipFile, json.JSONDecodeError, UnicodeDecodeError): return None return None def _int_or_none(value: Any) -> int | None: if isinstance(value, bool) or value is None: return None try: return int(value) except (TypeError, ValueError): return None def _looks_sha256(value: Any) -> str: text = str(value or "").strip().lower() if len(text) != SHA256_HEX: return "" if any(ch not in "0123456789abcdef" for ch in text): return "" return text def semantic_sha256(obj: dict[str, Any]) -> str: blob = json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode( "utf-8" ) return hashlib.sha256(blob).hexdigest() def inventory_digest(inventory: dict[str, Any]) -> str: body = { "volume_manifest_member": inventory.get("volume_manifest_member"), "volume_manifest_schema": inventory.get("volume_manifest_schema"), "volume_manifest_sha256": inventory.get("volume_manifest_sha256"), "inventory_file_count": inventory.get("inventory_file_count"), "inventory_member_count": inventory.get("inventory_member_count"), "inventory_uncompressed_bytes": inventory.get("inventory_uncompressed_bytes"), "inventory_rows": inventory.get("inventory_rows") or [], } return semantic_sha256(body) def semantic_object( *, content: dict[str, Any], software: dict[str, Any], inventory: dict[str, Any] | None = None, ) -> dict[str, Any]: """Canonical subset used for sidecar vs nested vs actual-rerun comparison.""" unit = software.get("unit") if isinstance(software.get("unit"), dict) else {} modules: list[dict[str, Any]] = [] raw_modules = unit.get("modules") if isinstance(unit.get("modules"), list) else [] for mod in raw_modules: if not isinstance(mod, dict): continue modules.append( { "module": str(mod.get("module") or ""), "status": str(mod.get("status") or ""), "returncode": _int_or_none(mod.get("returncode")), } ) modules.sort(key=lambda row: row["module"]) layout = software.get("layout") if isinstance(software.get("layout"), dict) else {} checks = layout.get("checks") if isinstance(layout.get("checks"), dict) else {} provenance = ( software.get("provenance") if isinstance(software.get("provenance"), dict) else {} ) board = software.get("board") if isinstance(software.get("board"), dict) else {} obj: dict[str, Any] = { "checked_files": _int_or_none(content.get("checked_files")) or 0, "git_mode": str(software.get("git_mode") or ""), "layout_status": str(layout.get("status") or ""), "layout_checks": {str(k): checks.get(k) is True for k in sorted(checks)}, "provenance": { "status": str(provenance.get("status") or ""), "head_txt": provenance.get("head_txt") is True, "tree_manifest": provenance.get("tree_manifest") is True, "sanitized_snapshot_status": provenance.get("sanitized_snapshot_status") is True, "raw_git_required": provenance.get("raw_git_required") is True, }, "unit_status": str(unit.get("status") or ""), "unit_modules": modules, "board": { "status": str(board.get("status") or ""), "mode": str(board.get("mode") or ""), "returncode": _int_or_none(board.get("returncode")), "reference_regeneration_replay": str( board.get("reference_regeneration_replay") or "" ), }, "software_status": str(software.get("status") or ""), "volume_manifest_sha256": "", "inventory_digest": "", "inventory_file_count": 0, "inventory_member_count": 0, } if inventory: obj["volume_manifest_sha256"] = str(inventory.get("volume_manifest_sha256") or "") obj["inventory_digest"] = str(inventory.get("inventory_digest") or "") obj["inventory_file_count"] = int(inventory.get("inventory_file_count") or 0) obj["inventory_member_count"] = int(inventory.get("inventory_member_count") or 0) obj["checked_files"] = int(inventory.get("inventory_file_count") or 0) return obj def stamp_replay_semantic( report: dict[str, Any], *, zip_path: Path | None = None, ) -> dict[str, Any]: content = report.get("package_content") if isinstance(report.get("package_content"), dict) else {} software = ( report.get("detached_software") if isinstance(report.get("detached_software"), dict) else {} ) inventory = None if zip_path is not None: failures, inventory = verify_exact_inventory(zip_path) if failures: report["inventory_stamp_failures"] = list(failures) inventory = None elif inventory is not None: content["checked_files"] = int(inventory["inventory_file_count"]) obj = semantic_object(content=content, software=software, inventory=inventory) report["replay_semantic"] = obj report["replay_semantic_sha256"] = semantic_sha256(obj) if inventory is not None: report["volume_manifest_sha256"] = inventory["volume_manifest_sha256"] report["inventory_digest"] = inventory["inventory_digest"] report["inventory_file_count"] = inventory["inventory_file_count"] report["inventory_member_count"] = inventory["inventory_member_count"] return report def align_checked_files_to_manifest(content: dict[str, Any], zip_path: Path) -> None: """Force package_content.checked_files to VOLUME-MANIFEST.file_count.""" _failures, inventory = verify_exact_inventory(zip_path) if inventory is None: return content["checked_files"] = int(inventory["inventory_file_count"]) def _ordinary_zip_members(zf: zipfile.ZipFile) -> tuple[list[str], list[str]]: """Return (canonical ordinary file members, failure codes).""" failures: list[str] = [] ordinary: list[str] = [] seen_raw: list[str] = [] for info in zf.infolist(): raw = info.filename seen_raw.append(raw) if info.is_dir() or raw.endswith("/"): try: parse_archive_member(raw, directory=True) except ArchivePathError: failures.append("replay_archive_unsafe_path") continue if _zip_info_is_symlink(info) or _zip_info_is_special(info): failures.append("replay_archive_non_regular_member") continue try: name = parse_archive_member(raw) except ArchivePathError: failures.append("replay_archive_unsafe_path") continue ordinary.append(name) if len(seen_raw) != len(set(seen_raw)): failures.append("replay_archive_duplicate_member") if len(ordinary) != len(set(ordinary)): failures.append("replay_archive_duplicate_member") folded = [n.casefold() for n in ordinary] if len(folded) != len(set(folded)): failures.append("replay_volume_manifest_casefold_collision") return ordinary, list(dict.fromkeys(failures)) def verify_exact_inventory(zip_path: Path) -> tuple[list[str], dict[str, Any] | None]: """Exact VOLUME-MANIFEST inventory. Fail-closed; never silently rewrite paths.""" failures: list[str] = [] try: zf_ctx = zipfile.ZipFile(zip_path) except (OSError, zipfile.BadZipFile): return ["replay_volume_manifest_inventory_mismatch"], None with zf_ctx as zf: ordinary, path_failures = _ordinary_zip_members(zf) failures.extend(path_failures) ordinary_set = set(ordinary) present_manifests = [m for m in VOLUME_MANIFEST_MEMBERS if m in ordinary_set] if len(present_manifests) == 0: failures.append("replay_volume_manifest_missing") return list(dict.fromkeys(failures)), None if len(present_manifests) != 1: failures.append("replay_volume_manifest_duplicate_alias") return list(dict.fromkeys(failures)), None manifest_member = present_manifests[0] try: manifest_bytes = zf.read(manifest_member) manifest = json.loads(manifest_bytes.decode("utf-8")) except (KeyError, UnicodeDecodeError, json.JSONDecodeError): failures.append("replay_volume_manifest_missing") return list(dict.fromkeys(failures)), None if not isinstance(manifest, dict): failures.append("replay_volume_manifest_missing") return list(dict.fromkeys(failures)), None schema = str(manifest.get("schema") or "") if schema not in ALLOWED_MANIFEST_SCHEMAS: failures.append("replay_volume_manifest_schema_invalid") files = manifest.get("files") if not isinstance(files, list): failures.append("replay_volume_manifest_inventory_mismatch") return list(dict.fromkeys(failures)), None claimed_count = _int_or_none(manifest.get("file_count")) if claimed_count is None or claimed_count < 0: failures.append("replay_volume_manifest_missing") return list(dict.fromkeys(failures)), None if claimed_count != len(files): failures.append("replay_volume_manifest_file_count_mismatch") if schema == OFFICIAL_MANIFEST_SCHEMA: package_name = str(manifest.get("package_name") or "").strip() volume_number = _int_or_none(manifest.get("volume_number")) volume_count = _int_or_none(manifest.get("volume_count")) if not package_name: failures.append("replay_volume_manifest_schema_invalid") if volume_number is None or volume_number < 1: failures.append("replay_volume_manifest_schema_invalid") if volume_count is None or volume_count < 1: failures.append("replay_volume_manifest_schema_invalid") rows: list[dict[str, Any]] = [] row_paths: list[str] = [] row_folded: list[str] = [] size_sum = 0 for row in files: if not isinstance(row, dict): failures.append("replay_volume_manifest_inventory_mismatch") continue if "path" in row and "archive_path" not in row: failures.append("replay_volume_manifest_row_missing_archive_path") continue if "archive_path" not in row: failures.append("replay_volume_manifest_row_missing_archive_path") continue if "size" not in row: failures.append("replay_volume_manifest_row_missing_size") continue if "sha256" not in row: failures.append("replay_volume_manifest_row_missing_sha256") continue try: rel = parse_archive_member(str(row.get("archive_path") or "")) except ArchivePathError: failures.append("replay_archive_unsafe_path") continue if rel.endswith("/"): failures.append("replay_volume_manifest_row_directory") continue if rel == manifest_member: failures.append("replay_volume_manifest_self_listed") continue size = _int_or_none(row.get("size")) if size is None or size < 0: failures.append("replay_volume_manifest_row_invalid_size") continue sha = _looks_sha256(row.get("sha256")) if not sha: failures.append("replay_volume_manifest_row_invalid_sha256") continue if rel not in ordinary_set: failures.append("replay_volume_manifest_listed_missing") continue data = zf.read(rel) if size != len(data): failures.append("replay_volume_manifest_size_mismatch") continue if sha != hashlib.sha256(data).hexdigest(): failures.append("replay_volume_manifest_hash_mismatch") continue row_paths.append(rel) row_folded.append(rel.casefold()) size_sum += size rows.append({"archive_path": rel, "size": size, "sha256": sha}) if len(row_paths) != len(set(row_paths)): failures.append("replay_volume_manifest_duplicate_path") if len(row_folded) != len(set(row_folded)): failures.append("replay_volume_manifest_casefold_collision") expected = set(row_paths) | {manifest_member} extra = ordinary_set - expected missing = set(row_paths) - ordinary_set if extra: failures.append("replay_volume_manifest_unmanifested_extra") if missing: failures.append("replay_volume_manifest_listed_missing") uncompressed = _int_or_none(manifest.get("uncompressed_bytes")) if schema == OFFICIAL_MANIFEST_SCHEMA: if uncompressed is None: failures.append("replay_volume_manifest_uncompressed_bytes_mismatch") elif uncompressed != size_sum: failures.append("replay_volume_manifest_uncompressed_bytes_mismatch") elif uncompressed is not None and uncompressed != size_sum: failures.append("replay_volume_manifest_uncompressed_bytes_mismatch") failures = list(dict.fromkeys(failures)) if failures: return failures, None inventory = { "volume_manifest_member": manifest_member, "volume_manifest_schema": schema, "volume_manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(), "inventory_file_count": claimed_count, "inventory_member_count": len(ordinary_set), "inventory_uncompressed_bytes": size_sum, "inventory_rows": sorted(rows, key=lambda r: r["archive_path"]), } inventory["inventory_digest"] = inventory_digest(inventory) return [], inventory def verify_volume_manifest_inventory(zip_path: Path) -> list[str]: failures, _inventory = verify_exact_inventory(zip_path) return failures def safe_extract_zip(zip_path: Path, dest: Path) -> list[Path]: """Extract regular files only after strict path validation. No extractall.""" failures, inventory = verify_exact_inventory(zip_path) if failures or inventory is None: raise ValueError("unsafe or inexact archive inventory: " + ",".join(failures)) allowed = {row["archive_path"] for row in inventory["inventory_rows"]} allowed.add(inventory["volume_manifest_member"]) dest.mkdir(parents=True, exist_ok=False) dest_res = dest.resolve() written: list[Path] = [] with zipfile.ZipFile(zip_path) as zf: for info in zf.infolist(): if info.is_dir() or info.filename.endswith("/"): continue name = parse_archive_member(info.filename) if name not in allowed: raise ValueError(f"extract of non-inventory member: {info.filename!r}") target = dest / Path(*name.split("/")) resolved = target.resolve() if dest_res not in resolved.parents and resolved != dest_res: raise ValueError(f"zip-slip archive member: {info.filename!r}") target.parent.mkdir(parents=True, exist_ok=True) with zf.open(info, "r") as source, target.open("wb") as out: shutil.copyfileobj(source, out, length=1024 * 1024) written.append(target) return written def _run_actual_software_replay(zip_path: Path) -> dict[str, Any]: try: from replay_review_compact import resolve_cpld_root, run_detached_software_replay except ImportError: from tools.replay_review_compact import ( # type: ignore resolve_cpld_root, run_detached_software_replay, ) tmp = Path(tempfile.mkdtemp(prefix="prod2u-replay-bind-")) try: dest = tmp / "from-zip" safe_extract_zip(zip_path, dest) cpld = resolve_cpld_root(dest) return run_detached_software_replay(cpld) finally: shutil.rmtree(tmp, ignore_errors=True) def _field_mismatches(claimed: dict[str, Any], actual: dict[str, Any]) -> list[str]: failures: list[str] = [] if claimed["unit_modules"] != actual["unit_modules"] or claimed["unit_status"] != actual["unit_status"]: failures.append("replay_semantic_unit_mismatch") if claimed["layout_checks"] != actual["layout_checks"] or claimed["layout_status"] != actual["layout_status"]: failures.append("replay_semantic_layout_mismatch") if claimed["provenance"] != actual["provenance"]: failures.append("replay_semantic_provenance_mismatch") if claimed["board"] != actual["board"]: failures.append("replay_semantic_board_mismatch") if claimed["software_status"] != actual["software_status"]: failures.append("replay_semantic_software_status_mismatch") if claimed["git_mode"] and actual["git_mode"] and claimed["git_mode"] != actual["git_mode"]: failures.append("replay_semantic_git_mode_mismatch") if claimed["checked_files"] != actual["checked_files"]: failures.append("replay_semantic_checked_files_mismatch") if claimed.get("volume_manifest_sha256") != actual.get("volume_manifest_sha256"): failures.append("replay_semantic_inventory_mismatch") if claimed.get("inventory_digest") != actual.get("inventory_digest"): failures.append("replay_semantic_inventory_mismatch") if claimed.get("inventory_file_count") != actual.get("inventory_file_count"): failures.append("replay_semantic_inventory_mismatch") if claimed.get("inventory_member_count") != actual.get("inventory_member_count"): failures.append("replay_semantic_inventory_mismatch") return list(dict.fromkeys(failures)) def bind_independent_replay(zip_path: Path, sidecar: dict[str, Any]) -> list[str]: """Four-way bind: sidecar object, digest, nested evidence, actual ZIP. Dummy ZIPs without a source tree skip only the independent software rerun. Inventory/path failures never continue into extract/replay. """ failures, inventory = verify_exact_inventory(zip_path) content = sidecar.get("package_content") if isinstance(sidecar.get("package_content"), dict) else {} claimed_sw = ( sidecar.get("detached_software") if isinstance(sidecar.get("detached_software"), dict) else {} ) nested = semantic_object(content=content, software=claimed_sw, inventory=inventory) sidecar_obj = sidecar.get("replay_semantic") if not isinstance(sidecar_obj, dict) or not sidecar_obj: failures.append("replay_semantic_missing") sidecar_obj = None claimed_digest = str(sidecar.get("replay_semantic_sha256") or "").strip().lower() if not claimed_digest: failures.append("replay_semantic_sha256_missing") elif sidecar_obj is not None: recomputed = semantic_sha256(sidecar_obj) if claimed_digest != recomputed: failures.append("replay_semantic_sha256_mismatch") if sidecar_obj is not None and sidecar_obj != nested: failures.append("replay_semantic_nested_mismatch") failures.extend(_field_mismatches(sidecar_obj, nested)) if inventory is None or any( code.startswith("replay_volume_manifest_") or code.startswith("replay_archive_") for code in failures ): return list(dict.fromkeys(failures)) if sidecar_obj is not None: failures.extend(_field_mismatches(sidecar_obj, nested)) if not review_zip_has_source_tree(zip_path): return list(dict.fromkeys(failures)) try: actual_software = _run_actual_software_replay(zip_path) except Exception: # noqa: BLE001 — bind must fail-closed, not raise failures.append("replay_actual_rerun_error") return list(dict.fromkeys(failures)) if str(actual_software.get("status") or "").casefold() != "pass": failures.append("replay_actual_rerun_not_pass") actual = semantic_object(content=content, software=actual_software, inventory=inventory) if sidecar_obj is not None and sidecar_obj != actual: failures.append("replay_semantic_actual_mismatch") failures.extend(_field_mismatches(sidecar_obj, actual)) failures.extend(_field_mismatches(nested, actual)) return list(dict.fromkeys(failures))