test_compact_package_selftest.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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/release-set-identity.json",
  156. (
  157. json.dumps(
  158. {
  159. "schema": "prod2u-release-set-identity-v1",
  160. "package_stage": "intermediate-review",
  161. "non_final": True,
  162. "release_set_id": "ab" * 32,
  163. "artifact_source_commit": head,
  164. "delivery_commit": head,
  165. "reference_set_fingerprint": "cd" * 32,
  166. "hardware_validation": "not_run",
  167. }
  168. )
  169. + "\n"
  170. ).encode(),
  171. )
  172. archive.writestr(
  173. "CPLD/evidence/selftest/compact-package-selftest-pointer.json",
  174. (
  175. json.dumps(
  176. {
  177. "schema": "cpld-review-compact-selftest-pointer-v1",
  178. "role": "external_sidecar_only",
  179. }
  180. )
  181. + "\n"
  182. ).encode(),
  183. )
  184. (package_dir / "EXCLUSIONS.txt").write_text("none\n", encoding="utf-8")
  185. (package_dir / "START-HERE.zh-CN.md").write_text("# start\n", encoding="utf-8")
  186. files = [
  187. {
  188. "path": "meta/td-source-closure-binding.json",
  189. "sha256": hashlib.sha256(
  190. json.dumps(
  191. {"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}
  192. ).encode()
  193. ).hexdigest(),
  194. "size": len(
  195. json.dumps(
  196. {"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}
  197. ).encode()
  198. ),
  199. },
  200. {
  201. "path": "source/src/ok.v",
  202. "sha256": hashlib.sha256(b"module ok; endmodule\n").hexdigest(),
  203. "size": len(b"module ok; endmodule\n"),
  204. },
  205. {
  206. "path": "meta/git/HEAD.txt",
  207. "sha256": hashlib.sha256(
  208. b"cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7\n"
  209. ).hexdigest(),
  210. "size": len(b"cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7\n"),
  211. },
  212. {
  213. "path": "meta/git/tree-manifest.json",
  214. "sha256": hashlib.sha256(b"{}\n").hexdigest(),
  215. "size": 3,
  216. },
  217. {
  218. "path": "meta/git/sanitized-snapshot-status.json",
  219. "sha256": hashlib.sha256(
  220. b'{"status":"pass","requested":false}\n'
  221. ).hexdigest(),
  222. "size": len(b'{"status":"pass","requested":false}\n'),
  223. },
  224. {
  225. "path": "evidence/.keep",
  226. "sha256": hashlib.sha256(b"\n").hexdigest(),
  227. "size": 1,
  228. },
  229. ]
  230. # Recompute sizes/hashes from ZIP members for accuracy.
  231. with zipfile.ZipFile(zip_path) as archive:
  232. rebuilt = []
  233. for name in archive.namelist():
  234. if name.endswith("/"):
  235. continue
  236. data = archive.read(name)
  237. rel = name[len("CPLD/") :] if name.startswith("CPLD/") else name
  238. rebuilt.append(
  239. {
  240. "path": rel,
  241. "sha256": hashlib.sha256(data).hexdigest(),
  242. "size": len(data),
  243. }
  244. )
  245. index = {
  246. "profile": "review-compact",
  247. "volumes": [{"file": zip_path.name, "sha256": "x"}],
  248. "files": rebuilt,
  249. "content_dedup": [],
  250. }
  251. (package_dir / "HANDOFF-INDEX.json").write_text(
  252. json.dumps(index), encoding="utf-8"
  253. )
  254. zip_digest = hashlib.sha256(zip_path.read_bytes()).hexdigest()
  255. index["volumes"][0]["sha256"] = zip_digest
  256. (package_dir / "HANDOFF-INDEX.json").write_text(
  257. json.dumps(index), encoding="utf-8"
  258. )
  259. sums = [
  260. f"{hashlib.sha256((package_dir / 'HANDOFF-INDEX.json').read_bytes()).hexdigest()} HANDOFF-INDEX.json",
  261. f"{zip_digest} {zip_path.name}",
  262. ]
  263. # HANDOFF-INDEX changed after first hash — rewrite sums after final index write.
  264. final_index_bytes = (package_dir / "HANDOFF-INDEX.json").read_bytes()
  265. sums = [
  266. f"{hashlib.sha256(final_index_bytes).hexdigest()} HANDOFF-INDEX.json",
  267. f"{zip_digest} {zip_path.name}",
  268. ]
  269. (package_dir / "SHA256SUMS.txt").write_text("\n".join(sums) + "\n", encoding="ascii")
  270. report = selftest.run_compact_package_selftest(
  271. package_dir,
  272. skip_software=True,
  273. )
  274. # Path/forbidden/hash should pass; detached software skipped.
  275. self.assertEqual(report["checks"]["manifest_and_hashes"], "pass")
  276. self.assertEqual(report["checks"]["path_safety"], "pass")
  277. self.assertEqual(report["checks"]["forbidden_files"], "pass")
  278. self.assertEqual(report["checks"]["source_tracked_subset"], "pass")
  279. self.assertEqual(report["binding_status"], "present")
  280. # Standalone ZIP mode must also accept the same archive.
  281. zip_report = selftest.run_compact_zip_selftest(zip_path)
  282. self.assertEqual(zip_report["status"], "pass", zip_report.get("failures"))
  283. def test_source_check_rejects_untracked_formal_workdir(self) -> None:
  284. selftest = load_selftest()
  285. import hashlib
  286. with tempfile.TemporaryDirectory() as tmp:
  287. zip_path = Path(tmp) / "bad.zip"
  288. formal = b"module alt_config_limit_normalize_formal; endmodule\n"
  289. head = "a" * 40
  290. tree = {
  291. "schema": "cpld-review-git-tree-manifest-v1",
  292. "head": head,
  293. "file_count": 1,
  294. "files": [
  295. {
  296. "path": "tests/formal/alt_config_limit_normalize_formal.v",
  297. "sha256": hashlib.sha256(formal).hexdigest(),
  298. "size": len(formal),
  299. }
  300. ],
  301. }
  302. packaged = {
  303. "schema": "prod2u-packaged-source-manifest-v1",
  304. "source_snapshot_mode": "exact_commit_tracked_subset",
  305. "delivery_commit": head,
  306. "policy_excluded": [],
  307. }
  308. with zipfile.ZipFile(zip_path, "w") as archive:
  309. archive.writestr(
  310. "CPLD/source/tests/formal/alt_config_limit_normalize_formal.v",
  311. formal,
  312. )
  313. # Inject untracked SBY PASS marker — must fail closed.
  314. archive.writestr(
  315. "CPLD/source/tests/formal/alt_config_limit_normalize_bmc/PASS",
  316. b"PASS\n",
  317. )
  318. archive.writestr(
  319. "CPLD/meta/git/tree-manifest.json",
  320. (json.dumps(tree) + "\n").encode(),
  321. )
  322. archive.writestr(
  323. "CPLD/meta/git/packaged-source-manifest.json",
  324. (json.dumps(packaged) + "\n").encode(),
  325. )
  326. with zipfile.ZipFile(zip_path) as archive:
  327. failures = selftest.check_source_tracked_subset(archive)
  328. self.assertTrue(
  329. any(item.startswith("untracked_source_member:") for item in failures),
  330. failures,
  331. )
  332. self.assertTrue(
  333. any(item.startswith("formal_workdir_in_source:") for item in failures),
  334. failures,
  335. )
  336. def test_source_check_rejects_missing_tracked_formal_wrapper(self) -> None:
  337. selftest = load_selftest()
  338. import hashlib
  339. with tempfile.TemporaryDirectory() as tmp:
  340. zip_path = Path(tmp) / "missing.zip"
  341. ok = b"module ok; endmodule\n"
  342. head = "b" * 40
  343. tree = {
  344. "schema": "cpld-review-git-tree-manifest-v1",
  345. "head": head,
  346. "file_count": 2,
  347. "files": [
  348. {
  349. "path": "src/ok.v",
  350. "sha256": hashlib.sha256(ok).hexdigest(),
  351. "size": len(ok),
  352. },
  353. {
  354. "path": "tests/formal/alt_config_limit_normalize_formal.v",
  355. "sha256": "c" * 64,
  356. "size": 1,
  357. },
  358. ],
  359. }
  360. packaged = {
  361. "schema": "prod2u-packaged-source-manifest-v1",
  362. "source_snapshot_mode": "exact_commit_tracked_subset",
  363. "delivery_commit": head,
  364. "policy_excluded": [],
  365. }
  366. with zipfile.ZipFile(zip_path, "w") as archive:
  367. archive.writestr("CPLD/source/src/ok.v", ok)
  368. # Canonical formal missing; only a generated-looking copy would be wrong.
  369. archive.writestr(
  370. "CPLD/meta/git/tree-manifest.json",
  371. (json.dumps(tree) + "\n").encode(),
  372. )
  373. archive.writestr(
  374. "CPLD/meta/git/packaged-source-manifest.json",
  375. (json.dumps(packaged) + "\n").encode(),
  376. )
  377. with zipfile.ZipFile(zip_path) as archive:
  378. failures = selftest.check_source_tracked_subset(archive)
  379. self.assertTrue(
  380. any("missing_required_tracked_source" in item for item in failures),
  381. failures,
  382. )
  383. if __name__ == "__main__":
  384. unittest.main()