test_compact_package_selftest.py 16 KB

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