test_package_adversarial_compact.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. #!/usr/bin/env python3
  2. """Lane P6: adversarial packaging fixtures for review-compact fail-closed policy.
  3. Ownership: tests/unit/test_package_* and tests/fixtures/package_adversarial only.
  4. Does not weaken packager production policy. review-compact gated cases skip until
  5. P1 registers the profile; tip cases exercise current fail-closed APIs.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import shutil
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import unicodedata
  14. import unittest
  15. import zipfile
  16. from pathlib import Path
  17. UNIT_DIR = Path(__file__).resolve().parent
  18. if str(UNIT_DIR) not in sys.path:
  19. sys.path.insert(0, str(UNIT_DIR))
  20. from package_review_compact_contract import ( # noqa: E402
  21. DEFAULT_REVIEW_COMPACT_INCLUDE_FULL_HISTORY,
  22. DEFAULT_REVIEW_COMPACT_INCLUDE_GIT_BUNDLE,
  23. REVIEW_COMPACT_PROFILE,
  24. adversarial_fixture_relatives,
  25. adversarial_private_key_bytes,
  26. assert_no_full_git_bundle,
  27. handoff_profiles,
  28. intended_review_compact_exclusion_reason,
  29. load_analyzer,
  30. load_handoff,
  31. path_looks_like_full_git_bundle,
  32. require_review_compact,
  33. review_compact_available,
  34. )
  35. ROOT = Path(__file__).resolve().parents[2]
  36. FIXTURE_ROOT = ROOT / "tests" / "fixtures" / "package_adversarial"
  37. PAYLOAD_ROOT = FIXTURE_ROOT / "payloads"
  38. def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path:
  39. path = root / Path(relative)
  40. path.parent.mkdir(parents=True, exist_ok=True)
  41. path.write_bytes(data)
  42. return path
  43. def plant_adversarial_tree(root: Path) -> dict[str, bytes]:
  44. payloads = adversarial_fixture_relatives()
  45. for relative, data in payloads.items():
  46. write_file(root, relative, data)
  47. return payloads
  48. class ReviewCompactContractUnitTests(unittest.TestCase):
  49. """Always-on contract documentation (no packager profile required)."""
  50. maxDiff = None
  51. def test_contract_defaults_forbid_full_bundle_and_history(self) -> None:
  52. self.assertFalse(DEFAULT_REVIEW_COMPACT_INCLUDE_GIT_BUNDLE)
  53. self.assertFalse(DEFAULT_REVIEW_COMPACT_INCLUDE_FULL_HISTORY)
  54. self.assertEqual(REVIEW_COMPACT_PROFILE, "review-compact")
  55. def test_fixture_manifest_lists_attack_vectors(self) -> None:
  56. manifest_path = FIXTURE_ROOT / "manifest.json"
  57. self.assertTrue(manifest_path.is_file())
  58. payload = json.loads(manifest_path.read_text(encoding="utf-8"))
  59. self.assertEqual(payload["schema"], "prod2u-package-adversarial-fixtures-v1")
  60. ids = {item["id"] for item in payload["vectors"]}
  61. for required in {
  62. "pdf-schematic",
  63. "brd-board",
  64. "dsn-orcad",
  65. "vendor-installer",
  66. "license-archive",
  67. "private-key",
  68. "dotenv",
  69. "path-traversal-zip",
  70. }:
  71. self.assertIn(required, ids)
  72. for item in payload["vectors"]:
  73. path = FIXTURE_ROOT / item["path"]
  74. self.assertTrue(path.is_file(), f"missing fixture payload {path}")
  75. self.assertGreater(path.stat().st_size, 0, f"empty fixture payload {path}")
  76. def test_intended_policy_excludes_sneaky_reference_and_secrets(self) -> None:
  77. cases = {
  78. "reference/original/board/sneaky-main.brd": "compact_excludes_original_board",
  79. "reference/original/schematics/sneaky-schematic.pdf": "compact_excludes_original_schematics",
  80. "docs/sneak/leak.pdf": "compact_excludes_reference_design_blob",
  81. "src/rtl/leak.brd": "compact_excludes_reference_design_blob",
  82. "src/rtl/leak.dsn": "compact_excludes_reference_design_blob",
  83. "td_release_2026.1_fake.zip": "vendor_toolchain_archive",
  84. "oss-cad-suite-linux.tgz": "vendor_toolchain_archive",
  85. "anlogic_cd/installer/setup.exe": "vendor_installer_payload",
  86. "config/.env": "secret_environment_file",
  87. "secrets/id_ed25519": "private_key_file",
  88. "node_modules/left-pad/index.js": "node_modules_runtime",
  89. ".venv/bin/python": "virtual_environment",
  90. "td/build/current/design.bit": "td_build_output",
  91. "runs/old-matrix/receipt.json": "run_state_directory",
  92. "td_20260804_sneaky.log": "td_root_runtime_log",
  93. ".run_id": "local_run_id_marker",
  94. "evidence-batch-summary.txt": "old_run_or_batch_summary",
  95. "reference/original/local_archives/Anlogic.lic": "credential_or_license_file",
  96. }
  97. for relative, expected in cases.items():
  98. self.assertEqual(
  99. intended_review_compact_exclusion_reason(relative, is_dir=False),
  100. expected,
  101. relative,
  102. )
  103. # Ancestor prefix still covers non-license junk under local_archives.
  104. self.assertEqual(
  105. intended_review_compact_exclusion_reason(
  106. "reference/original/local_archives/vendor-blob.bin",
  107. is_dir=False,
  108. ),
  109. "compact_excludes_original_local_archives",
  110. )
  111. self.assertIsNone(
  112. intended_review_compact_exclusion_reason(
  113. "tests/board_viewer/fixtures/keep-small.txt",
  114. is_dir=False,
  115. )
  116. )
  117. self.assertIsNone(
  118. intended_review_compact_exclusion_reason("src/rtl/core.v", is_dir=False)
  119. )
  120. def test_bundle_path_detector(self) -> None:
  121. self.assertTrue(path_looks_like_full_git_bundle("git-history/workspace-current.bundle"))
  122. self.assertTrue(path_looks_like_full_git_bundle("CPLD/git-history/repo.bundle"))
  123. self.assertFalse(path_looks_like_full_git_bundle("meta/git-status.txt"))
  124. self.assertFalse(path_looks_like_full_git_bundle("source/src/rtl/core.v"))
  125. class TipFailClosedAdversarialTests(unittest.TestCase):
  126. """Exercise current packager APIs with sneaky trees (should pass on tip)."""
  127. maxDiff = None
  128. def test_analysis_scan_excludes_secrets_vendor_venv_td_and_src_board_files(self) -> None:
  129. analyzer = load_analyzer()
  130. handoff = load_handoff()
  131. with tempfile.TemporaryDirectory() as tmp:
  132. root = Path(tmp) / "src"
  133. plant_adversarial_tree(root)
  134. # Symlink escape planted separately (raises if not excluded first).
  135. candidates, excluded, _ = analyzer.scan_analysis_root(root)
  136. included = {item.relative for item in candidates}
  137. excluded_by_path = {item["path"]: item["rule"] for item in excluded}
  138. self.assertIn("src/rtl/core.v", included)
  139. self.assertIn("tests/board_viewer/fixtures/keep-small.txt", included)
  140. self.assertNotIn("config/.env", included)
  141. self.assertEqual(excluded_by_path.get("config/.env"), "secret_environment_file")
  142. self.assertNotIn("secrets/id_ed25519", included)
  143. self.assertEqual(excluded_by_path.get("secrets/id_ed25519"), "private_key_file")
  144. self.assertNotIn("node_modules", included)
  145. self.assertEqual(excluded_by_path.get("node_modules"), "node_modules_runtime")
  146. self.assertNotIn(".venv", included)
  147. self.assertEqual(excluded_by_path.get(".venv"), "virtual_environment")
  148. self.assertEqual(excluded_by_path.get("venv"), "virtual_environment")
  149. self.assertNotIn("td/build", included)
  150. self.assertEqual(excluded_by_path.get("td/build"), "td_build_output")
  151. self.assertNotIn("runs", included)
  152. self.assertEqual(excluded_by_path.get("runs"), "run_state_directory")
  153. self.assertNotIn("anlogic_cd", included)
  154. self.assertEqual(excluded_by_path.get("anlogic_cd"), "vendor_installer_payload")
  155. self.assertNotIn("td_release_2026.1_fake.zip", included)
  156. self.assertIn(
  157. excluded_by_path.get("td_release_2026.1_fake.zip"),
  158. {"vendor_toolchain_archive", "archive_file_not_source"},
  159. )
  160. self.assertNotIn("src/rtl/leak.brd", included)
  161. self.assertEqual(excluded_by_path.get("src/rtl/leak.brd"), "board_design_file")
  162. self.assertNotIn("src/rtl/leak.dsn", included)
  163. self.assertEqual(excluded_by_path.get("src/rtl/leak.dsn"), "board_design_file")
  164. self.assertNotIn(
  165. "reference/original/local_archives/Anlogic.lic",
  166. included,
  167. )
  168. self.assertEqual(
  169. excluded_by_path.get("reference/original/local_archives/Anlogic.lic"),
  170. "credential_or_license_file",
  171. )
  172. # Tip full profile still keeps reference originals; compact contract forbids them.
  173. self.assertIn("reference/original/board/sneaky-main.brd", included)
  174. self.assertEqual(
  175. intended_review_compact_exclusion_reason(
  176. "reference/original/board/sneaky-main.brd",
  177. is_dir=False,
  178. ),
  179. "compact_excludes_original_board",
  180. )
  181. self.assertIsNotNone(handoff.HANDOFF_PROFILES)
  182. def test_handoff_scan_excludes_old_td_logs_and_vendor_archives(self) -> None:
  183. handoff = load_handoff()
  184. with tempfile.TemporaryDirectory() as tmp:
  185. root = Path(tmp) / "src"
  186. write_file(root, "src/rtl/core.v", b"module core; endmodule\n")
  187. write_file(root, "td_20260804_sneaky.log", b"old td run log\n")
  188. write_file(root, "td_release_2026.1_fake.zip", b"PK\x03\x04ADV")
  189. write_file(root, "license-pack.zip", b"PK\x03\x04ADV-LIC")
  190. write_file(root, "vendor/tool.exe", b"MZADV")
  191. candidates, excluded, _ = handoff.scan_tree(root)
  192. included = {item.relative for item in candidates}
  193. excluded_by_path = {item["path"]: item["rule"] for item in excluded}
  194. self.assertIn("src/rtl/core.v", included)
  195. self.assertEqual(excluded_by_path["td_20260804_sneaky.log"], "td_root_runtime_log")
  196. self.assertEqual(
  197. excluded_by_path["td_release_2026.1_fake.zip"],
  198. "vendor_toolchain_archive",
  199. )
  200. self.assertEqual(excluded_by_path["license-pack.zip"], "license_archive")
  201. self.assertEqual(excluded_by_path["vendor/tool.exe"], "vendor_executable")
  202. def test_symlink_escape_refuses_packaging(self) -> None:
  203. handoff = load_handoff()
  204. with tempfile.TemporaryDirectory() as tmp:
  205. temp = Path(tmp)
  206. root = temp / "src"
  207. outside = temp / "outside"
  208. write_file(root, "src/rtl/core.v", b"module core; endmodule\n")
  209. write_file(outside, "secret.txt", b"must-never-follow\n")
  210. link = root / "docs" / "escape-link"
  211. link.parent.mkdir(parents=True, exist_ok=True)
  212. link.symlink_to(outside, target_is_directory=True)
  213. with self.assertRaisesRegex(handoff.PackagingError, "undeclared reparse point"):
  214. handoff.scan_tree(root)
  215. def test_archive_path_traversal_members_fail_closed(self) -> None:
  216. handoff = load_handoff()
  217. with tempfile.TemporaryDirectory() as tmp:
  218. source = Path(tmp) / "source"
  219. archive = write_file(
  220. source,
  221. "docs/traversal-member.zip",
  222. (PAYLOAD_ROOT / "traversal-member.zip").read_bytes(),
  223. )
  224. # Tip analysis excludes bare .zip; plant under a path that handoff scan keeps
  225. # so archive member traversal is exercised via scan_candidate_archive.
  226. candidates, _, _ = handoff.scan_tree(source)
  227. # If .zip is excluded by a future rule, fall back to direct Candidate.
  228. match = next((item for item in candidates if item.absolute == archive), None)
  229. if match is None:
  230. st = archive.stat()
  231. match = handoff.Candidate(
  232. archive,
  233. "docs/traversal-member.zip",
  234. st.st_size,
  235. st.st_mtime_ns,
  236. int(st.st_dev),
  237. int(st.st_ino),
  238. int(st.st_mode),
  239. )
  240. with self.assertRaisesRegex(handoff.PackagingError, "unsafe archive member"):
  241. handoff.scan_candidate_archive(match)
  242. def test_unicode_nfc_nfd_collision_fails_closed(self) -> None:
  243. handoff = load_handoff()
  244. with tempfile.TemporaryDirectory() as tmp:
  245. root = Path(tmp) / "src"
  246. write_file(root, "src/rtl/core.v", b"module core; endmodule\n")
  247. # Same Windows collision key via NFC vs NFD "é"
  248. nfc_name = "caf" + unicodedata.normalize("NFC", "é") + ".txt"
  249. nfd_name = "caf" + unicodedata.normalize("NFD", "é") + ".txt"
  250. self.assertNotEqual(nfc_name, nfd_name)
  251. self.assertEqual(
  252. handoff.windows_collision_key(f"docs/{nfc_name}"),
  253. handoff.windows_collision_key(f"docs/{nfd_name}"),
  254. )
  255. write_file(root, f"docs/{nfc_name}", b"nfc\n")
  256. write_file(root, f"docs/{nfd_name}", b"nfd\n")
  257. with self.assertRaisesRegex(handoff.PackagingError, "Windows ZIP path collision"):
  258. handoff.scan_tree(root)
  259. def test_private_key_pem_content_fails_closed(self) -> None:
  260. handoff = load_handoff()
  261. marker = adversarial_private_key_bytes()
  262. with self.assertRaises(handoff.PackagingError):
  263. handoff.scan_secret_markers(marker, b"", "docs/leaked.pem")
  264. def test_duplicate_identical_evidence_is_physically_deduped(self) -> None:
  265. analyzer = load_analyzer()
  266. handoff = load_handoff()
  267. with tempfile.TemporaryDirectory() as tmp:
  268. temp = Path(tmp)
  269. # Content dedup threshold is 4096 bytes (or .pdf/.brd names).
  270. payload = (b'{"id":"dup","pad":"' + (b"A" * 4200) + b'"}\n')
  271. a = write_file(temp / "source", "receipts/dup-a.json", payload)
  272. b = write_file(temp / "source", "receipts/dup-b.json", payload)
  273. items = (
  274. analyzer.make_package_item(
  275. a,
  276. relative="workspace-current/receipts/dup-a.json",
  277. category="core",
  278. source_id="workspace-current",
  279. ),
  280. analyzer.make_package_item(
  281. b,
  282. relative="workspace-current/receipts/dup-b.json",
  283. category="core",
  284. source_id="workspace-current",
  285. ),
  286. )
  287. inventory = [
  288. {
  289. "path": item.candidate.relative,
  290. "sha256": handoff.sha256_file(item.candidate.absolute),
  291. "size": item.candidate.size,
  292. }
  293. for item in items
  294. ]
  295. kept, dedup_records, excluded = analyzer.apply_content_dedup(items, inventory)
  296. kept_paths = {item.candidate.relative for item in kept}
  297. self.assertEqual(len(kept_paths), 1)
  298. self.assertEqual(len(dedup_records), 1)
  299. self.assertEqual(
  300. dedup_records[0]["reason"],
  301. "identical_content_single_physical_copy",
  302. )
  303. self.assertTrue(
  304. any(item["rule"] == "duplicate_content_logical_alias" for item in excluded)
  305. )
  306. def test_git_ref_path_traversal_not_followed(self) -> None:
  307. handoff = load_handoff()
  308. with tempfile.TemporaryDirectory() as tmp:
  309. temp = Path(tmp)
  310. git_dir = temp / "source" / ".git"
  311. write_file(git_dir, "HEAD", b"ref: ../../outside-ref\n")
  312. write_file(temp, "outside-ref", b"0123456789abcdef0123456789abcdef01234567\n")
  313. self.assertEqual(handoff.read_head_metadata(git_dir), (None, None))
  314. def test_nested_archive_secret_fails_closed_on_audit(self) -> None:
  315. handoff = load_handoff()
  316. marker = adversarial_private_key_bytes()
  317. with tempfile.TemporaryDirectory() as tmp:
  318. source = Path(tmp) / "source"
  319. buf_path = source / "docs" / "nested-secret.bin"
  320. buf_path.parent.mkdir(parents=True, exist_ok=True)
  321. with zipfile.ZipFile(buf_path, "w") as zf:
  322. zf.writestr("payload/secret.pem", marker)
  323. st = buf_path.stat()
  324. candidate = handoff.Candidate(
  325. buf_path,
  326. "docs/nested-secret.bin",
  327. st.st_size,
  328. st.st_mtime_ns,
  329. int(st.st_dev),
  330. int(st.st_ino),
  331. int(st.st_mode),
  332. )
  333. with self.assertRaisesRegex(handoff.PackagingError, "secret|PRIVATE KEY|credential"):
  334. handoff.scan_candidate_archive(candidate)
  335. class ReviewCompactProfileAdversarialTests(unittest.TestCase):
  336. """Gated on P1 registering review-compact; skip with explicit reason otherwise."""
  337. maxDiff = None
  338. def test_profile_enum_documents_availability(self) -> None:
  339. profiles = handoff_profiles()
  340. self.assertIn("full", profiles)
  341. self.assertIn("code-only", profiles)
  342. if not review_compact_available():
  343. self.skipTest(
  344. "review-compact profile not in HANDOFF_PROFILES yet (pending P1 packager core)"
  345. )
  346. self.assertIn(REVIEW_COMPACT_PROFILE, profiles)
  347. def test_review_compact_excludes_reference_pdf_brd_dsn_and_vendor(self) -> None:
  348. require_review_compact(self)
  349. analyzer = load_analyzer()
  350. with tempfile.TemporaryDirectory() as tmp:
  351. root = Path(tmp) / "src"
  352. plant_adversarial_tree(root)
  353. candidates, excluded, _ = analyzer.scan_analysis_root(
  354. root,
  355. profile=REVIEW_COMPACT_PROFILE,
  356. )
  357. included = {item.relative for item in candidates}
  358. excluded_by_path = {item["path"]: item["rule"] for item in excluded}
  359. self.assertIn("src/rtl/core.v", included)
  360. self.assertIn("tests/board_viewer/fixtures/keep-small.txt", included)
  361. forbidden = [
  362. "reference/original/board/sneaky-main.brd",
  363. "reference/original/schematics/sneaky-schematic.pdf",
  364. "reference/original/diagrams/sneaky-diagram.pdf",
  365. "reference/original/board/sneaky.dsn",
  366. "reference/original/local_archives/vendor-license.zip",
  367. "docs/sneak/leak.pdf",
  368. "src/rtl/leak.brd",
  369. "src/rtl/leak.dsn",
  370. "td_release_2026.1_fake.zip",
  371. "oss-cad-suite-linux.tgz",
  372. "anlogic_cd/installer/setup.exe",
  373. "config/.env",
  374. "secrets/id_ed25519",
  375. "node_modules/left-pad/index.js",
  376. ".venv/bin/python",
  377. "td/build/current/design.bit",
  378. "runs/old-matrix/receipt.json",
  379. "td_20260804_sneaky.log",
  380. "evidence-batch-summary.txt",
  381. ".run_id",
  382. ]
  383. for relative in forbidden:
  384. self.assertNotIn(relative, included, relative)
  385. # Either direct exclusion or ancestor exclusion is acceptable.
  386. reason = excluded_by_path.get(relative) or next(
  387. (
  388. rule
  389. for path, rule in excluded_by_path.items()
  390. if relative == path or relative.startswith(path.rstrip("/") + "/")
  391. ),
  392. None,
  393. )
  394. self.assertIsNotNone(reason, f"expected exclusion for {relative}; excluded={excluded_by_path}")
  395. intended = intended_review_compact_exclusion_reason(relative, is_dir=False)
  396. self.assertIsNotNone(intended, relative)
  397. def test_review_compact_default_omits_full_git_bundle(self) -> None:
  398. require_review_compact(self)
  399. analyzer = load_analyzer()
  400. git = shutil.which("git")
  401. if not git:
  402. self.skipTest("Git is required")
  403. with tempfile.TemporaryDirectory() as tmp:
  404. temp = Path(tmp)
  405. repo = temp / "repo"
  406. repo.mkdir()
  407. subprocess.run([git, "init", "-q", str(repo)], check=True)
  408. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  409. subprocess.run(
  410. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  411. check=True,
  412. )
  413. # Plant a reference blob that must never ride along via full history bundle.
  414. write_file(repo, "reference/original/board/hidden.brd", b"%HIDDEN-BRD%\n")
  415. write_file(repo, "src/rtl/core.v", b"module core; endmodule\n")
  416. subprocess.run([git, "-C", str(repo), "add", "."], check=True)
  417. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  418. config = analyzer.HandoffConfig(
  419. max_zip_bytes=2_000_000,
  420. target_zip_bytes=1_500_000,
  421. external_sources=(),
  422. extra_exclusions=(),
  423. )
  424. # Default compact must not require / include a full git bundle.
  425. kwargs = {
  426. "repo_root": repo,
  427. "config": config,
  428. "temp_root": temp / "run",
  429. "profile": REVIEW_COMPACT_PROFILE,
  430. }
  431. # Prefer packager default (include_git_bundle omitted). If API still
  432. # defaults True until P1 wires profile defaults, pass explicit False
  433. # only when the signature still requires the flag for non-full profiles.
  434. try:
  435. collection = analyzer.collect_analysis_inputs(**kwargs)
  436. except TypeError:
  437. collection = analyzer.collect_analysis_inputs(
  438. **kwargs,
  439. include_git_bundle=DEFAULT_REVIEW_COMPACT_INCLUDE_GIT_BUNDLE,
  440. )
  441. except analyzer.PackagingError as exc:
  442. # full-profile-style hard requirement must not apply to compact.
  443. self.assertNotIn("git bundle", str(exc).lower())
  444. raise
  445. member_paths = [item.candidate.relative for item in collection.items]
  446. assert_no_full_git_bundle(member_paths, testcase=self)
  447. # Also ensure hidden BRD is not present as a packaged path.
  448. self.assertFalse(
  449. any(path.casefold().endswith(".brd") for path in member_paths),
  450. member_paths,
  451. )
  452. def test_review_compact_package_members_have_no_bundle_or_reference_blobs(self) -> None:
  453. require_review_compact(self)
  454. analyzer = load_analyzer()
  455. git = shutil.which("git")
  456. if not git:
  457. self.skipTest("Git is required")
  458. with tempfile.TemporaryDirectory() as tmp:
  459. temp = Path(tmp)
  460. repo = temp / "repo"
  461. repo.mkdir()
  462. subprocess.run([git, "init", "-q", str(repo)], check=True)
  463. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  464. subprocess.run(
  465. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  466. check=True,
  467. )
  468. plant_adversarial_tree(repo)
  469. subprocess.run([git, "-C", str(repo), "add", "-A"], check=True)
  470. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "adversarial"], check=True)
  471. config = analyzer.HandoffConfig(
  472. max_zip_bytes=5_000_000,
  473. target_zip_bytes=4_000_000,
  474. external_sources=(),
  475. extra_exclusions=(),
  476. )
  477. try:
  478. collection = analyzer.collect_analysis_inputs(
  479. repo_root=repo,
  480. config=config,
  481. temp_root=temp / "run",
  482. profile=REVIEW_COMPACT_PROFILE,
  483. include_git_bundle=False,
  484. )
  485. except TypeError:
  486. collection = analyzer.collect_analysis_inputs(
  487. repo_root=repo,
  488. config=config,
  489. temp_root=temp / "run",
  490. profile=REVIEW_COMPACT_PROFILE,
  491. )
  492. result = analyzer.create_analysis_package(
  493. collection=collection,
  494. output_root=temp / "output",
  495. package_name="adv-compact",
  496. max_zip_bytes=5_000_000,
  497. target_zip_bytes=4_000_000,
  498. force=False,
  499. profile=REVIEW_COMPACT_PROFILE,
  500. )
  501. package_dir = Path(result["output_dir"])
  502. volume = package_dir / result["volumes"][0]["file"]
  503. with zipfile.ZipFile(volume) as archive:
  504. names = archive.namelist()
  505. assert_no_full_git_bundle(names, testcase=self)
  506. lowered = [name.casefold() for name in names]
  507. for needle in (".pdf", ".brd", ".dsn", "anlogic.lic", "/.env", "id_ed25519"):
  508. offenders = [name for name in lowered if needle in name]
  509. self.assertEqual(offenders, [], f"leaked {needle}: {offenders}")
  510. class DiskFixturePayloadTests(unittest.TestCase):
  511. def test_payload_private_key_and_traversal_bytes(self) -> None:
  512. key = (PAYLOAD_ROOT / "id_ed25519").read_bytes()
  513. self.assertIn(b"PRIVATE KEY", key)
  514. with zipfile.ZipFile(PAYLOAD_ROOT / "traversal-member.zip") as archive:
  515. members = archive.namelist()
  516. self.assertTrue(any(".." in name or name.startswith("../") for name in members))
  517. if __name__ == "__main__":
  518. unittest.main()