#!/usr/bin/env python3 """Unit tests for compact package selftest helpers and binding path safety.""" from __future__ import annotations import importlib.util import json import tempfile import unittest import zipfile from pathlib import Path from types import ModuleType ROOT = Path(__file__).resolve().parents[2] TOOLS = ROOT / "tools" def load_selftest() -> ModuleType: path = TOOLS / "compact_package_selftest.py" spec = importlib.util.spec_from_file_location("compact_package_selftest_lane_d", path) assert spec is not None and spec.loader is not None module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module class CompactPackageSelftestUnitTests(unittest.TestCase): maxDiff = None def test_path_safety_rejects_traversal_and_absolute(self) -> None: selftest = load_selftest() failures = selftest.check_path_safety( [ "CPLD/source/src/ok.v", "CPLD/source/../escape.v", "/etc/passwd", "CPLD\\bad\\slash.v", ] ) self.assertTrue(any(item.startswith("unsafe_path_segment:") for item in failures)) self.assertTrue(any(item.startswith("absolute_path:") for item in failures)) self.assertTrue(any(item.startswith("backslash_path:") for item in failures)) def test_forbidden_members_catch_pdf_and_adversarial_payload(self) -> None: selftest = load_selftest() failures = selftest.check_forbidden_members( [ "CPLD/source/docs/leak.pdf", "CPLD/source/tests/fixtures/package_adversarial/payloads/sneaky-main.brd", "CPLD/source/src/ok.v", "CPLD/meta/td-source-closure-binding.json", ] ) self.assertTrue(any("forbidden_suffix" in item for item in failures)) self.assertTrue(any("adversarial_payload_in_compact" in item for item in failures)) def test_selftest_on_minimal_synthetic_package(self) -> None: selftest = load_selftest() import hashlib # noqa: WPS433 — keep local for synthetic fixture hashing with tempfile.TemporaryDirectory() as tmp: package_dir = Path(tmp) / "pkg" package_dir.mkdir() zip_path = package_dir / "demo.zip" ok_v = b"module ok; endmodule\n" formal_v = b"// BMC/cover only\nmodule alt_config_limit_normalize_formal; endmodule\n" head = "cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7" tree = { "schema": "cpld-review-git-tree-manifest-v1", "head": head, "file_count": 2, "source": "git_archive_exact_commit", "files": [ { "path": "src/ok.v", "sha256": hashlib.sha256(ok_v).hexdigest(), "size": len(ok_v), }, { "path": "tests/formal/alt_config_limit_normalize_formal.v", "sha256": hashlib.sha256(formal_v).hexdigest(), "size": len(formal_v), }, ], } packaged = { "schema": "prod2u-packaged-source-manifest-v1", "source_snapshot_mode": "exact_commit_tracked_subset", "delivery_commit": head, "tracked_file_count": 2, "included_source_count": 2, "included_source_files": [ {"path": "src/ok.v", "package_path": "source/src/ok.v"}, { "path": "tests/formal/alt_config_limit_normalize_formal.v", "package_path": "source/tests/formal/alt_config_limit_normalize_formal.v", }, ], "policy_excluded": [], "silent_missing_tracked": [], } with zipfile.ZipFile(zip_path, "w") as archive: archive.writestr( "CPLD/meta/td/td-source-closure-binding.json", json.dumps({"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}), ) archive.writestr( "CPLD/meta/td-source-closure-binding.json", json.dumps({"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}), ) archive.writestr("CPLD/source/src/ok.v", ok_v) archive.writestr( "CPLD/source/tests/formal/alt_config_limit_normalize_formal.v", formal_v, ) archive.writestr( "CPLD/meta/git/HEAD.txt", f"{head}\n".encode(), ) archive.writestr("CPLD/meta/git/branch.txt", b"dev\n") archive.writestr("CPLD/meta/git/status.txt", b"## dev\n") archive.writestr( "CPLD/meta/git/log-20.txt", f"{head} 2026-01-01 chore\n".encode(), ) archive.writestr( "CPLD/meta/git/tree-manifest.json", (json.dumps(tree) + "\n").encode(), ) archive.writestr( "CPLD/meta/git/source-file-sha256.json", json.dumps( { "schema": "cpld-review-git-file-sha256-v1", "head": head, "files": { "src/ok.v": hashlib.sha256(ok_v).hexdigest(), "tests/formal/alt_config_limit_normalize_formal.v": hashlib.sha256( formal_v ).hexdigest(), }, } ).encode(), ) archive.writestr( "CPLD/meta/git/packaged-source-manifest.json", (json.dumps(packaged) + "\n").encode(), ) archive.writestr( "CPLD/meta/git/sanitized-snapshot-status.json", b'{"status":"pass","requested":false}\n', ) archive.writestr( "CPLD/meta/REFERENCE-POINTER.json", b'{"schema":"prod2u-reference-pointer-v1","reference_reused":true}\n', ) archive.writestr( "CPLD/meta/source-closure-relations.json", b'{"schema":"prod2u-source-closure-relations-v1"}\n', ) archive.writestr( "CPLD/meta/release-set-sibling.json", b'{"schema":"prod2u-release-set-sibling-v1","this_role":"review-compact"}\n', ) archive.writestr( "CPLD/meta/package-stage.txt", b"intermediate-review\n", ) archive.writestr( "CPLD/meta/release-set-identity.json", ( json.dumps( { "schema": "prod2u-release-set-identity-v1", "package_stage": "intermediate-review", "non_final": True, "release_set_id": "ab" * 32, "artifact_source_commit": head, "delivery_commit": head, "reference_set_fingerprint": "cd" * 32, "hardware_validation": "not_run", } ) + "\n" ).encode(), ) archive.writestr( "CPLD/evidence/selftest/compact-package-selftest-pointer.json", ( json.dumps( { "schema": "cpld-review-compact-selftest-pointer-v1", "role": "external_sidecar_only", } ) + "\n" ).encode(), ) (package_dir / "EXCLUSIONS.txt").write_text("none\n", encoding="utf-8") (package_dir / "START-HERE.zh-CN.md").write_text("# start\n", encoding="utf-8") files = [ { "path": "meta/td-source-closure-binding.json", "sha256": hashlib.sha256( json.dumps( {"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"} ).encode() ).hexdigest(), "size": len( json.dumps( {"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"} ).encode() ), }, { "path": "source/src/ok.v", "sha256": hashlib.sha256(b"module ok; endmodule\n").hexdigest(), "size": len(b"module ok; endmodule\n"), }, { "path": "meta/git/HEAD.txt", "sha256": hashlib.sha256( b"cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7\n" ).hexdigest(), "size": len(b"cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7\n"), }, { "path": "meta/git/tree-manifest.json", "sha256": hashlib.sha256(b"{}\n").hexdigest(), "size": 3, }, { "path": "meta/git/sanitized-snapshot-status.json", "sha256": hashlib.sha256( b'{"status":"pass","requested":false}\n' ).hexdigest(), "size": len(b'{"status":"pass","requested":false}\n'), }, { "path": "evidence/.keep", "sha256": hashlib.sha256(b"\n").hexdigest(), "size": 1, }, ] # Recompute sizes/hashes from ZIP members for accuracy. with zipfile.ZipFile(zip_path) as archive: rebuilt = [] for name in archive.namelist(): if name.endswith("/"): continue data = archive.read(name) rel = name[len("CPLD/") :] if name.startswith("CPLD/") else name rebuilt.append( { "path": rel, "sha256": hashlib.sha256(data).hexdigest(), "size": len(data), } ) index = { "profile": "review-compact", "volumes": [{"file": zip_path.name, "sha256": "x"}], "files": rebuilt, "content_dedup": [], } (package_dir / "HANDOFF-INDEX.json").write_text( json.dumps(index), encoding="utf-8" ) zip_digest = hashlib.sha256(zip_path.read_bytes()).hexdigest() index["volumes"][0]["sha256"] = zip_digest (package_dir / "HANDOFF-INDEX.json").write_text( json.dumps(index), encoding="utf-8" ) sums = [ f"{hashlib.sha256((package_dir / 'HANDOFF-INDEX.json').read_bytes()).hexdigest()} HANDOFF-INDEX.json", f"{zip_digest} {zip_path.name}", ] # HANDOFF-INDEX changed after first hash — rewrite sums after final index write. final_index_bytes = (package_dir / "HANDOFF-INDEX.json").read_bytes() sums = [ f"{hashlib.sha256(final_index_bytes).hexdigest()} HANDOFF-INDEX.json", f"{zip_digest} {zip_path.name}", ] (package_dir / "SHA256SUMS.txt").write_text("\n".join(sums) + "\n", encoding="ascii") report = selftest.run_compact_package_selftest( package_dir, skip_software=True, ) # Path/forbidden/hash should pass; detached software skipped. self.assertEqual(report["checks"]["manifest_and_hashes"], "pass") self.assertEqual(report["checks"]["path_safety"], "pass") self.assertEqual(report["checks"]["forbidden_files"], "pass") self.assertEqual(report["checks"]["source_tracked_subset"], "pass") self.assertEqual(report["binding_status"], "present") # Standalone ZIP mode must also accept the same archive. # No --stage: auto-detect intermediate from package metadata. zip_report = selftest.run_compact_zip_selftest(zip_path) self.assertEqual(zip_report["status"], "pass", zip_report.get("failures")) self.assertEqual(zip_report["package_stage"], "intermediate-review") # CLI stage mismatch must fail closed (no silent intermediate). mismatch = selftest.run_compact_zip_selftest( zip_path, package_stage="final-review" ) self.assertEqual(mismatch["status"], "fail") self.assertTrue( any("package_stage_cli_mismatch" in item for item in mismatch["failures"]), mismatch.get("failures"), ) def test_final_evidence_casefold_path_compare(self) -> None: selftest = load_selftest() import hashlib with tempfile.TemporaryDirectory() as tmp: zip_path = Path(tmp) / "case.zip" bit = b"BITSTREAM" bit_sha = hashlib.sha256(bit).hexdigest() with zipfile.ZipFile(zip_path, "w") as archive: for suffix in selftest.FINAL_MANDATORY_EVIDENCE_SUFFIXES: # Intentionally casefold the member path; compare must still pass. member = f"CPLD/{suffix.casefold()}" if suffix.endswith(".bit"): archive.writestr(member, bit) elif suffix.endswith("BITSTREAM-SHA256.txt"): archive.writestr(member, f"{bit_sha}\n".encode()) elif suffix.endswith(".json"): archive.writestr(member, b"{}\n") else: archive.writestr(member, b"# note\n") with zipfile.ZipFile(zip_path) as archive: path_failures = selftest.check_final_evidence_paths( archive, list(archive.namelist()) ) semantic = selftest.check_final_canonical_evidence( archive, list(archive.namelist()) ) self.assertEqual(path_failures, [], path_failures) # Empty `{}` JSON must fail semantic selftest (Round-10). self.assertTrue(semantic, "empty JSON fixtures must not pass semantic selftest") def test_source_check_rejects_untracked_formal_workdir(self) -> None: selftest = load_selftest() import hashlib with tempfile.TemporaryDirectory() as tmp: zip_path = Path(tmp) / "bad.zip" formal = b"module alt_config_limit_normalize_formal; endmodule\n" head = "a" * 40 tree = { "schema": "cpld-review-git-tree-manifest-v1", "head": head, "file_count": 1, "files": [ { "path": "tests/formal/alt_config_limit_normalize_formal.v", "sha256": hashlib.sha256(formal).hexdigest(), "size": len(formal), } ], } packaged = { "schema": "prod2u-packaged-source-manifest-v1", "source_snapshot_mode": "exact_commit_tracked_subset", "delivery_commit": head, "policy_excluded": [], } with zipfile.ZipFile(zip_path, "w") as archive: archive.writestr( "CPLD/source/tests/formal/alt_config_limit_normalize_formal.v", formal, ) # Inject untracked SBY PASS marker — must fail closed. archive.writestr( "CPLD/source/tests/formal/alt_config_limit_normalize_bmc/PASS", b"PASS\n", ) archive.writestr( "CPLD/meta/git/tree-manifest.json", (json.dumps(tree) + "\n").encode(), ) archive.writestr( "CPLD/meta/git/packaged-source-manifest.json", (json.dumps(packaged) + "\n").encode(), ) with zipfile.ZipFile(zip_path) as archive: failures = selftest.check_source_tracked_subset(archive) self.assertTrue( any(item.startswith("untracked_source_member:") for item in failures), failures, ) self.assertTrue( any(item.startswith("formal_workdir_in_source:") for item in failures), failures, ) def test_source_check_rejects_missing_tracked_formal_wrapper(self) -> None: selftest = load_selftest() import hashlib with tempfile.TemporaryDirectory() as tmp: zip_path = Path(tmp) / "missing.zip" ok = b"module ok; endmodule\n" head = "b" * 40 tree = { "schema": "cpld-review-git-tree-manifest-v1", "head": head, "file_count": 2, "files": [ { "path": "src/ok.v", "sha256": hashlib.sha256(ok).hexdigest(), "size": len(ok), }, { "path": "tests/formal/alt_config_limit_normalize_formal.v", "sha256": "c" * 64, "size": 1, }, ], } packaged = { "schema": "prod2u-packaged-source-manifest-v1", "source_snapshot_mode": "exact_commit_tracked_subset", "delivery_commit": head, "policy_excluded": [], } with zipfile.ZipFile(zip_path, "w") as archive: archive.writestr("CPLD/source/src/ok.v", ok) # Canonical formal missing; only a generated-looking copy would be wrong. archive.writestr( "CPLD/meta/git/tree-manifest.json", (json.dumps(tree) + "\n").encode(), ) archive.writestr( "CPLD/meta/git/packaged-source-manifest.json", (json.dumps(packaged) + "\n").encode(), ) with zipfile.ZipFile(zip_path) as archive: failures = selftest.check_source_tracked_subset(archive) self.assertTrue( any("missing_required_tracked_source" in item for item in failures), failures, ) if __name__ == "__main__": unittest.main()