package_provenance.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. #!/usr/bin/env python3
  2. """Minimal packager provenance helpers (no packager rewrite).
  3. Provides:
  4. - source-closure-relations.json (machine authority = per-file compare)
  5. - REFERENCE-POINTER.json (compact pointer; raw BRD/PDF stay out of default compact)
  6. - release_set_id + external release-set JSON (no cyclic ZIP SHA cross-bind)
  7. """
  8. from __future__ import annotations
  9. import hashlib
  10. import json
  11. import re
  12. from datetime import datetime, timezone
  13. from pathlib import Path
  14. from typing import Any
  15. ROOT = Path(__file__).resolve().parents[1]
  16. # Round-9 door-percent base: locked immutable `dev` tip (not historical jog baseline).
  17. OLD_BASELINE_DEFAULT = "d4f3df2549efeb1e9227f62d1d71c6179c9f9160"
  18. BASE_DEV_COMMIT_DEFAULT = OLD_BASELINE_DEFAULT
  19. ARTIFACT_DEFAULT = "f23d6d4c57959071cd3886ea5503fbe903aee547"
  20. RELEASE_TASK_SLUG = "door-percent"
  21. def release_sibling_filename(kind: str, delivery_commit: str) -> str:
  22. """Canonical sibling names for this task (never altconfig / cross-task slugs)."""
  23. short = _short(delivery_commit, 8)
  24. kind_n = kind.strip().casefold()
  25. if kind_n in {"review-compact", "review", "compact"}:
  26. return f"prod2u-review-compact-{RELEASE_TASK_SLUG}-{short}.zip"
  27. if kind_n in {"firmware", "fw"}:
  28. return f"prod2u-firmware-{RELEASE_TASK_SLUG}-{short}.zip"
  29. if kind_n in {"review-selftest", "compact-selftest"}:
  30. return f"prod2u-review-compact-{RELEASE_TASK_SLUG}-{short}.selftest.json"
  31. if kind_n in {"firmware-selftest", "fw-selftest"}:
  32. return f"prod2u-firmware-{RELEASE_TASK_SLUG}-{short}.selftest.json"
  33. if kind_n in {"release-set", "release_set"}:
  34. return f"prod2u-release-set-{RELEASE_TASK_SLUG}-{short}.json"
  35. raise ValueError(f"unknown sibling kind: {kind}")
  36. def assert_no_stale_task_slug(text: str) -> None:
  37. """Fail when packaging metadata still carries a cross-task stale slug."""
  38. lowered = text.casefold()
  39. if "altconfig" in lowered and RELEASE_TASK_SLUG not in lowered:
  40. raise ValueError(f"stale task slug 'altconfig' in packaging identity: {text}")
  41. # Standalone raw reference package identity (receipt-backed; ZIP not in default compact).
  42. REFERENCE_PACKAGE_FILENAME = "prod2u-reference-v1_2-3axis-20260805T171312Z.zip"
  43. REFERENCE_PACKAGE_SHA256 = (
  44. "b8a1dd092f453b1b25a4faf4734e8c5a404bfa38752f19fb67cf842d228ec2b1"
  45. )
  46. REFERENCE_PACKAGE_SIZE = 4446292
  47. REFERENCE_CANONICAL_BRD_SHA256 = (
  48. "269b5bab2f2e1215b9392079a003badc34238ae3cbe8e5094c9a11bba8b84ebb"
  49. )
  50. REFERENCE_RECEIPT_REL = "receipts/reference-package-20260805T171312Z.json"
  51. def _sha256_bytes(data: bytes) -> str:
  52. return hashlib.sha256(data).hexdigest()
  53. def _sha256_file(path: Path) -> str:
  54. digest = hashlib.sha256()
  55. with path.open("rb") as stream:
  56. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  57. digest.update(chunk)
  58. return digest.hexdigest()
  59. def _read_json(path: Path) -> Any:
  60. return json.loads(path.read_text(encoding="utf-8-sig"))
  61. def _short(commit: str, n: int = 8) -> str:
  62. return commit[:n]
  63. def build_source_closure_relations(
  64. *,
  65. old_baseline_commit: str,
  66. artifact_commit: str,
  67. delivery_commit: str,
  68. old_to_artifact_unchanged: bool | None,
  69. artifact_to_delivery_unchanged: bool | None,
  70. old_to_artifact_changed_paths: list[str] | None = None,
  71. artifact_to_delivery_changed_paths: list[str] | None = None,
  72. comparison_mode: str = "commit_compare",
  73. ) -> dict[str, Any]:
  74. """Machine-authoritative dual-edge source-closure relations."""
  75. old_paths = list(old_to_artifact_changed_paths or [])
  76. del_paths = list(artifact_to_delivery_changed_paths or [])
  77. payload = {
  78. "schema": "prod2u-source-closure-relations-v1",
  79. "generated_at_utc": datetime.now(timezone.utc).isoformat(),
  80. "comparison_mode": comparison_mode,
  81. # Round-9 naming: base_dev → artifact → delivery (never call preview tip final_dev).
  82. "base_dev_commit": old_baseline_commit,
  83. "artifact_source_commit": artifact_commit,
  84. "delivery_commit": delivery_commit,
  85. "old_baseline_to_artifact": {
  86. "from_commit": old_baseline_commit,
  87. "to_commit": artifact_commit,
  88. "from_short": _short(old_baseline_commit),
  89. "to_short": _short(artifact_commit),
  90. "unchanged": old_to_artifact_unchanged,
  91. "production_changed_paths": old_paths,
  92. "edge": "base_dev_to_artifact",
  93. },
  94. "artifact_to_delivery": {
  95. "from_commit": artifact_commit,
  96. "to_commit": delivery_commit,
  97. "from_short": _short(artifact_commit),
  98. "to_short": _short(delivery_commit),
  99. "unchanged": artifact_to_delivery_unchanged,
  100. "production_changed_paths": del_paths,
  101. "edge": "artifact_to_delivery",
  102. },
  103. # Human-readable aliases (same authority, not a second truth).
  104. "OLD_TO_NEW_SOURCE_CLOSURE_UNCHANGED": old_to_artifact_unchanged,
  105. "NEW_ARTIFACT_TO_DELIVERY_SOURCE_CLOSURE_UNCHANGED": artifact_to_delivery_unchanged,
  106. }
  107. return payload
  108. def validate_source_closure_relations(relations: dict[str, Any] | Any) -> dict[str, Any]:
  109. """Fail-closed consistency checks for dual-edge relations.
  110. Negatives required by contract:
  111. - unchanged=false + empty changed_paths + mode=commit_compare → FAIL
  112. - unchanged=true + non-empty changed_paths → FAIL
  113. - comparison_mode=commit_compare with unknown booleans → FAIL
  114. """
  115. failures: list[str] = []
  116. if not isinstance(relations, dict):
  117. return {"status": "fail", "failures": ["relations_not_object"]}
  118. mode = relations.get("comparison_mode")
  119. if mode not in {"commit_compare", "snapshot_hash", "comparison_unavailable"}:
  120. failures.append(f"bad_comparison_mode:{mode}")
  121. for edge_key in ("old_baseline_to_artifact", "artifact_to_delivery"):
  122. edge = relations.get(edge_key) or {}
  123. if not isinstance(edge, dict):
  124. failures.append(f"{edge_key}_not_object")
  125. continue
  126. unchanged = edge.get("unchanged")
  127. paths = edge.get("production_changed_paths") or []
  128. if not isinstance(paths, list):
  129. failures.append(f"{edge_key}_paths_not_list")
  130. paths = []
  131. if mode == "commit_compare":
  132. if unchanged is True and paths:
  133. failures.append(f"{edge_key}_unchanged_true_with_changed_paths")
  134. if unchanged is False and not paths:
  135. failures.append(f"{edge_key}_unchanged_false_empty_paths")
  136. if unchanged not in (True, False):
  137. failures.append(f"{edge_key}_unchanged_not_bool_under_commit_compare")
  138. if mode == "comparison_unavailable":
  139. if unchanged is not None:
  140. failures.append(f"{edge_key}_guessed_bool_when_unavailable")
  141. # Identity presence
  142. old_edge = relations.get("old_baseline_to_artifact") or {}
  143. art_edge = relations.get("artifact_to_delivery") or {}
  144. if not old_edge.get("from_commit") or not old_edge.get("to_commit"):
  145. failures.append("old_edge_missing_commits")
  146. if not art_edge.get("from_commit") or not art_edge.get("to_commit"):
  147. failures.append("art_edge_missing_commits")
  148. if (
  149. old_edge.get("to_commit")
  150. and art_edge.get("from_commit")
  151. and old_edge.get("to_commit") != art_edge.get("from_commit")
  152. ):
  153. failures.append("artifact_identity_mismatch_across_edges")
  154. return {"status": "fail" if failures else "pass", "failures": failures}
  155. def load_reference_package_identity(repo_root: Path | None = None) -> dict[str, Any]:
  156. """Raw reference package identity from canonical receipt (stable; no timestamps)."""
  157. root = repo_root or ROOT
  158. receipt_path = root / REFERENCE_RECEIPT_REL
  159. identity = {
  160. "filename": REFERENCE_PACKAGE_FILENAME,
  161. "size": REFERENCE_PACKAGE_SIZE,
  162. "sha256": REFERENCE_PACKAGE_SHA256,
  163. "canonical_brd_sha256": REFERENCE_CANONICAL_BRD_SHA256,
  164. "receipt_path": REFERENCE_RECEIPT_REL,
  165. }
  166. if receipt_path.is_file():
  167. receipt = _read_json(receipt_path)
  168. zip_sha = receipt.get("zip_sha256")
  169. zip_bytes = receipt.get("zip_bytes")
  170. brd_sha = receipt.get("brd_sha256")
  171. pkg_name = receipt.get("package_name")
  172. if zip_sha and zip_sha != REFERENCE_PACKAGE_SHA256:
  173. raise ValueError(
  174. f"reference receipt zip sha mismatch: {zip_sha} != {REFERENCE_PACKAGE_SHA256}"
  175. )
  176. if brd_sha and brd_sha != REFERENCE_CANONICAL_BRD_SHA256:
  177. raise ValueError(
  178. f"reference receipt BRD sha mismatch: {brd_sha} != {REFERENCE_CANONICAL_BRD_SHA256}"
  179. )
  180. if zip_bytes and int(zip_bytes) != REFERENCE_PACKAGE_SIZE:
  181. raise ValueError(
  182. f"reference receipt size mismatch: {zip_bytes} != {REFERENCE_PACKAGE_SIZE}"
  183. )
  184. if pkg_name and f"{pkg_name}.zip" != REFERENCE_PACKAGE_FILENAME:
  185. # Allow receipt package_name without .zip suffix.
  186. if pkg_name != REFERENCE_PACKAGE_FILENAME.removesuffix(".zip"):
  187. raise ValueError(f"reference receipt name mismatch: {pkg_name}")
  188. identity["receipt_status"] = receipt.get("status")
  189. return identity
  190. def derived_board_viewer_identity(repo_root: Path | None = None) -> dict[str, Any]:
  191. """Derived board-viewer evidence identity (separate from raw reference package)."""
  192. root = repo_root or ROOT
  193. generated = root / "tools" / "board-viewer" / "generated"
  194. names = (
  195. "board-data.json",
  196. "build-info.json",
  197. "import-report.json",
  198. "board-copper.svg",
  199. "board-silkscreen.svg",
  200. "board-mask-edge.svg",
  201. "board-copper-back.svg",
  202. "board-silkscreen-back.svg",
  203. "board-mask-edge-back.svg",
  204. )
  205. assets: dict[str, str | None] = {}
  206. for name in names:
  207. path = generated / name
  208. assets[name] = _sha256_file(path) if path.is_file() else None
  209. build_info = _read_json(generated / "build-info.json") if (generated / "build-info.json").is_file() else {}
  210. input_brd = None
  211. sources = build_info.get("sources") if isinstance(build_info, dict) else None
  212. if isinstance(sources, dict):
  213. brd = sources.get("brd")
  214. if isinstance(brd, dict):
  215. input_brd = brd.get("sha256")
  216. # Stable fingerprint MUST NOT include generated_at or absolute paths.
  217. parts = {
  218. "assets": assets,
  219. "board_viewer_generator_version": build_info.get("generator_version"),
  220. "input_brd_sha256": input_brd,
  221. }
  222. fp = _sha256_bytes(json.dumps(parts, sort_keys=True, separators=(",", ":")).encode("utf-8"))
  223. return {
  224. "schema": "prod2u-derived-board-viewer-identity-v1",
  225. "sha256": fp,
  226. "parts": parts,
  227. # Informational only — not mixed into raw reference fingerprint.
  228. "generated_at_informational": build_info.get("generated_at"),
  229. }
  230. def stable_reference_inventory_semantics(inventory: dict[str, Any] | None) -> dict[str, Any]:
  231. """Extract stable semantic fields only (no generated_at / abs paths / file SHA)."""
  232. inv = inventory if isinstance(inventory, dict) else {}
  233. boundaries = inv.get("evidence_boundaries") if isinstance(inv.get("evidence_boundaries"), dict) else {}
  234. v12 = boundaries.get("v1_2_schematic_pdf") if isinstance(boundaries.get("v1_2_schematic_pdf"), dict) else {}
  235. return {
  236. "v1_2_schematic_pdf_status": v12.get("status", "unknown"),
  237. "historical_schematic_side_evidence": boundaries.get(
  238. "historical_schematic_side_evidence"
  239. ),
  240. }
  241. def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
  242. """Stable raw reference-set fingerprint v2 (no generated_at / temp paths / inventory SHA)."""
  243. root = repo_root or ROOT
  244. inventory_path = root / "docs" / "REFERENCE-INVENTORY.json"
  245. raw = load_reference_package_identity(root)
  246. inventory = _read_json(inventory_path) if inventory_path.is_file() else {}
  247. schematic_identity = stable_reference_inventory_semantics(
  248. inventory if isinstance(inventory, dict) else {}
  249. )
  250. # Normalized inventory content fingerprint (stable fields only; informational).
  251. inventory_content_fingerprint = _sha256_bytes(
  252. json.dumps(schematic_identity, sort_keys=True, separators=(",", ":")).encode(
  253. "utf-8"
  254. )
  255. )
  256. # Raw fingerprint v2: schema + ZIP identity + BRD + stable schematic semantics.
  257. # Do NOT mix in inventory file SHA / generated_at / repository_root / abs paths.
  258. content_parts = {
  259. "fingerprint_schema": "prod2u-reference-set-fingerprint-v2",
  260. "reference_package_filename": raw["filename"],
  261. "reference_package_sha256": raw["sha256"],
  262. "reference_package_size": raw["size"],
  263. "canonical_brd_sha256": raw["canonical_brd_sha256"],
  264. "schematic_identity": schematic_identity,
  265. }
  266. fp = _sha256_bytes(
  267. json.dumps(content_parts, sort_keys=True, separators=(",", ":")).encode("utf-8")
  268. )
  269. inventory_file_sha = (
  270. _sha256_file(inventory_path) if inventory_path.is_file() else None
  271. )
  272. return {
  273. "schema": "prod2u-reference-set-fingerprint-v2",
  274. "sha256": fp,
  275. "parts": content_parts,
  276. "inventory_content_fingerprint": inventory_content_fingerprint,
  277. # Informational only — must not participate in raw fp / release_set_id.
  278. "inventory_file_sha256_informational": inventory_file_sha,
  279. "canonical_brd_path": (
  280. "reference/original/board/FCB_FPGA_MCU_V1.2_20260717/"
  281. "FCB_FPGA+MCU_V1.2_20260717.brd"
  282. ),
  283. "raw_brd_pdf_dsn_in_default_compact": False,
  284. }
  285. def build_reference_pointer(
  286. *,
  287. artifact_commit: str,
  288. delivery_commit: str,
  289. reference_changed: bool = False,
  290. reference_reused: bool = True,
  291. repo_root: Path | None = None,
  292. summary_only: bool = False,
  293. ) -> dict[str, Any]:
  294. """Build REFERENCE-POINTER.json (full for review-compact; summary for firmware)."""
  295. root = repo_root or ROOT
  296. raw = load_reference_package_identity(root)
  297. ref_fp = reference_set_fingerprint(root)
  298. derived = derived_board_viewer_identity(root)
  299. pointer = {
  300. "schema": "prod2u-reference-pointer-v1",
  301. "generated_at_utc": datetime.now(timezone.utc).isoformat(),
  302. "reference_changed": bool(reference_changed),
  303. "reference_reused": bool(reference_reused),
  304. # Raw reference package identity (NOT inventory filename/hash).
  305. "filename": raw["filename"],
  306. "size": raw["size"],
  307. "sha256": raw["sha256"],
  308. "content_fingerprint": ref_fp["sha256"],
  309. "brd_sha256": raw["canonical_brd_sha256"],
  310. "schematic_identity": ref_fp["parts"].get("schematic_identity"),
  311. "raw_reference_package": {
  312. "filename": raw["filename"],
  313. "size": raw["size"],
  314. "sha256": raw["sha256"],
  315. "canonical_brd_sha256": raw["canonical_brd_sha256"],
  316. "receipt_path": raw.get("receipt_path"),
  317. },
  318. "derived_board_viewer": {
  319. "fingerprint_sha256": derived["sha256"],
  320. "assets": derived["parts"]["assets"],
  321. "board_viewer_generator_version": derived["parts"]["board_viewer_generator_version"],
  322. "input_brd_sha256": derived["parts"]["input_brd_sha256"],
  323. },
  324. "artifact_source_commit": artifact_commit,
  325. "delivery_commit": delivery_commit,
  326. "raw_brd_pdf_dsn_in_default_compact": False,
  327. }
  328. if summary_only:
  329. return {
  330. "schema": pointer["schema"],
  331. "reference_changed": pointer["reference_changed"],
  332. "reference_reused": pointer["reference_reused"],
  333. "filename": pointer["filename"],
  334. "sha256": pointer["sha256"],
  335. "content_fingerprint": pointer["content_fingerprint"],
  336. "brd_sha256": pointer["brd_sha256"],
  337. "artifact_source_commit": artifact_commit,
  338. "delivery_commit": delivery_commit,
  339. "raw_brd_pdf_dsn_in_default_compact": False,
  340. }
  341. return pointer
  342. def compute_release_set_id(
  343. *,
  344. artifact_commit: str,
  345. delivery_commit: str,
  346. bitstream_sha256: str,
  347. config_fingerprint: str,
  348. td_run_id: str,
  349. reference_set_fingerprint_sha256: str,
  350. base_dev_commit: str = "d4f3df2549efeb1e9227f62d1d71c6179c9f9160",
  351. td_bound_commit: str | None = None,
  352. package_stage: str = "final-review",
  353. hardware_validation: str = "not_run",
  354. ) -> str:
  355. """Stable release_set_id — never includes final ZIP SHAs (avoids cyclic bind)."""
  356. material = {
  357. "base_dev_commit": base_dev_commit,
  358. "artifact_source_commit": artifact_commit,
  359. "td_bound_commit": td_bound_commit or artifact_commit,
  360. "delivery_commit": delivery_commit,
  361. "bitstream_sha256": bitstream_sha256,
  362. "production_polarity_fingerprint": config_fingerprint,
  363. "td_artifact_run_id": td_run_id,
  364. "reference_set_fingerprint": reference_set_fingerprint_sha256,
  365. "package_stage": package_stage,
  366. "hardware_validation": hardware_validation,
  367. }
  368. return _sha256_bytes(
  369. json.dumps(material, sort_keys=True, separators=(",", ":")).encode("utf-8")
  370. )
  371. def sibling_role_stub(
  372. *,
  373. role: str,
  374. expected_filename: str,
  375. release_set_id: str,
  376. ) -> dict[str, Any]:
  377. """In-package sibling pointer: role + expected filename only (no ZIP SHA)."""
  378. if role not in {"firmware", "review-compact"}:
  379. raise ValueError(f"unsupported sibling role: {role}")
  380. return {
  381. "schema": "prod2u-release-set-sibling-v1",
  382. "release_set_id": release_set_id,
  383. "this_role": role,
  384. "sibling_role": "review-compact" if role == "firmware" else "firmware",
  385. "sibling_expected_filename": expected_filename,
  386. "note": "Final ZIP SHAs are recorded only in the external release-set JSON after both packages exist.",
  387. }
  388. def build_release_set_document(
  389. *,
  390. release_set_id: str,
  391. artifact_commit: str,
  392. delivery_commit: str,
  393. bitstream_sha256: str,
  394. td_run_id: str,
  395. config_fingerprint: str,
  396. reference_set_fingerprint_sha256: str,
  397. firmware_filename: str,
  398. firmware_size: int,
  399. firmware_sha256: str,
  400. review_compact_filename: str,
  401. review_compact_size: int,
  402. review_compact_sha256: str,
  403. hardware_validation: str = "not_run",
  404. ) -> dict[str, Any]:
  405. """External release-set JSON written AFTER both packages exist."""
  406. for name, sha in (
  407. (firmware_filename, firmware_sha256),
  408. (review_compact_filename, review_compact_sha256),
  409. ):
  410. if not re.fullmatch(r"[0-9a-f]{64}", sha):
  411. raise ValueError(f"invalid package sha for {name}")
  412. return {
  413. "schema": "prod2u-release-set-v1",
  414. "generated_at_utc": datetime.now(timezone.utc).isoformat(),
  415. "release_set_id": release_set_id,
  416. "hardware_validation": hardware_validation,
  417. "identity": {
  418. "artifact_source_commit": artifact_commit,
  419. "delivery_commit": delivery_commit,
  420. "bitstream_sha256": bitstream_sha256,
  421. "td_run_id": td_run_id,
  422. "config_fingerprint": config_fingerprint,
  423. "reference_set_fingerprint": reference_set_fingerprint_sha256,
  424. },
  425. "packages": {
  426. "firmware": {
  427. "role": "firmware",
  428. "filename": firmware_filename,
  429. "size": firmware_size,
  430. "sha256": firmware_sha256,
  431. },
  432. "review_compact": {
  433. "role": "review-compact",
  434. "filename": review_compact_filename,
  435. "size": review_compact_size,
  436. "sha256": review_compact_sha256,
  437. },
  438. },
  439. "cyclic_zip_sha_cross_bind": False,
  440. }
  441. def write_release_set_files(
  442. output_dir: Path,
  443. document: dict[str, Any],
  444. ) -> tuple[Path, Path]:
  445. """Write prod2u-release-set-<delivery8>.json + .sha256 sidecar."""
  446. delivery8 = _short(document["identity"]["delivery_commit"])
  447. output_dir = Path(output_dir)
  448. output_dir.mkdir(parents=True, exist_ok=True)
  449. json_path = output_dir / f"prod2u-release-set-{delivery8}.json"
  450. text = json.dumps(document, indent=2, sort_keys=True) + "\n"
  451. json_path.write_text(text, encoding="utf-8")
  452. digest = _sha256_bytes(text.encode("utf-8"))
  453. sha_path = output_dir / f"prod2u-release-set-{delivery8}.json.sha256"
  454. sha_path.write_text(f"{digest} {json_path.name}\n", encoding="utf-8")
  455. return json_path, sha_path
  456. def validate_release_set_selftest(
  457. document: dict[str, Any],
  458. *,
  459. firmware_path: Path | None = None,
  460. review_compact_path: Path | None = None,
  461. expected_sibling_filename_in_firmware: str | None = None,
  462. expected_sibling_filename_in_compact: str | None = None,
  463. package_sibling_records: dict[str, dict[str, Any]] | None = None,
  464. ) -> dict[str, Any]:
  465. """Unit / fresh-extraction / tamper-negative checks for release-set."""
  466. failures: list[str] = []
  467. if document.get("schema") != "prod2u-release-set-v1":
  468. failures.append("bad_schema")
  469. if document.get("cyclic_zip_sha_cross_bind") is not False:
  470. failures.append("cyclic_flag_not_false")
  471. if document.get("hardware_validation") != "not_run":
  472. failures.append("hardware_not_not_run")
  473. packages = document.get("packages") or {}
  474. fw = packages.get("firmware") or {}
  475. rc = packages.get("review_compact") or {}
  476. if not fw.get("filename") or not rc.get("filename"):
  477. failures.append("missing_package_filenames")
  478. if fw.get("sha256") == rc.get("sha256"):
  479. failures.append("firmware_and_compact_sha_identical_suspicious")
  480. if firmware_path is not None:
  481. if firmware_path.name != fw.get("filename"):
  482. failures.append("firmware_filename_mismatch")
  483. if firmware_path.is_file() and _sha256_file(firmware_path) != fw.get("sha256"):
  484. failures.append("firmware_sha_mismatch")
  485. if firmware_path.is_file() and firmware_path.stat().st_size != fw.get("size"):
  486. failures.append("firmware_size_mismatch")
  487. if review_compact_path is not None:
  488. if review_compact_path.name != rc.get("filename"):
  489. failures.append("review_compact_filename_mismatch")
  490. if review_compact_path.is_file() and _sha256_file(review_compact_path) != rc.get("sha256"):
  491. failures.append("review_compact_sha_mismatch")
  492. if package_sibling_records:
  493. for role, record in package_sibling_records.items():
  494. if record.get("release_set_id") != document.get("release_set_id"):
  495. failures.append(f"sibling_release_set_id_mismatch:{role}")
  496. if "sha256" in record or "zip_sha256" in record:
  497. failures.append(f"sibling_contains_zip_sha:{role}")
  498. sib_name = record.get("sibling_expected_filename")
  499. if role == "firmware" and expected_sibling_filename_in_firmware is not None:
  500. if sib_name != expected_sibling_filename_in_firmware:
  501. failures.append("firmware_sibling_filename_mismatch")
  502. if role == "review-compact" and expected_sibling_filename_in_compact is not None:
  503. if sib_name != expected_sibling_filename_in_compact:
  504. failures.append("compact_sibling_filename_mismatch")
  505. identity = document.get("identity") or {}
  506. if not identity.get("bitstream_sha256"):
  507. failures.append("missing_bitstream_identity")
  508. if not identity.get("reference_set_fingerprint"):
  509. failures.append("missing_reference_fingerprint")
  510. return {
  511. "status": "fail" if failures else "pass",
  512. "failures": failures,
  513. "release_set_id": document.get("release_set_id"),
  514. }