Sfoglia il codice sorgente

test: add adversarial review-compact packaging fixtures (Lane P6)

Plant PDF/BRD/DSN/vendor/secret/symlink/traversal/Unicode/bundle-leak attack trees under tests/ and assert tip fail-closed APIs plus gated review-compact policy (skip until P1 registers the profile).

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 mesi fa
parent
commit
a313e7d6be

+ 18 - 0
tests/fixtures/package_adversarial/manifest.json

@@ -0,0 +1,18 @@
+{
+  "schema": "prod2u-package-adversarial-fixtures-v1",
+  "lane": "P6",
+  "description": "Attacker trees for review-compact fail-closed packaging. Payloads are synthetic markers, not real IP.",
+  "vectors": [
+    {"id": "pdf-schematic", "path": "payloads/sneaky-schematic.pdf", "expect": "exclude_or_fail_closed"},
+    {"id": "brd-board", "path": "payloads/sneaky-main.brd", "expect": "exclude_or_fail_closed"},
+    {"id": "dsn-orcad", "path": "payloads/sneaky.dsn", "expect": "exclude_or_fail_closed"},
+    {"id": "vendor-installer", "path": "payloads/td_release_2026.1_fake.zip", "expect": "exclude_or_fail_closed"},
+    {"id": "license-archive", "path": "payloads/vendor-license.zip", "expect": "exclude_or_fail_closed"},
+    {"id": "license-file", "path": "payloads/Anlogic.lic", "expect": "exclude_or_fail_closed"},
+    {"id": "private-key", "path": "payloads/id_ed25519", "expect": "exclude_or_fail_closed"},
+    {"id": "dotenv", "path": "payloads/dotenv.env", "expect": "exclude_or_fail_closed"},
+    {"id": "path-traversal-zip", "path": "payloads/traversal-member.zip", "expect": "fail_closed"},
+    {"id": "unicode-conflict-a", "path": "payloads/unicode-cafe-nfc.txt", "expect": "collision_or_normalize"},
+    {"id": "unicode-conflict-b", "path": "payloads/unicode-cafe-nfd.txt", "expect": "collision_or_normalize"}
+  ]
+}

+ 1 - 0
tests/fixtures/package_adversarial/payloads/dotenv.env

@@ -0,0 +1 @@
+SECRET=should-never-pack

+ 3 - 0
tests/fixtures/package_adversarial/payloads/id_ed25519

@@ -0,0 +1,3 @@
+-----BEGIN PRIVATE KEY-----
+ADVERSARIAL_FIXTURE_NOT_A_REAL_KEY
+-----END PRIVATE KEY-----

+ 1 - 0
tests/fixtures/package_adversarial/payloads/sneaky-main.brd

@@ -0,0 +1 @@
+%ADV-BRD-FIXTURE%

+ 1 - 0
tests/fixtures/package_adversarial/payloads/sneaky-schematic.pdf

@@ -0,0 +1 @@
+%PDF-1.4 ADV-FIXTURE

+ 1 - 0
tests/fixtures/package_adversarial/payloads/sneaky.dsn

@@ -0,0 +1 @@
+(dsn sneaky)

+ 1 - 0
tests/fixtures/package_adversarial/payloads/unicode-cafe-nfc.txt

@@ -0,0 +1 @@
+nfc cafe

+ 1 - 0
tests/fixtures/package_adversarial/payloads/unicode-cafe-nfd.txt

@@ -0,0 +1 @@
+nfd cafe

+ 222 - 0
tests/unit/package_review_compact_contract.py

