|
|
@@ -1,19 +1,19 @@
|
|
|
#!/usr/bin/env python3
|
|
|
-"""Independent review-ZIP inventory + detached-replay semantic digest.
|
|
|
+"""Independent review-ZIP exact inventory + detached-replay semantic digest.
|
|
|
|
|
|
-Sidecar nested ``status: pass`` is not evidence. When the ZIP contains a
|
|
|
-``source/`` tree, release-validation safe-extracts the actual bytes, reruns
|
|
|
-``run_detached_software_replay`` on the extracted CPLD root, and compares a
|
|
|
-canonical semantic object (and optional ``replay_semantic_sha256``) to the
|
|
|
-external sidecar. Dummy unit-test ZIPs without source skip the rerun.
|
|
|
+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 re
|
|
|
import shutil
|
|
|
+import stat
|
|
|
import tempfile
|
|
|
import zipfile
|
|
|
from pathlib import Path
|
|
|
@@ -23,18 +23,71 @@ 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 _norm_member(name: str) -> str:
|
|
|
- return str(name or "").replace("\\", "/").lstrip("./")
|
|
|
+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():
|
|
|
- name = _norm_member(raw)
|
|
|
- if name.endswith("/"):
|
|
|
+ if raw.endswith("/"):
|
|
|
+ continue
|
|
|
+ try:
|
|
|
+ name = parse_archive_member(raw)
|
|
|
+ except ArchivePathError:
|
|
|
continue
|
|
|
if name.startswith("source/") or "/source/" in f"/{name}":
|
|
|
return True
|
|
|
@@ -46,29 +99,63 @@ def review_zip_has_source_tree(zip_path: Path) -> bool:
|
|
|
def read_volume_manifest(zip_path: Path) -> dict[str, Any] | None:
|
|
|
try:
|
|
|
with zipfile.ZipFile(zip_path) as zf:
|
|
|
- names = set(zf.namelist())
|
|
|
- for member in VOLUME_MANIFEST_MEMBERS:
|
|
|
- if member not in names:
|
|
|
- continue
|
|
|
- doc = json.loads(zf.read(member).decode("utf-8"))
|
|
|
- if isinstance(doc, dict):
|
|
|
- return doc
|
|
|
+ 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:
|
|
|
- if value is None:
|
|
|
- return None
|
|
|
return int(value)
|
|
|
except (TypeError, ValueError):
|
|
|
return None
|
|
|
|
|
|
|
|
|
-def semantic_object(*, content: dict[str, Any], software: dict[str, Any]) -> dict[str, Any]:
|
|
|
- """Canonical subset used for sidecar vs actual-rerun comparison."""
|
|
|
+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 []
|
|
|
@@ -89,7 +176,7 @@ def semantic_object(*, content: dict[str, Any], software: dict[str, Any]) -> dic
|
|
|
software.get("provenance") if isinstance(software.get("provenance"), dict) else {}
|
|
|
)
|
|
|
board = software.get("board") if isinstance(software.get("board"), dict) else {}
|
|
|
- return {
|
|
|
+ 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 ""),
|
|
|
@@ -112,14 +199,18 @@ def semantic_object(*, content: dict[str, Any], software: dict[str, Any]) -> dic
|
|
|
),
|
|
|
},
|
|
|
"software_status": str(software.get("status") or ""),
|
|
|
+ "volume_manifest_sha256": "",
|
|
|
+ "inventory_digest": "",
|
|
|
+ "inventory_file_count": 0,
|
|
|
+ "inventory_member_count": 0,
|
|
|
}
|
|
|
-
|
|
|
-
|
|
|
-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()
|
|
|
+ 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(
|
|
|
@@ -133,41 +224,228 @@ def stamp_replay_semantic(
|
|
|
if isinstance(report.get("detached_software"), dict)
|
|
|
else {}
|
|
|
)
|
|
|
+ inventory = None
|
|
|
if zip_path is not None:
|
|
|
- align_checked_files_to_manifest(content, zip_path)
|
|
|
- obj = semantic_object(content=content, software=software)
|
|
|
+ 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."""
|
|
|
- manifest = read_volume_manifest(zip_path)
|
|
|
- if not isinstance(manifest, dict) or "file_count" not in manifest:
|
|
|
- return
|
|
|
- count = _int_or_none(manifest.get("file_count"))
|
|
|
- if count is None:
|
|
|
+ _failures, inventory = verify_exact_inventory(zip_path)
|
|
|
+ if inventory is None:
|
|
|
return
|
|
|
- content["checked_files"] = count
|
|
|
+ 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. No extractall; reject zip-slip paths."""
|
|
|
+ """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():
|
|
|
- name = _norm_member(info.filename)
|
|
|
- if not name or name.startswith("/") or re.match(r"^[A-Za-z]:", name):
|
|
|
- raise ValueError(f"unsafe archive member path: {info.filename!r}")
|
|
|
- parts = Path(name).parts
|
|
|
- if ".." in parts:
|
|
|
- raise ValueError(f"unsafe archive member path: {info.filename!r}")
|
|
|
- if info.is_dir() or name.endswith("/"):
|
|
|
+ if info.is_dir() or info.filename.endswith("/"):
|
|
|
continue
|
|
|
- target = dest / Path(*parts)
|
|
|
+ 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}")
|
|
|
@@ -178,45 +456,6 @@ def safe_extract_zip(zip_path: Path, dest: Path) -> list[Path]:
|
|
|
return written
|
|
|
|
|
|
|
|
|
-def verify_volume_manifest_inventory(zip_path: Path) -> list[str]:
|
|
|
- failures: list[str] = []
|
|
|
- manifest = read_volume_manifest(zip_path)
|
|
|
- if not isinstance(manifest, dict):
|
|
|
- return ["replay_volume_manifest_missing"]
|
|
|
- files = manifest.get("files") if isinstance(manifest.get("files"), list) else []
|
|
|
- try:
|
|
|
- claimed_count = int(manifest.get("file_count"))
|
|
|
- except (TypeError, ValueError):
|
|
|
- claimed_count = None
|
|
|
- if claimed_count is None:
|
|
|
- failures.append("replay_volume_manifest_missing")
|
|
|
- return failures
|
|
|
- if claimed_count != len(files):
|
|
|
- failures.append("replay_volume_manifest_file_count_mismatch")
|
|
|
- try:
|
|
|
- with zipfile.ZipFile(zip_path) as zf:
|
|
|
- names = {_norm_member(n) for n in zf.namelist() if not n.endswith("/")}
|
|
|
- for row in files:
|
|
|
- if not isinstance(row, dict):
|
|
|
- failures.append("replay_volume_manifest_inventory_mismatch")
|
|
|
- continue
|
|
|
- rel = _norm_member(str(row.get("archive_path") or row.get("path") or ""))
|
|
|
- if not rel or rel not in names:
|
|
|
- failures.append("replay_volume_manifest_inventory_mismatch")
|
|
|
- continue
|
|
|
- data = zf.read(rel)
|
|
|
- size = _int_or_none(row.get("size"))
|
|
|
- if size is not None and size != len(data):
|
|
|
- failures.append("replay_volume_manifest_inventory_mismatch")
|
|
|
- continue
|
|
|
- sha = str(row.get("sha256") or "").strip().lower()
|
|
|
- if sha and sha != hashlib.sha256(data).hexdigest():
|
|
|
- failures.append("replay_volume_manifest_inventory_mismatch")
|
|
|
- except (OSError, zipfile.BadZipFile, KeyError):
|
|
|
- failures.append("replay_volume_manifest_inventory_mismatch")
|
|
|
- return list(dict.fromkeys(failures))
|
|
|
-
|
|
|
-
|
|
|
def _run_actual_software_replay(zip_path: Path) -> dict[str, Any]:
|
|
|
try:
|
|
|
from replay_review_compact import resolve_cpld_root, run_detached_software_replay
|
|
|
@@ -227,7 +466,6 @@ def _run_actual_software_replay(zip_path: Path) -> dict[str, Any]:
|
|
|
)
|
|
|
tmp = Path(tempfile.mkdtemp(prefix="prod2u-replay-bind-"))
|
|
|
try:
|
|
|
- # mkdtemp already created tmp/; extract into a child so mkdir(exist_ok=False) succeeds.
|
|
|
dest = tmp / "from-zip"
|
|
|
safe_extract_zip(zip_path, dest)
|
|
|
cpld = resolve_cpld_root(dest)
|
|
|
@@ -236,34 +474,8 @@ def _run_actual_software_replay(zip_path: Path) -> dict[str, Any]:
|
|
|
shutil.rmtree(tmp, ignore_errors=True)
|
|
|
|
|
|
|
|
|
-def bind_independent_replay(zip_path: Path, sidecar: dict[str, Any]) -> list[str]:
|
|
|
- """Compare sidecar semantic object to an actual ZIP extract + replay.
|
|
|
-
|
|
|
- Dummy ZIPs without a source tree skip the independent rerun so unit-test
|
|
|
- identity fixtures remain completeness-on-sidecar only.
|
|
|
- """
|
|
|
- if not review_zip_has_source_tree(zip_path):
|
|
|
- return []
|
|
|
- failures = verify_volume_manifest_inventory(zip_path)
|
|
|
- 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")
|
|
|
-
|
|
|
- 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 {}
|
|
|
- )
|
|
|
- claimed = semantic_object(content=content, software=claimed_sw)
|
|
|
- actual = semantic_object(content=content, software=actual_software)
|
|
|
- manifest = read_volume_manifest(zip_path) or {}
|
|
|
- actual["checked_files"] = _int_or_none(manifest.get("file_count")) or 0
|
|
|
-
|
|
|
+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"]:
|
|
|
@@ -278,9 +490,70 @@ def bind_independent_replay(zip_path: Path, sidecar: dict[str, Any]) -> list[str
|
|
|
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()
|
|
|
- actual_digest = semantic_sha256(actual)
|
|
|
- if claimed_digest and claimed_digest != actual_digest:
|
|
|
- failures.append("replay_semantic_sha256_mismatch")
|
|
|
+ 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))
|