package_review_compact_contract.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #!/usr/bin/env python3
  2. """Documented review-compact packaging contract for adversarial tests (Lane P6).
  3. P1 owns packager production code. Until ``review-compact`` appears in
  4. ``HANDOFF_PROFILES``, gated tests skip with an explicit reason. This module
  5. stubs the intended exclusion / provenance policy so fixtures and assertions
  6. turn green when P1 lands without rewriting attacker trees.
  7. """
  8. from __future__ import annotations
  9. import importlib.util
  10. import sys
  11. from pathlib import Path
  12. from types import ModuleType
  13. ROOT = Path(__file__).resolve().parents[2]
  14. REVIEW_COMPACT_PROFILE = "review-compact"
  15. DEFAULT_REVIEW_COMPACT_INCLUDE_GIT_BUNDLE = False
  16. DEFAULT_REVIEW_COMPACT_INCLUDE_FULL_HISTORY = False
  17. # Large originals / vendor / runtime leakage that must not enter review-compact.
  18. REVIEW_COMPACT_EXCLUDED_PREFIXES: tuple[tuple[str, str], ...] = (
  19. ("reference/original/board", "compact_excludes_original_board"),
  20. ("reference/original/schematics", "compact_excludes_original_schematics"),
  21. ("reference/original/diagrams", "compact_excludes_original_diagrams"),
  22. ("reference/original/local_archives", "compact_excludes_original_local_archives"),
  23. ("anlogic_cd", "vendor_installer_payload"),
  24. ("td/build", "td_build_output"),
  25. ("runs", "run_state_directory"),
  26. ("node_modules", "node_modules_runtime"),
  27. (".venv", "virtual_environment"),
  28. ("venv", "virtual_environment"),
  29. )
  30. REVIEW_COMPACT_EXCLUDED_BASENAMES: tuple[tuple[str, str], ...] = (
  31. (".env", "secret_environment_file"),
  32. ("anlogic.lic", "credential_or_license_file"),
  33. ("id_rsa", "private_key_file"),
  34. ("id_ed25519", "private_key_file"),
  35. ("evidence-batch-summary.txt", "old_run_or_batch_summary"),
  36. )
  37. # Suffixes that sneak reference blobs into compact unless under an allowlisted fixture path.
  38. REVIEW_COMPACT_BLOCKED_SUFFIXES = frozenset({".pdf", ".brd", ".dsn", ".sch"})
  39. REVIEW_COMPACT_FIXTURE_ALLOW_PREFIXES = (
  40. "tests/board_viewer/fixtures/",
  41. "tests/fixtures/",
  42. )
  43. # Vendor installer / license archive name patterns (basename, casefold).
  44. VENDOR_INSTALLER_PREFIXES = ("bw_release_", "td_release_", "oss-cad-suite")
  45. VENDOR_ARCHIVE_SUFFIXES = frozenset({".zip", ".tgz", ".tar", ".gz", ".7z", ".rar"})
  46. GIT_BUNDLE_MEMBER_MARKERS = (
  47. "git-history/",
  48. ".bundle",
  49. "repo.bundle",
  50. "workspace-current.bundle",
  51. )
  52. def load_handoff() -> ModuleType:
  53. tools = str(ROOT / "tools")
  54. if tools not in sys.path:
  55. sys.path.insert(0, tools)
  56. import package_agent_handoff as handoff # noqa: WPS433
  57. return handoff
  58. def load_analyzer() -> ModuleType:
  59. module_path = ROOT / "package_for_agent_analysis.py"
  60. spec = importlib.util.spec_from_file_location("package_for_agent_analysis", module_path)
  61. if spec is None or spec.loader is None:
  62. raise RuntimeError("unable to load package_for_agent_analysis")
  63. module = importlib.util.module_from_spec(spec)
  64. spec.loader.exec_module(module)
  65. return module
  66. def handoff_profiles() -> frozenset[str]:
  67. handoff = load_handoff()
  68. profiles = getattr(handoff, "HANDOFF_PROFILES", frozenset())
  69. return frozenset(str(item) for item in profiles)
  70. def review_compact_available() -> bool:
  71. return REVIEW_COMPACT_PROFILE in handoff_profiles()
  72. def require_review_compact(testcase) -> None:
  73. """Skip gated tests until P1 registers the profile enum."""
  74. if not review_compact_available():
  75. testcase.skipTest(
  76. "review-compact profile not in HANDOFF_PROFILES yet (pending P1 packager core)"
  77. )
  78. def is_under(relative: str, prefix: str) -> bool:
  79. lower = relative.casefold().strip("/")
  80. pref = prefix.casefold().strip("/")
  81. return lower == pref or lower.startswith(pref + "/")
  82. def _basename(relative: str) -> str:
  83. return relative.casefold().rsplit("/", 1)[-1]
  84. def _suffix(relative: str) -> str:
  85. name = _basename(relative)
  86. dot = name.rfind(".")
  87. return name[dot:] if dot >= 0 else ""
  88. def fixture_path_allowlisted(relative: str) -> bool:
  89. lower = relative.casefold().replace("\\", "/")
  90. return any(lower.startswith(prefix) or f"/{prefix}" in f"/{lower}" for prefix in REVIEW_COMPACT_FIXTURE_ALLOW_PREFIXES)
  91. def intended_review_compact_exclusion_reason(relative: str, *, is_dir: bool) -> str | None:
  92. """Intended fail-closed / policy-exclude rules for review-compact (P1 contract).
  93. Tests assert live packager output against this helper once the profile exists.
  94. """
  95. del is_dir
  96. lower = relative.casefold().replace("\\", "/")
  97. name = _basename(relative)
  98. suffix = _suffix(relative)
  99. if name == ".env" or (
  100. name.startswith(".env.")
  101. and not name.endswith((".example", ".sample", ".template", ".dist"))
  102. ):
  103. return "secret_environment_file"
  104. if name in {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"} or name.startswith("id_rsa."):
  105. return "private_key_file"
  106. if name.endswith((".key", ".pfx", ".p12", ".lic")) or name == "anlogic.lic":
  107. return "credential_or_license_file"
  108. if name.startswith(".run_id"):
  109. return "local_run_id_marker"
  110. if name.startswith("td_") and suffix in {".log", ".logw"}:
  111. return "td_root_runtime_log"
  112. if name == "evidence-batch-summary.txt":
  113. return "old_run_or_batch_summary"
  114. if "license" in name and suffix in VENDOR_ARCHIVE_SUFFIXES:
  115. return "license_archive"
  116. for prefix, reason in REVIEW_COMPACT_EXCLUDED_PREFIXES:
  117. if is_under(lower, prefix):
  118. return reason
  119. if any(name.startswith(prefix) for prefix in VENDOR_INSTALLER_PREFIXES) and (
  120. suffix in VENDOR_ARCHIVE_SUFFIXES or suffix == ".exe"
  121. ):
  122. return "vendor_toolchain_archive"
  123. if suffix == ".exe":
  124. return "vendor_executable"
  125. for component in lower.split("/"):
  126. if component in {"node_modules", ".venv", "venv"}:
  127. return {
  128. "node_modules": "node_modules_runtime",
  129. ".venv": "virtual_environment",
  130. "venv": "virtual_environment",
  131. }[component]
  132. if suffix in REVIEW_COMPACT_BLOCKED_SUFFIXES and not fixture_path_allowlisted(relative):
  133. return "compact_excludes_reference_design_blob"
  134. return None
  135. def path_looks_like_full_git_bundle(member: str) -> bool:
  136. lower = member.casefold().replace("\\", "/")
  137. if lower.endswith(".bundle") or "/git-history/" in f"/{lower}/":
  138. return True
  139. return any(marker in lower for marker in GIT_BUNDLE_MEMBER_MARKERS if marker != ".bundle")
  140. def assert_no_full_git_bundle(members: list[str], *, testcase) -> None:
  141. offenders = [name for name in members if path_looks_like_full_git_bundle(name)]
  142. testcase.assertEqual(
  143. offenders,
  144. [],
  145. "review-compact must not ship a full git bundle that can carry excluded reference blobs",
  146. )
  147. def adversarial_private_key_bytes() -> bytes:
  148. """Load PEM-like fixture bytes without embedding secret markers in this module.
  149. The payload file basename ``id_ed25519`` is path-excluded from packaging; keeping
  150. the PEM text out of this helper avoids content-scan false positives on the helper.
  151. """
  152. path = ROOT / "tests" / "fixtures" / "package_adversarial" / "payloads" / "id_ed25519"
  153. return path.read_bytes()
  154. def adversarial_fixture_relatives() -> dict[str, bytes]:
  155. """Canonical sneaky paths planted into disposable source trees."""
  156. return {
  157. "reference/original/board/sneaky-main.brd": b"%ADV-BRD-FIXTURE%\n",
  158. "reference/original/schematics/sneaky-schematic.pdf": b"%PDF-1.4 ADV-FIXTURE\n",
  159. "reference/original/diagrams/sneaky-diagram.pdf": b"%PDF-1.4 ADV-DIAGRAM\n",
  160. "reference/original/local_archives/vendor-license.zip": b"PK\x03\x04ADV-LICENSE-ZIP",
  161. "reference/original/board/sneaky.dsn": b"(dsn sneaky)\n",
  162. "docs/sneak/leak.pdf": b"%PDF-1.4 SNEAK-INTO-DOCS\n",
  163. "src/rtl/leak.brd": b"%ADV-BRD-IN-SRC%\n",
  164. "src/rtl/leak.dsn": b"(dsn leak)\n",
  165. "td_release_2026.1_fake.zip": b"PK\x03\x04ADV-TD-RELEASE",
  166. "oss-cad-suite-linux.tgz": b"\x1f\x8bADV-OSSCAD",
  167. "anlogic_cd/installer/setup.exe": b"MZADV-INSTALLER",
  168. "reference/original/local_archives/Anlogic.lic": b"ADV-LICENSE-KEY\n",
  169. "config/.env": b"SECRET=should-never-pack\n",
  170. "secrets/id_ed25519": adversarial_private_key_bytes(),
  171. "node_modules/left-pad/index.js": b"module.exports=function(){}\n",
  172. ".venv/bin/python": b"#!/adversarial-venv\n",
  173. "venv/lib/site.py": b"# adversarial venv\n",
  174. "td/build/current/design.bit": b"ADV-BITSTREAM",
  175. "td/build/current/design.db": b"ADV-DB",
  176. "runs/old-matrix/receipt.json": b'{"status":"stale"}\n',
  177. "td_20260804_sneaky.log": b"old td run log\n",
  178. "evidence-batch-summary.txt": b"stale batch summary\n",
  179. ".run_id": b"packager-compact-adversarial\n",
  180. ".run_id_secondary": b"another-run-marker\n",
  181. "receipts/dup-a.json": b'{"id":"dup","sha":"same"}\n',
  182. "receipts/dup-b.json": b'{"id":"dup","sha":"same"}\n',
  183. "src/rtl/core.v": b"module core; endmodule\n",
  184. "tests/board_viewer/fixtures/keep-small.txt": b"allowlisted fixture\n",
  185. }