#!/usr/bin/env python3 """Lane P6: adversarial packaging fixtures for review-compact fail-closed policy. Ownership: tests/unit/test_package_* and tests/fixtures/package_adversarial only. Does not weaken packager production policy. review-compact gated cases skip until P1 registers the profile; tip cases exercise current fail-closed APIs. """ from __future__ import annotations import json import shutil import subprocess import sys import tempfile import unicodedata import unittest import zipfile from pathlib import Path UNIT_DIR = Path(__file__).resolve().parent if str(UNIT_DIR) not in sys.path: sys.path.insert(0, str(UNIT_DIR)) from package_review_compact_contract import ( # noqa: E402 DEFAULT_REVIEW_COMPACT_INCLUDE_FULL_HISTORY, DEFAULT_REVIEW_COMPACT_INCLUDE_GIT_BUNDLE, REVIEW_COMPACT_PROFILE, adversarial_fixture_relatives, adversarial_private_key_bytes, assert_no_full_git_bundle, handoff_profiles, intended_review_compact_exclusion_reason, load_analyzer, load_handoff, materialize_adversarial_payloads, path_looks_like_full_git_bundle, require_review_compact, review_compact_available, ) ROOT = Path(__file__).resolve().parents[2] FIXTURE_ROOT = ROOT / "tests" / "fixtures" / "package_adversarial" def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path: path = root / Path(relative) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) return path def plant_adversarial_tree(root: Path) -> dict[str, bytes]: payloads = adversarial_fixture_relatives() for relative, data in payloads.items(): write_file(root, relative, data) return payloads class ReviewCompactContractUnitTests(unittest.TestCase): """Always-on contract documentation (no packager profile required).""" maxDiff = None def test_contract_defaults_forbid_full_bundle_and_history(self) -> None: self.assertFalse(DEFAULT_REVIEW_COMPACT_INCLUDE_GIT_BUNDLE) self.assertFalse(DEFAULT_REVIEW_COMPACT_INCLUDE_FULL_HISTORY) self.assertEqual(REVIEW_COMPACT_PROFILE, "review-compact") def test_fixture_manifest_lists_attack_vectors(self) -> None: manifest_path = FIXTURE_ROOT / "manifest.json" self.assertTrue(manifest_path.is_file()) payload = json.loads(manifest_path.read_text(encoding="utf-8")) self.assertEqual(payload["schema"], "prod2u-package-adversarial-fixtures-v1") self.assertEqual(payload.get("payload_policy"), "generate_in_temp_dir") ids = {item["id"] for item in payload["vectors"]} for required in { "pdf-schematic", "brd-board", "dsn-orcad", "vendor-installer", "license-archive", "private-key", "dotenv", "path-traversal-zip", }: self.assertIn(required, ids) # Payloads are generated in temp; long-term payloads/ must not be required. self.assertFalse((FIXTURE_ROOT / "payloads").exists()) with tempfile.TemporaryDirectory() as tmp: written = materialize_adversarial_payloads(Path(tmp) / "payloads") for item in payload["vectors"]: name = item.get("temp_name") or Path(str(item.get("path", ""))).name self.assertIn(name, written) self.assertGreater(written[name].stat().st_size, 0, name) def test_intended_policy_excludes_sneaky_reference_and_secrets(self) -> None: cases = { "reference/original/board/sneaky-main.brd": "compact_excludes_original_board", "reference/original/schematics/sneaky-schematic.pdf": "compact_excludes_original_schematics", "docs/sneak/leak.pdf": "compact_excludes_reference_design_blob", "src/rtl/leak.brd": "compact_excludes_reference_design_blob", "src/rtl/leak.dsn": "compact_excludes_reference_design_blob", "td_release_2026.1_fake.zip": "vendor_toolchain_archive", "oss-cad-suite-linux.tgz": "vendor_toolchain_archive", "anlogic_cd/installer/setup.exe": "vendor_installer_payload", "config/.env": "secret_environment_file", "secrets/id_ed25519": "private_key_file", "node_modules/left-pad/index.js": "node_modules_runtime", ".venv/bin/python": "virtual_environment", "td/build/current/design.bit": "td_build_output", "runs/old-matrix/receipt.json": "run_state_directory", "td_20260804_sneaky.log": "td_root_runtime_log", ".run_id": "local_run_id_marker", "evidence-batch-summary.txt": "old_run_or_batch_summary", "reference/original/local_archives/Anlogic.lic": "credential_or_license_file", } for relative, expected in cases.items(): self.assertEqual( intended_review_compact_exclusion_reason(relative, is_dir=False), expected, relative, ) # Ancestor prefix still covers non-license junk under local_archives. self.assertEqual( intended_review_compact_exclusion_reason( "reference/original/local_archives/vendor-blob.bin", is_dir=False, ), "compact_excludes_original_local_archives", ) self.assertIsNone( intended_review_compact_exclusion_reason( "tests/board_viewer/fixtures/keep-small.txt", is_dir=False, ) ) self.assertIsNone( intended_review_compact_exclusion_reason("src/rtl/core.v", is_dir=False) ) def test_bundle_path_detector(self) -> None: self.assertTrue(path_looks_like_full_git_bundle("git-history/workspace-current.bundle")) self.assertTrue(path_looks_like_full_git_bundle("CPLD/git-history/repo.bundle")) self.assertFalse(path_looks_like_full_git_bundle("meta/git-status.txt")) self.assertFalse(path_looks_like_full_git_bundle("source/src/rtl/core.v")) class TipFailClosedAdversarialTests(unittest.TestCase): """Exercise current packager APIs with sneaky trees (should pass on tip).""" maxDiff = None def test_analysis_scan_excludes_secrets_vendor_venv_td_and_src_board_files(self) -> None: analyzer = load_analyzer() handoff = load_handoff() with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "src" plant_adversarial_tree(root) # Symlink escape planted separately (raises if not excluded first). candidates, excluded, _ = analyzer.scan_analysis_root(root) included = {item.relative for item in candidates} excluded_by_path = {item["path"]: item["rule"] for item in excluded} self.assertIn("src/rtl/core.v", included) self.assertIn("tests/board_viewer/fixtures/keep-small.txt", included) self.assertNotIn("config/.env", included) self.assertEqual(excluded_by_path.get("config/.env"), "secret_environment_file") self.assertNotIn("secrets/id_ed25519", included) self.assertEqual(excluded_by_path.get("secrets/id_ed25519"), "private_key_file") self.assertNotIn("node_modules", included) self.assertEqual(excluded_by_path.get("node_modules"), "node_modules_runtime") self.assertNotIn(".venv", included) self.assertEqual(excluded_by_path.get(".venv"), "virtual_environment") self.assertEqual(excluded_by_path.get("venv"), "virtual_environment") self.assertNotIn("td/build", included) self.assertEqual(excluded_by_path.get("td/build"), "td_build_output") self.assertNotIn("runs", included) self.assertEqual(excluded_by_path.get("runs"), "run_state_directory") self.assertNotIn("anlogic_cd", included) self.assertEqual(excluded_by_path.get("anlogic_cd"), "vendor_installer_payload") self.assertNotIn("td_release_2026.1_fake.zip", included) self.assertIn( excluded_by_path.get("td_release_2026.1_fake.zip"), {"vendor_toolchain_archive", "archive_file_not_source"}, ) self.assertNotIn("src/rtl/leak.brd", included) self.assertEqual(excluded_by_path.get("src/rtl/leak.brd"), "board_design_file") self.assertNotIn("src/rtl/leak.dsn", included) self.assertEqual(excluded_by_path.get("src/rtl/leak.dsn"), "board_design_file") self.assertNotIn( "reference/original/local_archives/Anlogic.lic", included, ) self.assertEqual( excluded_by_path.get("reference/original/local_archives/Anlogic.lic"), "credential_or_license_file", ) # Tip full profile still keeps reference originals; compact contract forbids them. self.assertIn("reference/original/board/sneaky-main.brd", included) self.assertEqual( intended_review_compact_exclusion_reason( "reference/original/board/sneaky-main.brd", is_dir=False, ), "compact_excludes_original_board", ) self.assertIsNotNone(handoff.HANDOFF_PROFILES) def test_handoff_scan_excludes_old_td_logs_and_vendor_archives(self) -> None: handoff = load_handoff() with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "src" write_file(root, "src/rtl/core.v", b"module core; endmodule\n") write_file(root, "td_20260804_sneaky.log", b"old td run log\n") write_file(root, "td_release_2026.1_fake.zip", b"PK\x03\x04ADV") write_file(root, "license-pack.zip", b"PK\x03\x04ADV-LIC") write_file(root, "vendor/tool.exe", b"MZADV") candidates, excluded, _ = handoff.scan_tree(root) included = {item.relative for item in candidates} excluded_by_path = {item["path"]: item["rule"] for item in excluded} self.assertIn("src/rtl/core.v", included) self.assertEqual(excluded_by_path["td_20260804_sneaky.log"], "td_root_runtime_log") self.assertEqual( excluded_by_path["td_release_2026.1_fake.zip"], "vendor_toolchain_archive", ) self.assertEqual(excluded_by_path["license-pack.zip"], "license_archive") self.assertEqual(excluded_by_path["vendor/tool.exe"], "vendor_executable") def test_symlink_escape_refuses_packaging(self) -> None: handoff = load_handoff() with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) root = temp / "src" outside = temp / "outside" write_file(root, "src/rtl/core.v", b"module core; endmodule\n") write_file(outside, "secret.txt", b"must-never-follow\n") link = root / "docs" / "escape-link" link.parent.mkdir(parents=True, exist_ok=True) link.symlink_to(outside, target_is_directory=True) with self.assertRaisesRegex(handoff.PackagingError, "undeclared reparse point"): handoff.scan_tree(root) def test_archive_path_traversal_members_fail_closed(self) -> None: handoff = load_handoff() with tempfile.TemporaryDirectory() as tmp: source = Path(tmp) / "source" payloads = materialize_adversarial_payloads(Path(tmp) / "payloads") archive = write_file( source, "docs/traversal-member.zip", payloads["traversal-member.zip"].read_bytes(), ) # Tip analysis excludes bare .zip; plant under a path that handoff scan keeps # so archive member traversal is exercised via scan_candidate_archive. candidates, _, _ = handoff.scan_tree(source) # If .zip is excluded by a future rule, fall back to direct Candidate. match = next((item for item in candidates if item.absolute == archive), None) if match is None: st = archive.stat() match = handoff.Candidate( archive, "docs/traversal-member.zip", st.st_size, st.st_mtime_ns, int(st.st_dev), int(st.st_ino), int(st.st_mode), ) with self.assertRaisesRegex(handoff.PackagingError, "unsafe archive member"): handoff.scan_candidate_archive(match) def test_unicode_nfc_nfd_collision_fails_closed(self) -> None: handoff = load_handoff() with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "src" write_file(root, "src/rtl/core.v", b"module core; endmodule\n") # Same Windows collision key via NFC vs NFD "é" nfc_name = "caf" + unicodedata.normalize("NFC", "é") + ".txt" nfd_name = "caf" + unicodedata.normalize("NFD", "é") + ".txt" self.assertNotEqual(nfc_name, nfd_name) self.assertEqual( handoff.windows_collision_key(f"docs/{nfc_name}"), handoff.windows_collision_key(f"docs/{nfd_name}"), ) write_file(root, f"docs/{nfc_name}", b"nfc\n") write_file(root, f"docs/{nfd_name}", b"nfd\n") with self.assertRaisesRegex(handoff.PackagingError, "Windows ZIP path collision"): handoff.scan_tree(root) def test_private_key_pem_content_fails_closed(self) -> None: handoff = load_handoff() marker = adversarial_private_key_bytes() with self.assertRaises(handoff.PackagingError): handoff.scan_secret_markers(marker, b"", "docs/leaked.pem") def test_duplicate_identical_evidence_is_physically_deduped(self) -> None: analyzer = load_analyzer() handoff = load_handoff() with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) # Content dedup threshold is 4096 bytes (or .pdf/.brd names). payload = (b'{"id":"dup","pad":"' + (b"A" * 4200) + b'"}\n') a = write_file(temp / "source", "receipts/dup-a.json", payload) b = write_file(temp / "source", "receipts/dup-b.json", payload) items = ( analyzer.make_package_item( a, relative="workspace-current/receipts/dup-a.json", category="core", source_id="workspace-current", ), analyzer.make_package_item( b, relative="workspace-current/receipts/dup-b.json", category="core", source_id="workspace-current", ), ) inventory = [ { "path": item.candidate.relative, "sha256": handoff.sha256_file(item.candidate.absolute), "size": item.candidate.size, } for item in items ] kept, dedup_records, excluded = analyzer.apply_content_dedup(items, inventory) kept_paths = {item.candidate.relative for item in kept} self.assertEqual(len(kept_paths), 1) self.assertEqual(len(dedup_records), 1) self.assertEqual( dedup_records[0]["reason"], "identical_content_single_physical_copy", ) self.assertTrue( any(item["rule"] == "duplicate_content_logical_alias" for item in excluded) ) def test_git_ref_path_traversal_not_followed(self) -> None: handoff = load_handoff() with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) git_dir = temp / "source" / ".git" write_file(git_dir, "HEAD", b"ref: ../../outside-ref\n") write_file(temp, "outside-ref", b"0123456789abcdef0123456789abcdef01234567\n") self.assertEqual(handoff.read_head_metadata(git_dir), (None, None)) def test_nested_archive_secret_fails_closed_on_audit(self) -> None: handoff = load_handoff() marker = adversarial_private_key_bytes() with tempfile.TemporaryDirectory() as tmp: source = Path(tmp) / "source" buf_path = source / "docs" / "nested-secret.bin" buf_path.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(buf_path, "w") as zf: zf.writestr("payload/secret.pem", marker) st = buf_path.stat() candidate = handoff.Candidate( buf_path, "docs/nested-secret.bin", st.st_size, st.st_mtime_ns, int(st.st_dev), int(st.st_ino), int(st.st_mode), ) with self.assertRaisesRegex(handoff.PackagingError, "secret|PRIVATE KEY|credential"): handoff.scan_candidate_archive(candidate) class ReviewCompactProfileAdversarialTests(unittest.TestCase): """Gated on P1 registering review-compact; skip with explicit reason otherwise.""" maxDiff = None def test_profile_enum_documents_availability(self) -> None: profiles = handoff_profiles() self.assertIn("full", profiles) self.assertIn("code-only", profiles) if not review_compact_available(): self.skipTest( "review-compact profile not in HANDOFF_PROFILES yet (pending P1 packager core)" ) self.assertIn(REVIEW_COMPACT_PROFILE, profiles) def test_review_compact_excludes_reference_pdf_brd_dsn_and_vendor(self) -> None: require_review_compact(self) analyzer = load_analyzer() with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "src" plant_adversarial_tree(root) candidates, excluded, _ = analyzer.scan_analysis_root( root, profile=REVIEW_COMPACT_PROFILE, ) included = {item.relative for item in candidates} excluded_by_path = {item["path"]: item["rule"] for item in excluded} self.assertIn("src/rtl/core.v", included) self.assertIn("tests/board_viewer/fixtures/keep-small.txt", included) forbidden = [ "reference/original/board/sneaky-main.brd", "reference/original/schematics/sneaky-schematic.pdf", "reference/original/diagrams/sneaky-diagram.pdf", "reference/original/board/sneaky.dsn", "reference/original/local_archives/vendor-license.zip", "docs/sneak/leak.pdf", "src/rtl/leak.brd", "src/rtl/leak.dsn", "td_release_2026.1_fake.zip", "oss-cad-suite-linux.tgz", "anlogic_cd/installer/setup.exe", "config/.env", "secrets/id_ed25519", "node_modules/left-pad/index.js", ".venv/bin/python", "td/build/current/design.bit", "runs/old-matrix/receipt.json", "td_20260804_sneaky.log", "evidence-batch-summary.txt", ".run_id", ] for relative in forbidden: self.assertNotIn(relative, included, relative) # Either direct exclusion or ancestor exclusion is acceptable. reason = excluded_by_path.get(relative) or next( ( rule for path, rule in excluded_by_path.items() if relative == path or relative.startswith(path.rstrip("/") + "/") ), None, ) self.assertIsNotNone(reason, f"expected exclusion for {relative}; excluded={excluded_by_path}") intended = intended_review_compact_exclusion_reason(relative, is_dir=False) self.assertIsNotNone(intended, relative) def test_review_compact_default_omits_full_git_bundle(self) -> None: require_review_compact(self) analyzer = load_analyzer() git = shutil.which("git") if not git: self.skipTest("Git is required") with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) repo = temp / "repo" repo.mkdir() subprocess.run([git, "init", "-q", str(repo)], check=True) subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True) subprocess.run( [git, "-C", str(repo), "config", "user.email", "test@example.invalid"], check=True, ) # Plant a reference blob that must never ride along via full history bundle. write_file(repo, "reference/original/board/hidden.brd", b"%HIDDEN-BRD%\n") write_file(repo, "src/rtl/core.v", b"module core; endmodule\n") subprocess.run([git, "-C", str(repo), "add", "."], check=True) subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True) config = analyzer.HandoffConfig( max_zip_bytes=2_000_000, target_zip_bytes=1_500_000, external_sources=(), extra_exclusions=(), ) # Default compact must not require / include a full git bundle. kwargs = { "repo_root": repo, "config": config, "temp_root": temp / "run", "profile": REVIEW_COMPACT_PROFILE, } # Prefer packager default (include_git_bundle omitted). If API still # defaults True until P1 wires profile defaults, pass explicit False # only when the signature still requires the flag for non-full profiles. try: collection = analyzer.collect_analysis_inputs(**kwargs) except TypeError: collection = analyzer.collect_analysis_inputs( **kwargs, include_git_bundle=DEFAULT_REVIEW_COMPACT_INCLUDE_GIT_BUNDLE, ) except analyzer.PackagingError as exc: # full-profile-style hard requirement must not apply to compact. self.assertNotIn("git bundle", str(exc).lower()) raise member_paths = [item.candidate.relative for item in collection.items] assert_no_full_git_bundle(member_paths, testcase=self) # Also ensure hidden BRD is not present as a packaged path. self.assertFalse( any(path.casefold().endswith(".brd") for path in member_paths), member_paths, ) def test_review_compact_package_members_have_no_bundle_or_reference_blobs(self) -> None: require_review_compact(self) analyzer = load_analyzer() git = shutil.which("git") if not git: self.skipTest("Git is required") with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) repo = temp / "repo" repo.mkdir() subprocess.run([git, "init", "-q", str(repo)], check=True) subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True) subprocess.run( [git, "-C", str(repo), "config", "user.email", "test@example.invalid"], check=True, ) plant_adversarial_tree(repo) subprocess.run([git, "-C", str(repo), "add", "-A"], check=True) subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "adversarial"], check=True) config = analyzer.HandoffConfig( max_zip_bytes=5_000_000, target_zip_bytes=4_000_000, external_sources=(), extra_exclusions=(), ) try: collection = analyzer.collect_analysis_inputs( repo_root=repo, config=config, temp_root=temp / "run", profile=REVIEW_COMPACT_PROFILE, include_git_bundle=False, ) except TypeError: collection = analyzer.collect_analysis_inputs( repo_root=repo, config=config, temp_root=temp / "run", profile=REVIEW_COMPACT_PROFILE, ) result = analyzer.create_analysis_package( collection=collection, output_root=temp / "output", package_name="adv-compact", max_zip_bytes=5_000_000, target_zip_bytes=4_000_000, force=False, profile=REVIEW_COMPACT_PROFILE, ) package_dir = Path(result["output_dir"]) volume = package_dir / result["volumes"][0]["file"] with zipfile.ZipFile(volume) as archive: names = archive.namelist() assert_no_full_git_bundle(names, testcase=self) lowered = [name.casefold() for name in names] for needle in (".pdf", ".brd", ".dsn", "anlogic.lic", "/.env", "id_ed25519"): offenders = [name for name in lowered if needle in name] self.assertEqual(offenders, [], f"leaked {needle}: {offenders}") class TempAdversarialPayloadTests(unittest.TestCase): def test_payload_private_key_and_traversal_bytes_generated_in_temp(self) -> None: with tempfile.TemporaryDirectory() as tmp: payloads = materialize_adversarial_payloads(Path(tmp) / "payloads") key = payloads["id_ed25519"].read_bytes() self.assertIn(b"PRIVATE KEY", key) with zipfile.ZipFile(payloads["traversal-member.zip"]) as archive: members = archive.namelist() self.assertTrue(any(".." in name or name.startswith("../") for name in members)) # Compact must not rely on a long-lived payloads/ tree in the repo. self.assertFalse((FIXTURE_ROOT / "payloads").exists()) if __name__ == "__main__": unittest.main()