test_compact_package_selftest.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. #!/usr/bin/env python3
  2. """Unit tests for compact package selftest helpers and binding path safety."""
  3. from __future__ import annotations
  4. import importlib.util
  5. import json
  6. import tempfile
  7. import unittest
  8. import zipfile
  9. from pathlib import Path
  10. from types import ModuleType
  11. ROOT = Path(__file__).resolve().parents[2]
  12. TOOLS = ROOT / "tools"
  13. def load_selftest() -> ModuleType:
  14. path = TOOLS / "compact_package_selftest.py"
  15. spec = importlib.util.spec_from_file_location("compact_package_selftest_lane_d", path)
  16. assert spec is not None and spec.loader is not None
  17. module = importlib.util.module_from_spec(spec)
  18. spec.loader.exec_module(module)
  19. return module
  20. class CompactPackageSelftestUnitTests(unittest.TestCase):
  21. maxDiff = None
  22. def test_path_safety_rejects_traversal_and_absolute(self) -> None:
  23. selftest = load_selftest()
  24. failures = selftest.check_path_safety(
  25. [
  26. "CPLD/source/src/ok.v",
  27. "CPLD/source/../escape.v",
  28. "/etc/passwd",
  29. "CPLD\\bad\\slash.v",
  30. ]
  31. )
  32. self.assertTrue(any(item.startswith("unsafe_path_segment:") for item in failures))
  33. self.assertTrue(any(item.startswith("absolute_path:") for item in failures))
  34. self.assertTrue(any(item.startswith("backslash_path:") for item in failures))
  35. def test_forbidden_members_catch_pdf_and_adversarial_payload(self) -> None:
  36. selftest = load_selftest()
  37. failures = selftest.check_forbidden_members(
  38. [
  39. "CPLD/source/docs/leak.pdf",
  40. "CPLD/source/tests/fixtures/package_adversarial/payloads/sneaky-main.brd",
  41. "CPLD/source/src/ok.v",
  42. "CPLD/meta/td-source-closure-binding.json",
  43. ]
  44. )
  45. self.assertTrue(any("forbidden_suffix" in item for item in failures))
  46. self.assertTrue(any("adversarial_payload_in_compact" in item for item in failures))
  47. def test_selftest_on_minimal_synthetic_package(self) -> None:
  48. selftest = load_selftest()
  49. import hashlib # noqa: WPS433 — keep local for synthetic fixture hashing
  50. with tempfile.TemporaryDirectory() as tmp:
  51. package_dir = Path(tmp) / "pkg"
  52. package_dir.mkdir()
  53. zip_path = package_dir / "demo.zip"
  54. ok_v = b"module ok; endmodule\n"
  55. formal_v = b"// BMC/cover only\nmodule alt_config_limit_normalize_formal; endmodule\n"
  56. head = "cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7"
  57. tree = {
  58. "schema": "cpld-review-git-tree-manifest-v1",
  59. "head": head,
  60. "file_count": 2,
  61. "source": "git_archive_exact_commit",
  62. "files": [
  63. {
  64. "path": "src/ok.v",
  65. "sha256": hashlib.sha256(ok_v).hexdigest(),
  66. "size": len(ok_v),
  67. },
  68. {
  69. "path": "tests/formal/alt_config_limit_normalize_formal.v",
  70. "sha256": hashlib.sha256(formal_v).hexdigest(),
  71. "size": len(formal_v),
  72. },
  73. ],
  74. }
  75. packaged = {
  76. "schema": "prod2u-packaged-source-manifest-v1",
  77. "source_snapshot_mode": "exact_commit_tracked_subset",
  78. "delivery_commit": head,
  79. "tracked_file_count": 2,
  80. "included_source_count": 2,
  81. "included_source_files": [
  82. {"path": "src/ok.v", "package_path": "source/src/ok.v"},
  83. {
  84. "path": "tests/formal/alt_config_limit_normalize_formal.v",
  85. "package_path": "source/tests/formal/alt_config_limit_normalize_formal.v",
  86. },
  87. ],
  88. "policy_excluded": [],
  89. "silent_missing_tracked": [],
  90. }
  91. with zipfile.ZipFile(zip_path, "w") as archive:
  92. archive.writestr(
  93. "CPLD/meta/td/td-source-closure-binding.json",
  94. json.dumps({"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}),
  95. )
  96. archive.writestr(
  97. "CPLD/meta/td-source-closure-binding.json",
  98. json.dumps({"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}),
  99. )
  100. archive.writestr("CPLD/source/src/ok.v", ok_v)
  101. archive.writestr(
  102. "CPLD/source/tests/formal/alt_config_limit_normalize_formal.v",
  103. formal_v,
  104. )
  105. archive.writestr(
  106. "CPLD/meta/git/HEAD.txt",
  107. f"{head}\n".encode(),
  108. )
  109. archive.writestr("CPLD/meta/git/branch.txt", b"dev\n")
  110. archive.writestr("CPLD/meta/git/status.txt", b"## dev\n")
  111. archive.writestr(
  112. "CPLD/meta/git/log-20.txt",
  113. f"{head} 2026-01-01 chore\n".encode(),
  114. )
  115. archive.writestr(
  116. "CPLD/meta/git/tree-manifest.json",
  117. (json.dumps(tree) + "\n").encode(),
  118. )
  119. archive.writestr(
  120. "CPLD/meta/git/source-file-sha256.json",
  121. json.dumps(
  122. {
  123. "schema": "cpld-review-git-file-sha256-v1",
  124. "head": head,
  125. "files": {
  126. "src/ok.v": hashlib.sha256(ok_v).hexdigest(),
  127. "tests/formal/alt_config_limit_normalize_formal.v": hashlib.sha256(
  128. formal_v
  129. ).hexdigest(),
  130. },
  131. }
  132. ).encode(),
  133. )
  134. archive.writestr(
  135. "CPLD/meta/git/packaged-source-manifest.json",
  136. (json.dumps(packaged) + "\n").encode(),
  137. )
  138. archive.writestr(
  139. "CPLD/meta/git/sanitized-snapshot-status.json",
  140. b'{"status":"pass","requested":false}\n',
  141. )
  142. archive.writestr(
  143. "CPLD/meta/REFERENCE-POINTER.json",
  144. b'{"schema":"prod2u-reference-pointer-v1","reference_reused":true}\n',
  145. )
  146. archive.writestr(
  147. "CPLD/meta/source-closure-relations.json",
  148. b'{"schema":"prod2u-source-closure-relations-v1"}\n',
  149. )
  150. archive.writestr(
  151. "CPLD/meta/release-set-sibling.json",
  152. b'{"schema":"prod2u-release-set-sibling-v1","this_role":"review-compact"}\n',
  153. )
  154. archive.writestr(
  155. "CPLD/meta/package-stage.txt",
  156. b"intermediate-review\n",
  157. )
  158. archive.writestr(
  159. "CPLD/meta/release-set-identity.json",
  160. (
  161. json.dumps(
  162. {
  163. "schema": "prod2u-release-set-identity-v1",
  164. "package_stage": "intermediate-review",
  165. "non_final": True,
  166. "release_set_id": "ab" * 32,
  167. "artifact_source_commit": head,
  168. "delivery_commit": head,
  169. "reference_set_fingerprint": "cd" * 32,
  170. "hardware_validation": "not_run",
  171. }
  172. )
  173. + "\n"
  174. ).encode(),
  175. )
  176. archive.writestr(
  177. "CPLD/evidence/selftest/compact-package-selftest-pointer.json",
  178. (
  179. json.dumps(
  180. {
  181. "schema": "cpld-review-compact-selftest-pointer-v1",
  182. "role": "external_sidecar_only",
  183. }
  184. )
  185. + "\n"
  186. ).encode(),
  187. )
  188. (package_dir / "EXCLUSIONS.txt").write_text("none\n", encoding="utf-8")
  189. (package_dir / "START-HERE.zh-CN.md").write_text("# start\n", encoding="utf-8")
  190. files = [
  191. {
  192. "path": "meta/td-source-closure-binding.json",
  193. "sha256": hashlib.sha256(
  194. json.dumps(
  195. {"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}
  196. ).encode()
  197. ).hexdigest(),
  198. "size": len(
  199. json.dumps(
  200. {"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}
  201. ).encode()
  202. ),
  203. },
  204. {
  205. "path": "source/src/ok.v",
  206. "sha256": hashlib.sha256(b"module ok; endmodule\n").hexdigest(),
  207. "size": len(b"module ok; endmodule\n"),
  208. },
  209. {
  210. "path": "meta/git/HEAD.txt",
  211. "sha256": hashlib.sha256(
  212. b"cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7\n"
  213. ).hexdigest(),
  214. "size": len(b"cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7\n"),
  215. },
  216. {
  217. "path": "meta/git/tree-manifest.json",
  218. "sha256": hashlib.sha256(b"{}\n").hexdigest(),
  219. "size": 3,
  220. },
  221. {
  222. "path": "meta/git/sanitized-snapshot-status.json",
  223. "sha256": hashlib.sha256(
  224. b'{"status":"pass","requested":false}\n'
  225. ).hexdigest(),
  226. "size": len(b'{"status":"pass","requested":false}\n'),
  227. },
  228. {
  229. "path": "evidence/.keep",
  230. "sha256": hashlib.sha256(b"\n").hexdigest(),
  231. "size": 1,
  232. },
  233. ]
  234. # Recompute sizes/hashes from ZIP members for accuracy.
  235. with zipfile.ZipFile(zip_path) as archive:
  236. rebuilt = []
  237. for name in archive.namelist():
  238. if name.endswith("/"):
  239. continue
  240. data = archive.read(name)
  241. rel = name[len("CPLD/") :] if name.startswith("CPLD/") else name
  242. rebuilt.append(
  243. {
  244. "path": rel,
  245. "sha256": hashlib.sha256(data).hexdigest(),
  246. "size": len(data),
  247. }
  248. )
  249. index = {
  250. "profile": "review-compact",
  251. "volumes": [{"file": zip_path.name, "sha256": "x"}],
  252. "files": rebuilt,
  253. "content_dedup": [],
  254. }
  255. (package_dir / "HANDOFF-INDEX.json").write_text(
  256. json.dumps(index), encoding="utf-8"
  257. )
  258. zip_digest = hashlib.sha256(zip_path.read_bytes()).hexdigest()
  259. index["volumes"][0]["sha256"] = zip_digest
  260. (package_dir / "HANDOFF-INDEX.json").write_text(
  261. json.dumps(index), encoding="utf-8"
  262. )
  263. sums = [
  264. f"{hashlib.sha256((package_dir / 'HANDOFF-INDEX.json').read_bytes()).hexdigest()} HANDOFF-INDEX.json",
  265. f"{zip_digest} {zip_path.name}",
  266. ]
  267. # HANDOFF-INDEX changed after first hash — rewrite sums after final index write.
  268. final_index_bytes = (package_dir / "HANDOFF-INDEX.json").read_bytes()
  269. sums = [
  270. f"{hashlib.sha256(final_index_bytes).hexdigest()} HANDOFF-INDEX.json",
  271. f"{zip_digest} {zip_path.name}",
  272. ]
  273. (package_dir / "SHA256SUMS.txt").write_text("\n".join(sums) + "\n", encoding="ascii")
  274. report = selftest.run_compact_package_selftest(
  275. package_dir,
  276. skip_software=True,
  277. )
  278. # Path/forbidden/hash should pass; detached software skipped.
  279. self.assertEqual(report["checks"]["manifest_and_hashes"], "pass")
  280. self.assertEqual(report["checks"]["path_safety"], "pass")
  281. self.assertEqual(report["checks"]["forbidden_files"], "pass")
  282. self.assertEqual(report["checks"]["source_tracked_subset"], "pass")
  283. self.assertEqual(report["binding_status"], "present")
  284. # Standalone ZIP mode must also accept the same archive.
  285. # No --stage: auto-detect intermediate from package metadata.
  286. zip_report = selftest.run_compact_zip_selftest(zip_path)
  287. self.assertEqual(zip_report["status"], "pass", zip_report.get("failures"))
  288. self.assertEqual(zip_report["package_stage"], "intermediate-review")
  289. # CLI stage mismatch must fail closed (no silent intermediate).
  290. mismatch = selftest.run_compact_zip_selftest(
  291. zip_path, package_stage="final-review"
  292. )
  293. self.assertEqual(mismatch["status"], "fail")
  294. self.assertTrue(
  295. any("package_stage_cli_mismatch" in item for item in mismatch["failures"]),
  296. mismatch.get("failures"),
  297. )
  298. def test_final_evidence_casefold_path_compare(self) -> None:
  299. selftest = load_selftest()
  300. import hashlib
  301. with tempfile.TemporaryDirectory() as tmp:
  302. zip_path = Path(tmp) / "case.zip"
  303. bit = b"BITSTREAM"
  304. bit_sha = hashlib.sha256(bit).hexdigest()
  305. with zipfile.ZipFile(zip_path, "w") as archive:
  306. for suffix in selftest.FINAL_MANDATORY_EVIDENCE_SUFFIXES:
  307. # Intentionally casefold the member path; compare must still pass.
  308. member = f"CPLD/{suffix.casefold()}"
  309. if suffix.endswith(".bit"):
  310. archive.writestr(member, bit)
  311. elif suffix.endswith("BITSTREAM-SHA256.txt"):
  312. archive.writestr(member, f"{bit_sha}\n".encode())
  313. elif suffix.endswith(".json"):
  314. archive.writestr(member, b"{}\n")
  315. else:
  316. archive.writestr(member, b"# note\n")
  317. with zipfile.ZipFile(zip_path) as archive:
  318. path_failures = selftest.check_final_evidence_paths(
  319. archive, list(archive.namelist())
  320. )
  321. semantic = selftest.check_final_canonical_evidence(
  322. archive, list(archive.namelist())
  323. )
  324. self.assertEqual(path_failures, [], path_failures)
  325. # Empty `{}` JSON must fail semantic selftest (Round-10).
  326. self.assertTrue(semantic, "empty JSON fixtures must not pass semantic selftest")
  327. def test_source_check_rejects_untracked_formal_workdir(self) -> None:
  328. selftest = load_selftest()
  329. import hashlib
  330. with tempfile.TemporaryDirectory() as tmp:
  331. zip_path = Path(tmp) / "bad.zip"
  332. formal = b"module alt_config_limit_normalize_formal; endmodule\n"
  333. head = "a" * 40
  334. tree = {
  335. "schema": "cpld-review-git-tree-manifest-v1",
  336. "head": head,
  337. "file_count": 1,
  338. "files": [
  339. {
  340. "path": "tests/formal/alt_config_limit_normalize_formal.v",
  341. "sha256": hashlib.sha256(formal).hexdigest(),
  342. "size": len(formal),
  343. }
  344. ],
  345. }
  346. packaged = {
  347. "schema": "prod2u-packaged-source-manifest-v1",
  348. "source_snapshot_mode": "exact_commit_tracked_subset",
  349. "delivery_commit": head,
  350. "policy_excluded": [],
  351. }
  352. with zipfile.ZipFile(zip_path, "w") as archive:
  353. archive.writestr(
  354. "CPLD/source/tests/formal/alt_config_limit_normalize_formal.v",
  355. formal,
  356. )
  357. # Inject untracked SBY PASS marker — must fail closed.
  358. archive.writestr(
  359. "CPLD/source/tests/formal/alt_config_limit_normalize_bmc/PASS",
  360. b"PASS\n",
  361. )
  362. archive.writestr(
  363. "CPLD/meta/git/tree-manifest.json",
  364. (json.dumps(tree) + "\n").encode(),
  365. )
  366. archive.writestr(
  367. "CPLD/meta/git/packaged-source-manifest.json",
  368. (json.dumps(packaged) + "\n").encode(),
  369. )
  370. with zipfile.ZipFile(zip_path) as archive:
  371. failures = selftest.check_source_tracked_subset(archive)
  372. self.assertTrue(
  373. any(item.startswith("untracked_source_member:") for item in failures),
  374. failures,
  375. )
  376. self.assertTrue(
  377. any(item.startswith("formal_workdir_in_source:") for item in failures),
  378. failures,
  379. )
  380. def test_source_check_rejects_missing_tracked_formal_wrapper(self) -> None:
  381. selftest = load_selftest()
  382. import hashlib
  383. with tempfile.TemporaryDirectory() as tmp:
  384. zip_path = Path(tmp) / "missing.zip"
  385. ok = b"module ok; endmodule\n"
  386. head = "b" * 40
  387. tree = {
  388. "schema": "cpld-review-git-tree-manifest-v1",
  389. "head": head,
  390. "file_count": 2,
  391. "files": [
  392. {
  393. "path": "src/ok.v",
  394. "sha256": hashlib.sha256(ok).hexdigest(),
  395. "size": len(ok),
  396. },
  397. {
  398. "path": "tests/formal/alt_config_limit_normalize_formal.v",
  399. "sha256": "c" * 64,
  400. "size": 1,
  401. },
  402. ],
  403. }
  404. packaged = {
  405. "schema": "prod2u-packaged-source-manifest-v1",
  406. "source_snapshot_mode": "exact_commit_tracked_subset",
  407. "delivery_commit": head,
  408. "policy_excluded": [],
  409. }
  410. with zipfile.ZipFile(zip_path, "w") as archive:
  411. archive.writestr("CPLD/source/src/ok.v", ok)
  412. # Canonical formal missing; only a generated-looking copy would be wrong.
  413. archive.writestr(
  414. "CPLD/meta/git/tree-manifest.json",
  415. (json.dumps(tree) + "\n").encode(),
  416. )
  417. archive.writestr(
  418. "CPLD/meta/git/packaged-source-manifest.json",
  419. (json.dumps(packaged) + "\n").encode(),
  420. )
  421. with zipfile.ZipFile(zip_path) as archive:
  422. failures = selftest.check_source_tracked_subset(archive)
  423. self.assertTrue(
  424. any("missing_required_tracked_source" in item for item in failures),
  425. failures,
  426. )
  427. if __name__ == "__main__":
  428. unittest.main()