@@ -0,0 +1,222 @@
+#!/usr/bin/env python3
+"""Documented review-compact packaging contract for adversarial tests (Lane P6).
+
+P1 owns packager production code. Until ``review-compact`` appears in
+``HANDOFF_PROFILES``, gated tests skip with an explicit reason. This module
+stubs the intended exclusion / provenance policy so fixtures and assertions
+turn green when P1 lands without rewriting attacker trees.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+from types import ModuleType
+
+ROOT = Path(__file__).resolve().parents[2]
+REVIEW_COMPACT_PROFILE = "review-compact"
+DEFAULT_REVIEW_COMPACT_INCLUDE_GIT_BUNDLE = False
+DEFAULT_REVIEW_COMPACT_INCLUDE_FULL_HISTORY = False
+
+# Large originals / vendor / runtime leakage that must not enter review-compact.
+REVIEW_COMPACT_EXCLUDED_PREFIXES: tuple[tuple[str, str], ...] = (
+    ("reference/original/board", "compact_excludes_original_board"),
+    ("reference/original/schematics", "compact_excludes_original_schematics"),
+    ("reference/original/diagrams", "compact_excludes_original_diagrams"),
+    ("reference/original/local_archives", "compact_excludes_original_local_archives"),
+    ("anlogic_cd", "vendor_installer_payload"),
+    ("td/build", "td_build_output"),
+    ("runs", "run_state_directory"),
+    ("node_modules", "node_modules_runtime"),
+    (".venv", "virtual_environment"),
+    ("venv", "virtual_environment"),
+)
+
+REVIEW_COMPACT_EXCLUDED_BASENAMES: tuple[tuple[str, str], ...] = (
+    (".env", "secret_environment_file"),
+    ("anlogic.lic", "credential_or_license_file"),
+    ("id_rsa", "private_key_file"),
+    ("id_ed25519", "private_key_file"),
+    ("evidence-batch-summary.txt", "old_run_or_batch_summary"),
+)
+
+# Suffixes that sneak reference blobs into compact unless under an allowlisted fixture path.
+REVIEW_COMPACT_BLOCKED_SUFFIXES = frozenset({".pdf", ".brd", ".dsn", ".sch"})
+REVIEW_COMPACT_FIXTURE_ALLOW_PREFIXES = (
+    "tests/board_viewer/fixtures/",
+    "tests/fixtures/",
+)
+
+# Vendor installer / license archive name patterns (basename, casefold).
+VENDOR_INSTALLER_PREFIXES = ("bw_release_", "td_release_", "oss-cad-suite")
+VENDOR_ARCHIVE_SUFFIXES = frozenset({".zip", ".tgz", ".tar", ".gz", ".7z", ".rar"})
+
+GIT_BUNDLE_MEMBER_MARKERS = (
+    "git-history/",
+    ".bundle",
+    "repo.bundle",
+    "workspace-current.bundle",
+)
+
+
+def load_handoff() -> ModuleType:
+    tools = str(ROOT / "tools")
+    if tools not in sys.path:
+        sys.path.insert(0, tools)
+    import package_agent_handoff as handoff  # noqa: WPS433
+
+    return handoff
+
+
+def load_analyzer() -> ModuleType:
+    module_path = ROOT / "package_for_agent_analysis.py"
+    spec = importlib.util.spec_from_file_location("package_for_agent_analysis", module_path)
+    if spec is None or spec.loader is None:
+        raise RuntimeError("unable to load package_for_agent_analysis")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+def handoff_profiles() -> frozenset[str]:
+    handoff = load_handoff()
+    profiles = getattr(handoff, "HANDOFF_PROFILES", frozenset())
+    return frozenset(str(item) for item in profiles)
+
+
+def review_compact_available() -> bool:
+    return REVIEW_COMPACT_PROFILE in handoff_profiles()
+
+
+def require_review_compact(testcase) -> None:
+    """Skip gated tests until P1 registers the profile enum."""
+    if not review_compact_available():
+        testcase.skipTest(
+            "review-compact profile not in HANDOFF_PROFILES yet (pending P1 packager core)"
+        )
+
+
+def is_under(relative: str, prefix: str) -> bool:
+    lower = relative.casefold().strip("/")
+    pref = prefix.casefold().strip("/")
+    return lower == pref or lower.startswith(pref + "/")
+
+
+def _basename(relative: str) -> str:
+    return relative.casefold().rsplit("/", 1)[-1]
+
+
+def _suffix(relative: str) -> str:
+    name = _basename(relative)
+    dot = name.rfind(".")
+    return name[dot:] if dot >= 0 else ""
+
+
+def fixture_path_allowlisted(relative: str) -> bool:
+    lower = relative.casefold().replace("\\", "/")
+    return any(lower.startswith(prefix) or f"/{prefix}" in f"/{lower}" for prefix in REVIEW_COMPACT_FIXTURE_ALLOW_PREFIXES)
+
+
+def intended_review_compact_exclusion_reason(relative: str, *, is_dir: bool) -> str | None:
+    """Intended fail-closed / policy-exclude rules for review-compact (P1 contract).
+
+    Tests assert live packager output against this helper once the profile exists.
+    """
+    del is_dir
+    lower = relative.casefold().replace("\\", "/")
+    name = _basename(relative)
+    suffix = _suffix(relative)
+
+    if name == ".env" or (
+        name.startswith(".env.")
+        and not name.endswith((".example", ".sample", ".template", ".dist"))
+    ):
+        return "secret_environment_file"
+    if name in {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"} or name.startswith("id_rsa."):
+        return "private_key_file"
+    if name.endswith((".key", ".pfx", ".p12", ".lic")) or name == "anlogic.lic":
+        return "credential_or_license_file"
+    if name.startswith(".run_id"):
+        return "local_run_id_marker"
+    if name.startswith("td_") and suffix in {".log", ".logw"}:
+        return "td_root_runtime_log"
+    if name == "evidence-batch-summary.txt":
+        return "old_run_or_batch_summary"
+    if "license" in name and suffix in VENDOR_ARCHIVE_SUFFIXES:
+        return "license_archive"
+
+    for prefix, reason in REVIEW_COMPACT_EXCLUDED_PREFIXES:
+        if is_under(lower, prefix):
+            return reason
+
+    if any(name.startswith(prefix) for prefix in VENDOR_INSTALLER_PREFIXES) and (
+        suffix in VENDOR_ARCHIVE_SUFFIXES or suffix == ".exe"
+    ):
+        return "vendor_toolchain_archive"
+    if suffix == ".exe":
+        return "vendor_executable"
+
+    for component in lower.split("/"):
+        if component in {"node_modules", ".venv", "venv"}:
+            return {
+                "node_modules": "node_modules_runtime",
+                ".venv": "virtual_environment",
+                "venv": "virtual_environment",
+            }[component]
+
+    if suffix in REVIEW_COMPACT_BLOCKED_SUFFIXES and not fixture_path_allowlisted(relative):
+        return "compact_excludes_reference_design_blob"
+
+    return None
+
+
+def path_looks_like_full_git_bundle(member: str) -> bool:
+    lower = member.casefold().replace("\\", "/")
+    if lower.endswith(".bundle") or "/git-history/" in f"/{lower}/":
+        return True
+    return any(marker in lower for marker in GIT_BUNDLE_MEMBER_MARKERS if marker != ".bundle")
+
+
+def assert_no_full_git_bundle(members: list[str], *, testcase) -> None:
+    offenders = [name for name in members if path_looks_like_full_git_bundle(name)]
+    testcase.assertEqual(
+        offenders,
+        [],
+        "review-compact must not ship a full git bundle that can carry excluded reference blobs",
+    )
+
+
+def adversarial_fixture_relatives() -> dict[str, bytes]:
+    """Canonical sneaky paths planted into disposable source trees."""
+    private_key = b"-----BEGIN PRIVATE KEY-----\nADVERSARIAL_FIXTURE_NOT_A_REAL_KEY\n-----END PRIVATE KEY-----\n"
+    return {
+        "reference/original/board/sneaky-main.brd": b"%ADV-BRD-FIXTURE%\n",
+        "reference/original/schematics/sneaky-schematic.pdf": b"%PDF-1.4 ADV-FIXTURE\n",
+        "reference/original/diagrams/sneaky-diagram.pdf": b"%PDF-1.4 ADV-DIAGRAM\n",
+        "reference/original/local_archives/vendor-license.zip": b"PK\x03\x04ADV-LICENSE-ZIP",
+        "reference/original/board/sneaky.dsn": b"(dsn sneaky)\n",
+        "docs/sneak/leak.pdf": b"%PDF-1.4 SNEAK-INTO-DOCS\n",
+        "src/rtl/leak.brd": b"%ADV-BRD-IN-SRC%\n",
+        "src/rtl/leak.dsn": b"(dsn leak)\n",
+        "td_release_2026.1_fake.zip": b"PK\x03\x04ADV-TD-RELEASE",
+        "oss-cad-suite-linux.tgz": b"\x1f\x8bADV-OSSCAD",
+        "anlogic_cd/installer/setup.exe": b"MZADV-INSTALLER",
+        "reference/original/local_archives/Anlogic.lic": b"ADV-LICENSE-KEY\n",
+        "config/.env": b"SECRET=should-never-pack\n",
+        "secrets/id_ed25519": private_key,
+        "node_modules/left-pad/index.js": b"module.exports=function(){}\n",
+        ".venv/bin/python": b"#!/adversarial-venv\n",
+        "venv/lib/site.py": b"# adversarial venv\n",
+        "td/build/current/design.bit": b"ADV-BITSTREAM",
+        "td/build/current/design.db": b"ADV-DB",
+        "runs/old-matrix/receipt.json": b'{"status":"stale"}\n',
+        "td_20260804_sneaky.log": b"old td run log\n",
+        "evidence-batch-summary.txt": b"stale batch summary\n",
+        ".run_id": b"packager-compact-adversarial\n",
+        ".run_id_secondary": b"another-run-marker\n",
+        "receipts/dup-a.json": b'{"id":"dup","sha":"same"}\n',
+        "receipts/dup-b.json": b'{"id":"dup","sha":"same"}\n',
+        "src/rtl/core.v": b"module core; endmodule\n",
+        "tests/board_viewer/fixtures/keep-small.txt": b"allowlisted fixture\n",
+    }

+ 572 - 0
tests/unit/test_package_adversarial_compact.py

@@ -0,0 +1,572 @@
+#!/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,
+    assert_no_full_git_bundle,
+    handoff_profiles,
+    intended_review_compact_exclusion_reason,
+    load_analyzer,
+    load_handoff,
+    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"
+PAYLOAD_ROOT = FIXTURE_ROOT / "payloads"
+
+
+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")
+        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)
+        for item in payload["vectors"]:
+            path = FIXTURE_ROOT / item["path"]
+            self.assertTrue(path.is_file(), f"missing fixture payload {path}")
+            self.assertGreater(path.stat().st_size, 0, f"empty fixture payload {path}")
+
+    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",
+            "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"
+            archive = write_file(
+                source,
+                "docs/traversal-member.zip",
+                (PAYLOAD_ROOT / "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 = b"-----BEGIN PRIVATE KEY-----\nsecret\n-----END PRIVATE KEY-----\n"
+        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 = b"-----BEGIN PRIVATE KEY-----\nsecret\n-----END PRIVATE KEY-----\n"
+        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",
+                "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,
+            )
+            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 DiskFixturePayloadTests(unittest.TestCase):
+    def test_payload_private_key_and_traversal_bytes(self) -> None:
+        key = (PAYLOAD_ROOT / "id_ed25519").read_bytes()
+        self.assertIn(b"PRIVATE KEY", key)
+        with zipfile.ZipFile(PAYLOAD_ROOT / "traversal-member.zip") as archive:
+            members = archive.namelist()
+        self.assertTrue(any(".." in name or name.startswith("../") for name in members))
+
+
+if __name__ == "__main__":
+    unittest.main()