| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231 |
- #!/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_private_key_bytes() -> bytes:
- """Load PEM-like fixture bytes without embedding secret markers in this module.
- The payload file basename ``id_ed25519`` is path-excluded from packaging; keeping
- the PEM text out of this helper avoids content-scan false positives on the helper.
- """
- path = ROOT / "tests" / "fixtures" / "package_adversarial" / "payloads" / "id_ed25519"
- return path.read_bytes()
- def adversarial_fixture_relatives() -> dict[str, bytes]:
- """Canonical sneaky paths planted into disposable source trees."""
- 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": adversarial_private_key_bytes(),
- "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",
- }
|