package_agent_handoff.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816
  1. #!/usr/bin/env python3
  2. """Create a comprehensive, sanitized CPLD workspace handoff archive."""
  3. from __future__ import annotations
  4. import argparse
  5. import gzip
  6. import hashlib
  7. import importlib.util
  8. import io
  9. import json
  10. import os
  11. import re
  12. import shutil
  13. import stat
  14. import subprocess
  15. import sys
  16. import tarfile
  17. import tempfile
  18. import tomllib
  19. import unicodedata
  20. import uuid
  21. import zipfile
  22. from collections import Counter
  23. from contextlib import contextmanager
  24. from dataclasses import dataclass
  25. from datetime import datetime, timezone
  26. from pathlib import Path
  27. from typing import BinaryIO, Callable, Iterable, Iterator, cast
  28. ROOT = Path(__file__).resolve().parents[1]
  29. ARCHIVE_ROOT = "CPLD"
  30. METADATA_ROOT = f"{ARCHIVE_ROOT}/HANDOFF-METADATA"
  31. SECRET_SCAN_OVERLAP = 512
  32. MAX_ARCHIVE_DEPTH = 3
  33. MAX_ARCHIVE_MEMBERS = 100_000
  34. MAX_ARCHIVE_UNCOMPRESSED_BYTES = 8 * 1024 * 1024 * 1024
  35. SECRET_PATTERNS = (
  36. (
  37. "private key",
  38. re.compile(
  39. rb"-----BEGIN "
  40. + rb"(?:ENCRYPTED |RSA |DSA |EC |OPENSSH )?"
  41. + rb"PRIVATE KEY-----"
  42. + rb"|-----BEGIN PGP "
  43. + rb"PRIVATE KEY BLOCK-----"
  44. ),
  45. ),
  46. (
  47. "GitHub token",
  48. re.compile(
  49. rb"(?<![A-Za-z0-9_])(?:gh[pousr]_[A-Za-z0-9]{36,255}"
  50. rb"|github_pat_[A-Za-z0-9_]{60,255})(?![A-Za-z0-9_])"
  51. ),
  52. ),
  53. (
  54. "AWS secret access key",
  55. re.compile(
  56. rb"(?<![A-Za-z0-9_])aws_"
  57. + rb"(?:secret_access_key|secret_key)[\"']?\s*[:=]\s*[\"']?"
  58. + rb"[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])",
  59. re.IGNORECASE,
  60. ),
  61. ),
  62. (
  63. "AWS session token",
  64. re.compile(
  65. rb"(?<![A-Za-z0-9_])aws_"
  66. + rb"(?:session_token|security_token)[\"']?\s*[:=]\s*[\"']?"
  67. + rb"[A-Za-z0-9/+=]{32,2048}(?![A-Za-z0-9/+=])",
  68. re.IGNORECASE,
  69. ),
  70. ),
  71. (
  72. "OpenAI API key",
  73. re.compile(
  74. rb"(?<![A-Za-z0-9_-])sk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,255}"
  75. rb"(?![A-Za-z0-9_-])"
  76. ),
  77. ),
  78. (
  79. "Slack token",
  80. re.compile(rb"(?<![A-Za-z0-9-])xox[baprs]-[A-Za-z0-9-]{20,255}(?![A-Za-z0-9-])"),
  81. ),
  82. )
  83. SAFE_PACKAGE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$")
  84. TD_BUILD_EVIDENCE_SUFFIXES = {".qor", ".area", ".timing", ".rpt", ".log", ".logw"}
  85. WINDOWS_RESERVED_NAMES = {
  86. "con",
  87. "prn",
  88. "aux",
  89. "nul",
  90. *(f"com{index}" for index in range(1, 10)),
  91. *(f"lpt{index}" for index in range(1, 10)),
  92. }
  93. WINDOWS_INVALID_FILENAME_CHARS = frozenset('<>:"/\\|?*')
  94. class PackagingError(RuntimeError):
  95. """Raised when a handoff archive cannot be produced safely."""
  96. @dataclass(frozen=True)
  97. class Candidate:
  98. absolute: Path
  99. relative: str
  100. size: int
  101. mtime_ns: int
  102. device: int
  103. inode: int
  104. mode: int
  105. @dataclass
  106. class CandidateSnapshot:
  107. stream: BinaryIO
  108. inventory: dict[str, object]
  109. @dataclass
  110. class ArchiveScanBudget:
  111. member_count: int = 0
  112. uncompressed_bytes: int = 0
  113. @dataclass(frozen=True)
  114. class ScanContext:
  115. changxin_version: str | None
  116. def utc_now() -> str:
  117. return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
  118. def find_7z() -> Path | None:
  119. discovered = shutil.which("7z") or shutil.which("7zz")
  120. candidates = [
  121. Path(discovered) if discovered else None,
  122. Path(r"C:\Program Files\7-Zip\7z.exe"),
  123. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  124. ]
  125. for candidate in candidates:
  126. if candidate is not None and candidate.is_file():
  127. return candidate.resolve(strict=True)
  128. return None
  129. def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
  130. del staging_root
  131. return [
  132. "a",
  133. "-tzip",
  134. "-mm=Deflate",
  135. "-mx=9",
  136. "-mmt",
  137. "-y",
  138. "-r",
  139. str(archive_path),
  140. "CPLD\\*",
  141. ]
  142. def run_7zip(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  143. try:
  144. completed = subprocess.run(
  145. [str(seven_zip), *arguments],
  146. cwd=cwd,
  147. stdout=subprocess.PIPE,
  148. stderr=subprocess.STDOUT,
  149. text=True,
  150. encoding="utf-8",
  151. errors="replace",
  152. timeout=300,
  153. check=False,
  154. )
  155. except (OSError, subprocess.TimeoutExpired) as exc:
  156. raise PackagingError("unable to run 7-Zip") from exc
  157. if completed.returncode != 0:
  158. detail = completed.stdout.strip().splitlines()
  159. suffix = f": {detail[-1]}" if detail else ""
  160. raise PackagingError(f"7-Zip failed{suffix}")
  161. return completed.stdout
  162. def rename_archive_entries(
  163. seven_zip: Path,
  164. archive_path: Path,
  165. renames: list[tuple[str, str]],
  166. ) -> None:
  167. for offset in range(0, len(renames), 64):
  168. batch = renames[offset : offset + 64]
  169. arguments = ["rn", "-y", str(archive_path)]
  170. for old_name, new_name in batch:
  171. arguments.extend((old_name, new_name))
  172. run_7zip(seven_zip, arguments, cwd=archive_path.parent)
  173. def validate_windows_component(component: str, relative: str) -> str:
  174. if component.endswith((" ", ".")):
  175. raise PackagingError(f"path component has a Windows-unsafe trailing character: {relative}")
  176. if any(ord(character) < 32 or character in WINDOWS_INVALID_FILENAME_CHARS for character in component):
  177. raise PackagingError(f"path component contains a Windows-invalid character: {relative}")
  178. normalized = component.casefold()
  179. if normalized.split(".", 1)[0] in WINDOWS_RESERVED_NAMES:
  180. raise PackagingError(f"Windows reserved device name is not portable: {relative}")
  181. return normalized
  182. def normalize_relative(parts: Iterable[str]) -> str:
  183. try:
  184. relative = unicodedata.normalize("NFC", "/".join(parts))
  185. relative.encode("utf-8", errors="strict")
  186. except UnicodeError as exc:
  187. raise PackagingError("path is not valid UTF-8") from exc
  188. components = relative.split("/")
  189. if not relative or relative.startswith("/") or any(part in {"", ".", ".."} for part in components):
  190. raise PackagingError(f"unsafe relative path: {relative!r}")
  191. for component in components:
  192. validate_windows_component(component, relative)
  193. return relative
  194. def windows_collision_key(relative: str) -> str:
  195. components = []
  196. for component in unicodedata.normalize("NFC", relative).split("/"):
  197. if not component:
  198. raise PackagingError(f"path component is empty after Windows normalization: {relative}")
  199. normalized = validate_windows_component(component, relative)
  200. components.append(normalized)
  201. return "/".join(components)
  202. def is_under(relative: str, prefix: str) -> bool:
  203. return relative == prefix or relative.startswith(prefix + "/")
  204. def load_scan_context(root: Path) -> ScanContext:
  205. pyproject = root / "tools" / "changxin-temp-uart" / "pyproject.toml"
  206. version: str | None = None
  207. try:
  208. raw_payload = read_stable_regular_bytes(
  209. pyproject,
  210. "Changxin pyproject",
  211. max_bytes=1024 * 1024,
  212. )
  213. payload = tomllib.loads(raw_payload.decode("utf-8-sig", errors="strict"))
  214. value = payload.get("project", {}).get("version")
  215. if isinstance(value, str) and value.strip():
  216. version = value.strip()
  217. except (PackagingError, UnicodeError, tomllib.TOMLDecodeError):
  218. version = None
  219. return ScanContext(version)
  220. def secret_path_reason(relative: str, *, is_dir: bool) -> str | None:
  221. if is_dir:
  222. return None
  223. name = relative.rsplit("/", 1)[-1].casefold()
  224. parts = relative.casefold().split("/")
  225. suffix = Path(name).suffix.casefold()
  226. if name == ".env" or (
  227. name.startswith(".env.")
  228. and not name.endswith((".example", ".sample", ".template", ".dist"))
  229. ):
  230. return "secret_environment_file"
  231. if name in {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"} or name.startswith("id_rsa."):
  232. return "private_key_file"
  233. if name in {".netrc", "_netrc", ".pypirc", ".npmrc", ".git-credentials"}:
  234. return "credential_configuration_file"
  235. if len(parts) >= 2 and parts[-2:] == [".aws", "credentials"]:
  236. return "cloud_credential_file"
  237. if len(parts) >= 2 and parts[-2:] == [".docker", "config.json"]:
  238. return "container_registry_credential_file"
  239. if len(parts) >= 2 and parts[-2:] == ["gcloud", "application_default_credentials.json"]:
  240. return "cloud_credential_file"
  241. if suffix in {".key", ".pfx", ".p12", ".lic"}:
  242. return "credential_or_license_file"
  243. return None
  244. def common_file_exclusion_reason(relative: str) -> str | None:
  245. lower = relative.casefold()
  246. name = lower.rsplit("/", 1)[-1]
  247. suffix = Path(name).suffix.casefold()
  248. if suffix in {".pyc", ".pyo"}:
  249. return "python_bytecode"
  250. if suffix in {".tmp", ".partial", ".part", ".swp", ".swo"} or name.endswith("~"):
  251. return "atomic_or_editor_temporary_file"
  252. if suffix == ".dmp" or name.startswith("minidump-"):
  253. return "crash_dump"
  254. if name == "a.out" or (name.startswith("tmp_last_pkg") and name.endswith(".txt")):
  255. return "temporary_build_artifact"
  256. if name in {".ds_store", "thumbs.db", "desktop.ini"}:
  257. return "os_metadata_cache"
  258. if name in {".coverage", "coverage.xml"}:
  259. return "coverage_cache"
  260. if name.startswith(".coverage."):
  261. return "coverage_cache"
  262. if lower.startswith("td/td_") and suffix in {".log", ".logw"}:
  263. return "td_root_runtime_log"
  264. if "/" not in lower and lower.startswith("td_") and suffix in {".log", ".logw"}:
  265. return "td_root_runtime_log"
  266. generated_binary_suffixes = {
  267. ".bit",
  268. ".bid",
  269. ".data",
  270. ".db",
  271. ".timing",
  272. ".rpt",
  273. ".area",
  274. ".qor",
  275. ".vvp",
  276. }
  277. if suffix in generated_binary_suffixes:
  278. return "generated_binary_artifact"
  279. if suffix == ".exe":
  280. return "vendor_executable"
  281. return None
  282. def exclusion_reason(relative: str, *, is_dir: bool, context: ScanContext) -> str | None:
  283. lower = relative.casefold()
  284. parts = lower.split("/")
  285. raw_parts = relative.split("/")
  286. name = parts[-1]
  287. if parts[0] == "handoff-metadata":
  288. raise PackagingError(f"source uses reserved package path: {relative}")
  289. secret_reason = secret_path_reason(relative, is_dir=is_dir)
  290. if secret_reason:
  291. return secret_reason
  292. explicit_roots = {
  293. ".git": "raw_git_metadata",
  294. ".codegraph": "external_codegraph_cache",
  295. ".omo": "agent_session_runtime",
  296. ".hypothesis": "hypothesis_cache",
  297. ".pytest_cache": "pytest_cache",
  298. "workspace": "deprecated_workspace",
  299. "_archive": "deprecated_archive",
  300. "unused": "unused_workspace_area",
  301. "log": "runtime_log_directory",
  302. "dist": "generated_handoff_output",
  303. "anlogic_cd": "vendor_installer_payload",
  304. "receipts/local": "local_runtime_receipt",
  305. "j6-binary921-deliverables": "generated_delivery_package",
  306. "j6tmp-v2-tailfix-package": "generated_delivery_package",
  307. "cpld-deliverables": "generated_delivery_package",
  308. "runs": "run_state_directory",
  309. }
  310. for prefix, reason in explicit_roots.items():
  311. if is_under(lower, prefix):
  312. return reason
  313. if lower in {"td/project/.lock.f", "td/project/.recent_user_depot.ini"}:
  314. return "td_gui_runtime_state"
  315. if is_under(lower, "td/project/log"):
  316. return "td_gui_runtime_log"
  317. if is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
  318. return "td_gui_runtime_run"
  319. if any(component.endswith("_Runs") for component in raw_parts):
  320. return "generated_run_directory"
  321. if lower == "tests/cocotb/results.xml":
  322. return "cocotb_transient_result"
  323. if not is_dir:
  324. common_reason = common_file_exclusion_reason(relative)
  325. if common_reason:
  326. return common_reason
  327. cache_components = {
  328. ".git": "raw_git_metadata",
  329. ".codegraph": "external_codegraph_cache",
  330. ".codex": "codex_local_runtime",
  331. "__pycache__": "python_bytecode_cache",
  332. ".pytest_cache": "pytest_cache",
  333. ".hypothesis": "hypothesis_cache",
  334. ".mypy_cache": "mypy_cache",
  335. ".ruff_cache": "ruff_cache",
  336. ".tox": "tox_environment",
  337. ".nox": "nox_environment",
  338. ".venv": "virtual_environment",
  339. "venv": "virtual_environment",
  340. "htmlcov": "coverage_report",
  341. "sim_build": "simulation_build",
  342. "obj_dir": "verilator_build",
  343. "node_modules": "node_modules_runtime",
  344. ".playwright-browsers": "browser_runtime_cache",
  345. "build": "build_output",
  346. "runs": "run_state_directory",
  347. }
  348. for component in parts:
  349. if component in cache_components:
  350. return cache_components[component]
  351. if component.endswith(".egg-info"):
  352. return "python_package_metadata"
  353. if component == "dist":
  354. return "generated_delivery_output"
  355. if component == ".logs":
  356. return "td_generated_run_directory"
  357. if is_under(lower, ".codex"):
  358. return "codex_local_runtime"
  359. if is_under(lower, "tools/changxin-temp-uart/build"):
  360. return "python_package_build_copy"
  361. if is_under(lower, "tools/changxin-temp-uart/pyinstaller-build"):
  362. return "pyinstaller_build_cache"
  363. if is_under(lower, "tools/changxin-temp-uart/pyinstaller-spec"):
  364. return "pyinstaller_spec_cache"
  365. if lower in {
  366. "tools/changxin-temp-uart/pyinstaller-entry.py",
  367. "tools/changxin-temp-uart/linux-onefile-build.json",
  368. "tools/changxin-temp-uart/changxin-temp-uart-static",
  369. }:
  370. return "pyinstaller_generated_output"
  371. if lower == "tools/changxin-temp-uart/dist":
  372. return None
  373. if is_under(lower, "tools/changxin-temp-uart/dist"):
  374. return None
  375. if is_under(lower, "td/build"):
  376. return "td_build_output"
  377. if lower == "tmp":
  378. return None
  379. if is_under(lower, "tmp"):
  380. transient_tmp_roots = {
  381. "tmp/rtl_sim": "compiled_rtl_simulation",
  382. "tmp/cocotb": "cocotb_runtime",
  383. "tmp/detector_selftest": "detector_selftest_runtime",
  384. "tmp/toolchain_probe": "toolchain_probe_runtime",
  385. "tmp/edge-headless-profile": "browser_runtime_profile",
  386. "tmp/td": "td_runtime_snapshot",
  387. "tmp/refactor": "compiled_refactor_probe",
  388. }
  389. for prefix, reason in transient_tmp_roots.items():
  390. if is_under(lower, prefix):
  391. return reason
  392. for evidence_prefix in (
  393. "tmp/resource_audit",
  394. "tmp/pwm_executor_probe",
  395. ):
  396. if is_under(lower, evidence_prefix):
  397. evidence_parts = parts[len(evidence_prefix.split("/")) :]
  398. if "td_user_env" in evidence_parts:
  399. return "td_staged_source_or_runtime_copy"
  400. return None
  401. if len(parts) == 2 and parts[1].startswith("pytest-"):
  402. return "temporary_test_runtime"
  403. return None
  404. return None
  405. def stat_is_reparse_point(file_stat: os.stat_result) -> bool:
  406. attributes = int(getattr(file_stat, "st_file_attributes", 0))
  407. reparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
  408. return stat.S_ISLNK(file_stat.st_mode) or bool(reparse_flag and attributes & reparse_flag)
  409. def is_reparse_point(entry: os.DirEntry[str], file_stat: os.stat_result) -> bool:
  410. return entry.is_symlink() or stat_is_reparse_point(file_stat)
  411. def invalid_receipt_reason(path: Path, relative: str, size: int) -> str | None:
  412. if not relative.casefold().startswith("receipts/") or not relative.casefold().endswith(".json"):
  413. return None
  414. if size == 0:
  415. return "empty_receipt"
  416. if size <= 32:
  417. try:
  418. if path.read_bytes().strip().lower() == b"null":
  419. return "null_receipt"
  420. except OSError as exc:
  421. raise PackagingError(f"unable to inspect receipt {relative}: {exc}") from exc
  422. return None
  423. def scan_tree(
  424. root: Path,
  425. *,
  426. exclusion_resolver: Callable[..., str | None] | None = None,
  427. ) -> tuple[list[Candidate], list[dict[str, str]], ScanContext]:
  428. context = load_scan_context(root)
  429. resolve_exclusion = exclusion_resolver or exclusion_reason
  430. included: list[Candidate] = []
  431. excluded: list[dict[str, str]] = []
  432. collision_paths: dict[str, str] = {}
  433. def record_exclusion(relative: str, reason: str) -> None:
  434. excluded.append({"path": relative, "rule": reason})
  435. def walk(directory: Path, relative_parts: tuple[str, ...]) -> None:
  436. try:
  437. with os.scandir(directory) as iterator:
  438. entries = sorted(
  439. list(iterator),
  440. key=lambda item: unicodedata.normalize("NFC", item.name).casefold(),
  441. )
  442. except OSError as exc:
  443. relative = "/".join(relative_parts) or "."
  444. raise PackagingError(f"unable to enumerate {relative}: {exc}") from exc
  445. for entry in entries:
  446. relative = normalize_relative((*relative_parts, entry.name))
  447. scan_secret_markers(relative.encode("utf-8"), b"", "[source path]")
  448. try:
  449. file_stat = os.lstat(entry.path)
  450. except OSError as exc:
  451. raise PackagingError(f"unable to inspect {relative}: {exc}") from exc
  452. is_directory = stat.S_ISDIR(file_stat.st_mode)
  453. reason = resolve_exclusion(relative, is_dir=is_directory, context=context)
  454. if is_reparse_point(entry, file_stat):
  455. if reason:
  456. record_exclusion(relative, reason)
  457. continue
  458. raise PackagingError(f"undeclared reparse point refuses packaging: {relative}")
  459. if reason:
  460. record_exclusion(relative, reason)
  461. continue
  462. if is_directory:
  463. walk(Path(entry.path), (*relative_parts, entry.name))
  464. continue
  465. if not stat.S_ISREG(file_stat.st_mode):
  466. raise PackagingError(f"unsupported non-regular file: {relative}")
  467. receipt_reason = invalid_receipt_reason(Path(entry.path), relative, file_stat.st_size)
  468. if receipt_reason:
  469. record_exclusion(relative, receipt_reason)
  470. continue
  471. key = windows_collision_key(relative)
  472. previous = collision_paths.get(key)
  473. if previous is not None:
  474. raise PackagingError(f"Windows ZIP path collision: {previous} and {relative}")
  475. collision_paths[key] = relative
  476. if int(file_stat.st_dev) == 0 or int(file_stat.st_ino) == 0:
  477. raise PackagingError(f"filesystem does not expose a stable file identity: {relative}")
  478. included.append(
  479. Candidate(
  480. Path(entry.path),
  481. relative,
  482. file_stat.st_size,
  483. file_stat.st_mtime_ns,
  484. int(file_stat.st_dev),
  485. int(file_stat.st_ino),
  486. int(file_stat.st_mode),
  487. )
  488. )
  489. walk(root, ())
  490. included.sort(key=lambda item: windows_collision_key(item.relative))
  491. excluded.sort(key=lambda item: (windows_collision_key(item["path"]), item["rule"]))
  492. return included, excluded, context
  493. def sha256_file(path: Path) -> str:
  494. digest = hashlib.sha256()
  495. with path.open("rb") as handle:
  496. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  497. digest.update(chunk)
  498. return digest.hexdigest()
  499. def scan_secret_markers(chunk: bytes, tail: bytes, relative: str) -> bytes:
  500. combined = tail + chunk
  501. for label, pattern in SECRET_PATTERNS:
  502. if pattern.search(combined):
  503. raise PackagingError(f"high-confidence {label} secret found in {relative}")
  504. return combined[-SECRET_SCAN_OVERLAP:]
  505. def candidate_stat_matches(file_stat: os.stat_result, candidate: Candidate) -> bool:
  506. return (
  507. stat.S_ISREG(file_stat.st_mode)
  508. and not stat_is_reparse_point(file_stat)
  509. and int(file_stat.st_dev) == candidate.device
  510. and int(file_stat.st_ino) == candidate.inode
  511. and (os.name == "nt" or int(file_stat.st_mode) == candidate.mode)
  512. and file_stat.st_size == candidate.size
  513. and file_stat.st_mtime_ns == candidate.mtime_ns
  514. )
  515. @contextmanager
  516. def open_candidate(candidate: Candidate) -> Iterator[BinaryIO]:
  517. try:
  518. before = os.lstat(candidate.absolute)
  519. except OSError as exc:
  520. raise PackagingError(f"unable to inspect {candidate.relative} before packaging: {exc}") from exc
  521. if not candidate_stat_matches(before, candidate):
  522. raise PackagingError(f"source changed after enumeration: {candidate.relative}")
  523. flags = os.O_RDONLY
  524. flags |= int(getattr(os, "O_BINARY", 0))
  525. flags |= int(getattr(os, "O_NOINHERIT", 0))
  526. flags |= int(getattr(os, "O_NOFOLLOW", 0))
  527. try:
  528. file_descriptor = os.open(candidate.absolute, flags)
  529. except OSError as exc:
  530. raise PackagingError(f"unable to open {candidate.relative} without following links: {exc}") from exc
  531. source: BinaryIO | None = None
  532. try:
  533. try:
  534. opened = os.fstat(file_descriptor)
  535. except OSError as exc:
  536. raise PackagingError(f"unable to inspect opened source {candidate.relative}: {exc}") from exc
  537. if not candidate_stat_matches(opened, candidate):
  538. raise PackagingError(f"source identity changed while opening: {candidate.relative}")
  539. source = os.fdopen(file_descriptor, "rb", closefd=True)
  540. file_descriptor = -1
  541. try:
  542. yield source
  543. try:
  544. opened_after = os.fstat(source.fileno())
  545. except OSError as exc:
  546. raise PackagingError(f"unable to inspect opened source {candidate.relative} after reading: {exc}") from exc
  547. finally:
  548. source.close()
  549. if not candidate_stat_matches(opened_after, candidate):
  550. raise PackagingError(f"source changed while reading: {candidate.relative}")
  551. finally:
  552. if file_descriptor >= 0:
  553. os.close(file_descriptor)
  554. try:
  555. after = os.lstat(candidate.absolute)
  556. except OSError as exc:
  557. raise PackagingError(f"unable to inspect {candidate.relative} after packaging: {exc}") from exc
  558. if not candidate_stat_matches(after, candidate):
  559. raise PackagingError(f"source changed during packaging: {candidate.relative}")
  560. @contextmanager
  561. def snapshot_candidate(
  562. candidate: Candidate,
  563. *,
  564. allow_disk: bool,
  565. ) -> Iterator[CandidateSnapshot]:
  566. snapshot = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO())
  567. try:
  568. digest = hashlib.sha256()
  569. total = 0
  570. secret_tail = b""
  571. with open_candidate(candidate) as source:
  572. while True:
  573. chunk = source.read(1024 * 1024)
  574. if not chunk:
  575. break
  576. secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative)
  577. snapshot.write(chunk)
  578. digest.update(chunk)
  579. total += len(chunk)
  580. if total != candidate.size:
  581. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  582. snapshot.seek(0)
  583. yield CandidateSnapshot(
  584. stream=snapshot,
  585. inventory={"path": candidate.relative, "size": total, "sha256": digest.hexdigest()},
  586. )
  587. except MemoryError as exc:
  588. raise PackagingError(f"insufficient memory to audit source file: {candidate.relative}") from exc
  589. finally:
  590. snapshot.close()
  591. def archive_kind(name: str) -> str | None:
  592. lower = name.casefold()
  593. if lower.endswith((".zip", ".whl", ".jar", ".apk", ".nupkg")):
  594. return "zip"
  595. if lower.endswith((".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".tar")):
  596. return "tar"
  597. if lower.endswith(".gz"):
  598. return "gzip"
  599. if lower.endswith((".rar", ".7z")):
  600. return "unsupported"
  601. return None
  602. def detect_archive_kind(source: BinaryIO, name: str) -> str | None:
  603. position = source.tell()
  604. try:
  605. source.seek(0)
  606. prefix = source.read(512)
  607. source.seek(0)
  608. if zipfile.is_zipfile(source):
  609. return "zip"
  610. hint = archive_kind(name)
  611. if prefix.startswith((b"7z\xbc\xaf'\x1c", b"Rar!\x1a\x07", b"(\xb5/\xfd", b"\x04\x22\x4d\x18")):
  612. return "unsupported"
  613. if prefix.startswith((b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")):
  614. return "zip"
  615. if prefix.startswith(b"\x1f\x8b"):
  616. return "tar" if hint == "tar" else "gzip"
  617. if prefix.startswith((b"BZh", b"\xfd7zXZ\x00")):
  618. return "tar"
  619. if len(prefix) >= 262 and prefix[257:262] == b"ustar":
  620. return "tar"
  621. if prefix.startswith((b"!<arch>\n", b"MSCF", b"xar!")):
  622. return "unsupported"
  623. return hint
  624. finally:
  625. source.seek(position)
  626. def archive_member_label(archive_label: str, member_name: str) -> str:
  627. normalized = unicodedata.normalize("NFC", member_name)
  628. if (
  629. "\\" in normalized
  630. or "\x00" in normalized
  631. or normalized.startswith("/")
  632. or re.match(r"^[A-Za-z]:", normalized)
  633. ):
  634. raise PackagingError(f"unsafe archive member path in {archive_label}")
  635. normalized = normalized.removesuffix("/")
  636. if not normalized:
  637. raise PackagingError(f"unsafe archive member path in {archive_label}")
  638. parts = normalized.split("/")
  639. if any(part in {"", ".", ".."} for part in parts):
  640. raise PackagingError(f"unsafe archive member path in {archive_label}")
  641. scan_secret_markers(normalized.encode("utf-8"), b"", f"{archive_label} member path")
  642. return f"{archive_label}!/{normalized}"
  643. def scan_archive_metadata(value: str | bytes, label: str) -> None:
  644. try:
  645. payload = value if isinstance(value, bytes) else value.encode("utf-8", errors="strict")
  646. except UnicodeError as exc:
  647. raise PackagingError(f"archive metadata is not valid UTF-8 in {label}") from exc
  648. scan_secret_markers(payload, b"", label)
  649. def account_archive_member(budget: ArchiveScanBudget, label: str) -> None:
  650. budget.member_count += 1
  651. if budget.member_count > MAX_ARCHIVE_MEMBERS:
  652. raise PackagingError(f"archive scan resource limit exceeded in {label}")
  653. def ensure_archive_bytes_available(budget: ArchiveScanBudget, size: int, label: str) -> None:
  654. if size < 0 or budget.uncompressed_bytes + size > MAX_ARCHIVE_UNCOMPRESSED_BYTES:
  655. raise PackagingError(f"archive scan resource limit exceeded in {label}")
  656. def scan_archive_member_stream(
  657. source: BinaryIO,
  658. *,
  659. member_name: str,
  660. label: str,
  661. depth: int,
  662. budget: ArchiveScanBudget,
  663. allow_disk: bool,
  664. ) -> None:
  665. sensitive_reason = secret_path_reason(member_name.removesuffix("/"), is_dir=False)
  666. if sensitive_reason is not None:
  667. raise PackagingError(
  668. f"credential or license path found in archive member: {label} ({sensitive_reason})"
  669. )
  670. nested = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO())
  671. try:
  672. secret_tail = b""
  673. while True:
  674. chunk = source.read(1024 * 1024)
  675. if not chunk:
  676. break
  677. ensure_archive_bytes_available(budget, len(chunk), label)
  678. budget.uncompressed_bytes += len(chunk)
  679. secret_tail = scan_secret_markers(chunk, secret_tail, label)
  680. nested.write(chunk)
  681. nested.seek(0)
  682. if detect_archive_kind(nested, member_name) is not None:
  683. scan_archive_stream(
  684. nested,
  685. name=member_name,
  686. label=label,
  687. depth=depth + 1,
  688. budget=budget,
  689. allow_disk=allow_disk,
  690. )
  691. except MemoryError as exc:
  692. raise PackagingError(f"insufficient memory to audit archive member: {label}") from exc
  693. finally:
  694. nested.close()
  695. def scan_archive_stream(
  696. source: BinaryIO,
  697. *,
  698. name: str,
  699. label: str,
  700. depth: int,
  701. budget: ArchiveScanBudget,
  702. allow_disk: bool,
  703. ) -> None:
  704. kind = detect_archive_kind(source, name)
  705. if kind is None:
  706. return
  707. if kind == "unsupported":
  708. raise PackagingError(f"unsupported archive format cannot be secret-scanned: {label}")
  709. if depth > MAX_ARCHIVE_DEPTH:
  710. raise PackagingError(f"archive scan resource limit exceeded in {label}")
  711. try:
  712. if kind == "zip":
  713. with zipfile.ZipFile(source) as archive:
  714. scan_archive_metadata(archive.comment, f"{label} archive comment")
  715. for zip_member in archive.infolist():
  716. account_archive_member(budget, label)
  717. member_label = archive_member_label(label, zip_member.filename)
  718. member_mode = (zip_member.external_attr >> 16) & 0xFFFF
  719. member_type = stat.S_IFMT(member_mode)
  720. scan_archive_metadata(zip_member.comment, f"{member_label} comment")
  721. scan_archive_metadata(zip_member.extra, f"{member_label} extra metadata")
  722. if zip_member.flag_bits & 0x1:
  723. raise PackagingError(f"unsafe archive member type in {member_label}")
  724. if zip_member.is_dir():
  725. if (
  726. zip_member.file_size != 0
  727. or zip_member.compress_size != 0
  728. or member_type not in {0, stat.S_IFDIR}
  729. ):
  730. raise PackagingError(f"unsafe archive member type in {member_label}")
  731. continue
  732. if member_type not in {0, stat.S_IFREG}:
  733. raise PackagingError(f"unsafe archive member type in {member_label}")
  734. ensure_archive_bytes_available(budget, zip_member.file_size, member_label)
  735. with archive.open(zip_member, "r") as zip_member_source:
  736. scan_archive_member_stream(
  737. cast(BinaryIO, zip_member_source),
  738. member_name=zip_member.filename,
  739. label=member_label,
  740. depth=depth,
  741. budget=budget,
  742. allow_disk=allow_disk,
  743. )
  744. return
  745. if kind == "tar":
  746. with tarfile.open(fileobj=source, mode="r:*") as archive:
  747. for key, value in archive.pax_headers.items():
  748. scan_archive_metadata(key, f"{label} global pax key")
  749. scan_archive_metadata(value, f"{label} global pax value")
  750. for tar_member in archive:
  751. account_archive_member(budget, label)
  752. member_label = archive_member_label(label, tar_member.name)
  753. for field_name, value in (
  754. ("linkname", tar_member.linkname),
  755. ("uname", tar_member.uname),
  756. ("gname", tar_member.gname),
  757. ):
  758. scan_archive_metadata(value, f"{member_label} {field_name}")
  759. for key, value in tar_member.pax_headers.items():
  760. scan_archive_metadata(key, f"{member_label} pax key")
  761. scan_archive_metadata(value, f"{member_label} pax value")
  762. if tar_member.isdir():
  763. if tar_member.size != 0:
  764. raise PackagingError(f"unsafe archive member type in {member_label}")
  765. continue
  766. if not tar_member.isfile():
  767. raise PackagingError(f"unsafe archive member type in {member_label}")
  768. ensure_archive_bytes_available(budget, tar_member.size, member_label)
  769. tar_member_source = archive.extractfile(tar_member)
  770. if tar_member_source is None:
  771. raise PackagingError(f"unable to inspect archive member in {member_label}")
  772. with tar_member_source:
  773. scan_archive_member_stream(
  774. cast(BinaryIO, tar_member_source),
  775. member_name=tar_member.name,
  776. label=member_label,
  777. depth=depth,
  778. budget=budget,
  779. allow_disk=allow_disk,
  780. )
  781. return
  782. with gzip.GzipFile(fileobj=source, mode="rb") as gzip_member_source:
  783. scan_archive_member_stream(
  784. cast(BinaryIO, gzip_member_source),
  785. member_name=name.removesuffix(".gz"),
  786. label=f"{label}!/<gzip>",
  787. depth=depth,
  788. budget=budget,
  789. allow_disk=allow_disk,
  790. )
  791. except PackagingError:
  792. raise
  793. except (OSError, EOFError, RuntimeError, tarfile.TarError, zipfile.BadZipFile) as exc:
  794. raise PackagingError(f"unable to inspect archive safely: {label} ({type(exc).__name__})") from exc
  795. def scan_candidate_archive(candidate: Candidate) -> None:
  796. with snapshot_candidate(candidate, allow_disk=True) as snapshot:
  797. scan_archive_stream(
  798. snapshot.stream,
  799. name=candidate.relative,
  800. label=candidate.relative,
  801. depth=0,
  802. budget=ArchiveScanBudget(),
  803. allow_disk=True,
  804. )
  805. def audit_candidates(candidates: Iterable[Candidate]) -> list[dict[str, object]]:
  806. inventory = []
  807. for candidate in candidates:
  808. inventory.append(stream_candidate(candidate))
  809. return inventory
  810. def zip_info(name: str, mode: int = stat.S_IFREG | 0o644) -> zipfile.ZipInfo:
  811. info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
  812. info.compress_type = zipfile.ZIP_DEFLATED
  813. info.create_system = 3
  814. info.external_attr = ((stat.S_IFREG | (mode & 0o777)) & 0xFFFF) << 16
  815. return info
  816. def stream_candidate(
  817. candidate: Candidate,
  818. target: BinaryIO | None = None,
  819. *,
  820. allow_disk: bool = True,
  821. ) -> dict[str, object]:
  822. with snapshot_candidate(candidate, allow_disk=allow_disk) as snapshot:
  823. scan_archive_stream(
  824. snapshot.stream,
  825. name=candidate.relative,
  826. label=candidate.relative,
  827. depth=0,
  828. budget=ArchiveScanBudget(),
  829. allow_disk=allow_disk,
  830. )
  831. if target is not None:
  832. snapshot.stream.seek(0)
  833. shutil.copyfileobj(snapshot.stream, target, length=1024 * 1024)
  834. return snapshot.inventory
  835. def hash_candidate(candidate: Candidate) -> dict[str, object]:
  836. digest = hashlib.sha256()
  837. total = 0
  838. secret_tail = b""
  839. with open_candidate(candidate) as source:
  840. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  841. secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative)
  842. digest.update(chunk)
  843. total += len(chunk)
  844. if total != candidate.size:
  845. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  846. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  847. def write_candidate(archive: zipfile.ZipFile, candidate: Candidate) -> dict[str, object]:
  848. entry_name = f"{ARCHIVE_ROOT}/{candidate.relative}"
  849. try:
  850. with archive.open(zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  851. return stream_candidate(candidate, target)
  852. except OSError as exc:
  853. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  854. def stage_candidate(
  855. staging_root: Path,
  856. candidate: Candidate,
  857. staging_name: str | None = None,
  858. ) -> dict[str, object]:
  859. target = staging_root / ARCHIVE_ROOT / (
  860. staging_name if staging_name is not None else Path(*candidate.relative.split("/"))
  861. )
  862. target.parent.mkdir(parents=True, exist_ok=True)
  863. try:
  864. with target.open("wb") as destination:
  865. return stream_candidate(candidate, target=destination)
  866. except OSError as exc:
  867. raise PackagingError(f"unable to stage {candidate.relative}: {exc}") from exc
  868. def write_bytes_entry(archive: zipfile.ZipFile, name: str, payload: bytes) -> None:
  869. scan_secret_markers(payload, b"", name)
  870. with archive.open(zip_info(name), "w", force_zip64=True) as handle:
  871. handle.write(payload)
  872. def json_bytes(payload: object) -> bytes:
  873. return (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
  874. def path_contains_reparse_point(root: Path, candidate: Path) -> bool:
  875. root_absolute = Path(os.path.abspath(root))
  876. candidate_absolute = Path(os.path.abspath(candidate))
  877. try:
  878. relative = candidate_absolute.relative_to(root_absolute)
  879. except ValueError:
  880. return True
  881. current = root_absolute
  882. for component in relative.parts:
  883. current /= component
  884. try:
  885. file_stat = os.lstat(current)
  886. except OSError:
  887. return True
  888. if stat_is_reparse_point(file_stat):
  889. return True
  890. return False
  891. def resolve_git_dir(root: Path) -> Path | None:
  892. marker = root / ".git"
  893. try:
  894. marker_stat = os.lstat(marker)
  895. except OSError:
  896. return None
  897. if stat_is_reparse_point(marker_stat):
  898. return None
  899. root_resolved = root.resolve(strict=True)
  900. if stat.S_ISDIR(marker_stat.st_mode):
  901. try:
  902. candidate = marker.resolve(strict=True)
  903. candidate.relative_to(root_resolved)
  904. except (OSError, RuntimeError, ValueError):
  905. return None
  906. return candidate
  907. if stat.S_ISREG(marker_stat.st_mode):
  908. try:
  909. text = read_stable_regular_bytes(marker, ".git marker", max_bytes=4096).decode(
  910. "utf-8",
  911. errors="strict",
  912. ).strip()
  913. except (PackagingError, UnicodeError):
  914. return None
  915. if text.startswith("gitdir:"):
  916. raw_candidate = root / text.split(":", 1)[1].strip()
  917. try:
  918. candidate = raw_candidate.resolve(strict=True)
  919. candidate.relative_to(root_resolved)
  920. except (OSError, RuntimeError, ValueError):
  921. return None
  922. if path_contains_reparse_point(root_resolved, raw_candidate):
  923. return None
  924. try:
  925. candidate_stat = os.lstat(candidate)
  926. except OSError:
  927. return None
  928. return candidate if stat.S_ISDIR(candidate_stat.st_mode) and not stat_is_reparse_point(candidate_stat) else None
  929. return None
  930. def read_head_metadata(git_dir: Path) -> tuple[str | None, str | None]:
  931. try:
  932. head = read_stable_regular_bytes(git_dir / "HEAD", "Git HEAD", max_bytes=4096).decode(
  933. "ascii",
  934. errors="strict",
  935. ).strip()
  936. except (PackagingError, UnicodeError):
  937. return None, None
  938. if not head.startswith("ref: "):
  939. return None, head if re.fullmatch(r"[0-9a-fA-F]{40}", head) else None
  940. ref = head[5:].strip()
  941. ref_parts = ref.split("/")
  942. if (
  943. not ref.startswith("refs/")
  944. or "\\" in ref
  945. or any(part in {"", ".", ".."} for part in ref_parts)
  946. or ".." in ref
  947. or "@{" in ref
  948. or ref.endswith((".", "/", ".lock"))
  949. or re.fullmatch(r"[A-Za-z0-9._/-]+", ref) is None
  950. ):
  951. return None, None
  952. branch = ref.removeprefix("refs/heads/") if ref.startswith("refs/heads/") else ref
  953. ref_file = git_dir.joinpath(*ref_parts)
  954. commit: str | None = None
  955. if os.path.lexists(ref_file):
  956. if path_contains_reparse_point(git_dir, ref_file):
  957. return branch, None
  958. try:
  959. commit = read_stable_regular_bytes(ref_file, f"Git ref {ref}", max_bytes=4096).decode(
  960. "ascii",
  961. errors="strict",
  962. ).strip()
  963. except (PackagingError, UnicodeError):
  964. return branch, None
  965. if commit is None:
  966. commit = None
  967. packed_refs = git_dir / "packed-refs"
  968. if os.path.lexists(packed_refs) and not path_contains_reparse_point(git_dir, packed_refs):
  969. try:
  970. packed_text = read_stable_regular_bytes(
  971. packed_refs,
  972. "Git packed-refs",
  973. max_bytes=16 * 1024 * 1024,
  974. ).decode("ascii", errors="strict")
  975. except (PackagingError, UnicodeError):
  976. packed_text = ""
  977. for line in packed_text.splitlines():
  978. if not line or line.startswith(("#", "^")):
  979. continue
  980. sha, _, packed_ref = line.partition(" ")
  981. if packed_ref == ref:
  982. commit = sha
  983. break
  984. if commit and not re.fullmatch(r"[0-9a-fA-F]{40}", commit):
  985. commit = None
  986. return branch, commit
  987. def run_capture(command: list[str], *, cwd: Path, timeout: int = 60) -> tuple[int, bytes]:
  988. try:
  989. completed = subprocess.run(
  990. command,
  991. cwd=cwd,
  992. stdout=subprocess.PIPE,
  993. stderr=subprocess.STDOUT,
  994. timeout=timeout,
  995. check=False,
  996. )
  997. except (OSError, subprocess.TimeoutExpired):
  998. return 1, b""
  999. return completed.returncode, completed.stdout
  1000. def collect_git_provenance(root: Path) -> tuple[dict[str, object], dict[str, bytes]]:
  1001. git_dir = resolve_git_dir(root)
  1002. if git_dir is None:
  1003. return {"status": "not_a_git_worktree", "branch": None, "head": None, "tool": None}, {}
  1004. branch, head = read_head_metadata(git_dir)
  1005. tool: str | None = None
  1006. status_command: list[str] | None = None
  1007. git = shutil.which("git")
  1008. if git:
  1009. tool = "git"
  1010. status_command = [
  1011. git,
  1012. "--no-optional-locks",
  1013. "-c",
  1014. "core.fsmonitor=false",
  1015. "-c",
  1016. "core.untrackedCache=false",
  1017. "status",
  1018. "--short",
  1019. "--branch",
  1020. "--untracked-files=all",
  1021. ]
  1022. elif importlib.util.find_spec("dulwich") is not None:
  1023. tool = "dulwich"
  1024. status_command = [sys.executable, "-I", "-m", "dulwich", "status"]
  1025. if status_command is None:
  1026. return {"status": "blocked_missing_git_tool", "branch": branch, "head": head, "tool": None}, {}
  1027. status_code, status_payload = run_capture(status_command, cwd=root)
  1028. artifacts: dict[str, bytes] = {}
  1029. if status_code == 0:
  1030. artifacts[f"{METADATA_ROOT}/git-status.txt"] = status_payload
  1031. capture_status = "pass" if status_code == 0 else "partial"
  1032. return {
  1033. "status": capture_status,
  1034. "branch": branch,
  1035. "head": head,
  1036. "tool": tool,
  1037. "status_captured": status_code == 0,
  1038. }, artifacts
  1039. def build_metadata(
  1040. *,
  1041. package_name: str,
  1042. inventory: list[dict[str, object]],
  1043. excluded: list[dict[str, str]],
  1044. context: ScanContext,
  1045. provenance: dict[str, object],
  1046. ) -> dict[str, bytes]:
  1047. rule_counts = Counter(item["rule"] for item in excluded)
  1048. manifest = {
  1049. "schema": "cpld-agent-handoff-v1",
  1050. "status": "pass",
  1051. "created_at": utc_now(),
  1052. "package_name": package_name,
  1053. "archive_root": ARCHIVE_ROOT,
  1054. "source_name": ARCHIVE_ROOT,
  1055. "included_file_count": len(inventory),
  1056. "included_bytes": sum(int(item["size"]) for item in inventory),
  1057. "excluded_entry_count": len(excluded),
  1058. "exclusion_rule_counts": dict(sorted(rule_counts.items())),
  1059. "changxin_temp_uart_version": context.changxin_version,
  1060. "git_provenance": provenance,
  1061. "archive_scan_limits": {
  1062. "max_depth": MAX_ARCHIVE_DEPTH,
  1063. "max_members": MAX_ARCHIVE_MEMBERS,
  1064. "max_uncompressed_bytes": MAX_ARCHIVE_UNCOMPRESSED_BYTES,
  1065. "source_file_size_limit": None,
  1066. },
  1067. "privacy": {
  1068. "manifest_contains_absolute_source_path": False,
  1069. "note": "Repository files are preserved byte-for-byte; review document and receipt contents before crossing a trust boundary.",
  1070. },
  1071. "authority_boundary": (
  1072. "This archive is an analysis handoff of source, requirements, tests, original references, and retained evidence. "
  1073. "It excludes credentials, private archives, raw Git objects, and declared reconstructable runtime outputs."
  1074. ),
  1075. }
  1076. exclusions_payload = {
  1077. "schema": "cpld-agent-handoff-exclusions-v1",
  1078. "excluded": excluded,
  1079. "rule_counts": dict(sorted(rule_counts.items())),
  1080. }
  1081. inventory_payload = {
  1082. "schema": "cpld-agent-handoff-sha256-inventory-v1",
  1083. "inventory": inventory,
  1084. }
  1085. return {
  1086. f"{METADATA_ROOT}/manifest.json": json_bytes(manifest),
  1087. f"{METADATA_ROOT}/exclusions.json": json_bytes(exclusions_payload),
  1088. f"{METADATA_ROOT}/sha256-inventory.json": json_bytes(inventory_payload),
  1089. }
  1090. def validate_zip_entry(name: str) -> str:
  1091. if not name.startswith(ARCHIVE_ROOT + "/") or "\\" in name or name.startswith("/"):
  1092. raise PackagingError(f"unsafe ZIP entry: {name}")
  1093. relative = name[len(ARCHIVE_ROOT) + 1 :]
  1094. normalize_relative(relative.split("/"))
  1095. return windows_collision_key(name)
  1096. def verify_archive(
  1097. path: Path | BinaryIO,
  1098. *,
  1099. expected_names: set[str],
  1100. inventory: list[dict[str, object]],
  1101. expected_payloads: dict[str, bytes] | None = None,
  1102. ) -> None:
  1103. try:
  1104. with zipfile.ZipFile(path, "r", allowZip64=True) as archive:
  1105. names = archive.namelist()
  1106. if len(names) != len(set(names)):
  1107. raise PackagingError("ZIP contains duplicate entry names")
  1108. file_names = [name for name in names if not name.endswith("/")]
  1109. collision_keys: dict[str, str] = {}
  1110. for name in names:
  1111. if name.endswith("/"):
  1112. if name == ARCHIVE_ROOT + "/":
  1113. continue
  1114. if not name.startswith(ARCHIVE_ROOT + "/"):
  1115. raise PackagingError(f"unsafe ZIP directory entry: {name}")
  1116. relative_directory = name[len(ARCHIVE_ROOT) + 1 :].removesuffix("/")
  1117. normalize_relative(relative_directory.split("/"))
  1118. continue
  1119. key = validate_zip_entry(name)
  1120. previous = collision_keys.get(key)
  1121. if previous is not None and previous != name:
  1122. raise PackagingError(f"ZIP contains a Windows path collision: {previous} and {name}")
  1123. collision_keys[key] = name
  1124. if set(file_names) != expected_names:
  1125. missing = sorted(expected_names - set(file_names))
  1126. unexpected = sorted(set(file_names) - expected_names)
  1127. raise PackagingError(f"ZIP entry verification failed; missing={missing}, unexpected={unexpected}")
  1128. bad = archive.testzip()
  1129. if bad is not None:
  1130. raise PackagingError(f"ZIP CRC verification failed for {bad}")
  1131. for item in inventory:
  1132. entry_name = f"{ARCHIVE_ROOT}/{item['path']}"
  1133. digest = hashlib.sha256()
  1134. total = 0
  1135. with archive.open(entry_name, "r") as handle:
  1136. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  1137. digest.update(chunk)
  1138. total += len(chunk)
  1139. if total != item["size"] or digest.hexdigest() != item["sha256"]:
  1140. raise PackagingError(f"ZIP SHA256 verification failed for {item['path']}")
  1141. for name, expected_payload in (expected_payloads or {}).items():
  1142. if archive.read(name) != expected_payload:
  1143. raise PackagingError(f"ZIP generated metadata verification failed for {name}")
  1144. except (OSError, zipfile.BadZipFile) as exc:
  1145. raise PackagingError(f"unable to verify ZIP archive: {exc}") from exc
  1146. def publish_target_identity(file_stat: os.stat_result) -> tuple[int, int, int, int, int]:
  1147. return (
  1148. int(file_stat.st_dev),
  1149. int(file_stat.st_ino),
  1150. int(file_stat.st_mode),
  1151. int(file_stat.st_size),
  1152. int(file_stat.st_mtime_ns),
  1153. )
  1154. def stat_is_windows_read_only(file_stat: os.stat_result) -> bool:
  1155. attributes = int(getattr(file_stat, "st_file_attributes", 0))
  1156. read_only_flag = int(getattr(stat, "FILE_ATTRIBUTE_READONLY", 0))
  1157. return bool(read_only_flag and attributes & read_only_flag)
  1158. def stat_is_read_only(file_stat: os.stat_result) -> bool:
  1159. return stat_is_windows_read_only(file_stat) or (int(file_stat.st_mode) & 0o222) == 0
  1160. def validate_publish_targets(paths: Iterable[Path], *, force: bool) -> dict[Path, tuple[int, int, int, int, int]]:
  1161. existing: dict[Path, tuple[int, int, int, int, int]] = {}
  1162. for path in paths:
  1163. if not os.path.lexists(path):
  1164. continue
  1165. if not force:
  1166. raise PackagingError(f"package artifact already exists: {path.name}")
  1167. try:
  1168. file_stat = os.lstat(path)
  1169. except OSError as exc:
  1170. raise PackagingError(f"unable to inspect existing package artifact {path.name}: {exc}") from exc
  1171. if not stat.S_ISREG(file_stat.st_mode) or stat_is_reparse_point(file_stat):
  1172. raise PackagingError(f"existing package artifact is not a regular file: {path.name}")
  1173. if stat_is_read_only(file_stat):
  1174. raise PackagingError(f"existing package artifact is read-only: {path.name}")
  1175. existing[path] = publish_target_identity(file_stat)
  1176. return existing
  1177. def publish_artifacts_atomically(
  1178. artifacts: list[tuple[Path, Path]],
  1179. *,
  1180. force: bool,
  1181. verify_published: Callable[[], None] | None = None,
  1182. ) -> list[str]:
  1183. backups: dict[Path, Path] = {}
  1184. published: list[Path] = []
  1185. final_paths = [final_path for _, final_path in artifacts]
  1186. existing = validate_publish_targets(final_paths, force=force)
  1187. try:
  1188. for _, final_path in artifacts:
  1189. expected_identity = existing.get(final_path)
  1190. if expected_identity is not None:
  1191. try:
  1192. current = os.lstat(final_path)
  1193. except OSError as exc:
  1194. raise PackagingError(f"existing package artifact changed before publication: {final_path.name}") from exc
  1195. if (
  1196. not stat.S_ISREG(current.st_mode)
  1197. or stat_is_reparse_point(current)
  1198. or stat_is_read_only(current)
  1199. or publish_target_identity(current) != expected_identity
  1200. ):
  1201. raise PackagingError(f"existing package artifact changed before publication: {final_path.name}")
  1202. backup = final_path.with_name(f".{final_path.name}.{uuid.uuid4().hex}.backup")
  1203. os.replace(final_path, backup)
  1204. backups[final_path] = backup
  1205. elif os.path.lexists(final_path):
  1206. raise PackagingError(f"package artifact appeared during publication: {final_path.name}")
  1207. for temp_path, final_path in artifacts:
  1208. os.link(temp_path, final_path)
  1209. published.append(final_path)
  1210. if verify_published is not None:
  1211. verify_published()
  1212. except BaseException as exc:
  1213. rollback_errors: list[str] = []
  1214. for final_path in reversed(published):
  1215. if final_path in backups:
  1216. continue
  1217. try:
  1218. final_path.unlink(missing_ok=True)
  1219. except OSError as rollback_exc:
  1220. rollback_errors.append(
  1221. f"remove {final_path.name} ({type(rollback_exc).__name__})"
  1222. )
  1223. for final_path, backup in backups.items():
  1224. if os.path.lexists(backup):
  1225. try:
  1226. os.replace(backup, final_path)
  1227. except OSError as rollback_exc:
  1228. rollback_errors.append(
  1229. f"restore {final_path.name} from {backup.name} ({type(rollback_exc).__name__})"
  1230. )
  1231. if rollback_errors:
  1232. recovery_paths = sorted(
  1233. str(path)
  1234. for path in (*backups.values(), *published)
  1235. if os.path.lexists(path)
  1236. )
  1237. recovery = ", ".join(recovery_paths) if recovery_paths else "none"
  1238. details = "; ".join(rollback_errors)
  1239. raise PackagingError(
  1240. f"package publication failed and rollback was incomplete: {details}; "
  1241. f"manual recovery paths: {recovery}"
  1242. ) from exc
  1243. if isinstance(exc, PackagingError):
  1244. raise
  1245. if isinstance(exc, OSError):
  1246. raise PackagingError(f"unable to publish package artifacts atomically: {exc}") from exc
  1247. raise
  1248. cleanup_warnings: list[str] = []
  1249. for temp_path, _ in artifacts:
  1250. try:
  1251. temp_path.unlink(missing_ok=True)
  1252. except OSError as exc:
  1253. cleanup_warnings.append(
  1254. f"published temporary artifact could not be removed: {temp_path.name} ({type(exc).__name__})"
  1255. )
  1256. for backup in backups.values():
  1257. try:
  1258. backup.unlink(missing_ok=True)
  1259. except OSError as exc:
  1260. cleanup_warnings.append(
  1261. f"published artifact backup could not be removed: {backup.name} ({type(exc).__name__})"
  1262. )
  1263. return cleanup_warnings
  1264. def remove_partial_artifacts(paths: Iterable[Path]) -> None:
  1265. failures: list[str] = []
  1266. for path in paths:
  1267. try:
  1268. path.unlink(missing_ok=True)
  1269. except OSError:
  1270. failures.append(path.name)
  1271. if failures:
  1272. names = ", ".join(sorted(failures))
  1273. raise PackagingError(f"unable to remove partial package artifacts: {names}")
  1274. @contextmanager
  1275. def open_stable_regular_file(path: Path, label: str) -> Iterator[BinaryIO]:
  1276. try:
  1277. before = os.lstat(path)
  1278. except OSError as exc:
  1279. raise PackagingError(f"unable to inspect {label}: {exc}") from exc
  1280. if not stat.S_ISREG(before.st_mode) or stat_is_reparse_point(before):
  1281. raise PackagingError(f"published artifact is not a regular file: {label}")
  1282. flags = os.O_RDONLY
  1283. flags |= int(getattr(os, "O_BINARY", 0))
  1284. flags |= int(getattr(os, "O_NOINHERIT", 0))
  1285. flags |= int(getattr(os, "O_NOFOLLOW", 0))
  1286. try:
  1287. descriptor = os.open(path, flags)
  1288. except OSError as exc:
  1289. raise PackagingError(f"unable to open {label} without following links: {exc}") from exc
  1290. handle: BinaryIO | None = None
  1291. try:
  1292. opened = os.fstat(descriptor)
  1293. if publish_target_identity(opened) != publish_target_identity(before):
  1294. raise PackagingError(f"published artifact changed while opening: {label}")
  1295. handle = os.fdopen(descriptor, "rb", closefd=True)
  1296. descriptor = -1
  1297. yield handle
  1298. opened_after = os.fstat(handle.fileno())
  1299. if publish_target_identity(opened_after) != publish_target_identity(opened):
  1300. raise PackagingError(f"published artifact changed while reading: {label}")
  1301. finally:
  1302. if handle is not None:
  1303. handle.close()
  1304. if descriptor >= 0:
  1305. os.close(descriptor)
  1306. try:
  1307. after = os.lstat(path)
  1308. except OSError as exc:
  1309. raise PackagingError(f"unable to re-inspect {label}: {exc}") from exc
  1310. if publish_target_identity(after) != publish_target_identity(before):
  1311. raise PackagingError(f"published artifact changed during verification: {label}")
  1312. def read_stable_regular_bytes(path: Path, label: str, *, max_bytes: int) -> bytes:
  1313. with open_stable_regular_file(path, label) as handle:
  1314. payload = handle.read(max_bytes + 1)
  1315. if len(payload) > max_bytes:
  1316. raise PackagingError(f"regular file exceeds safe metadata read limit: {label}")
  1317. return payload
  1318. def verify_published_artifacts(
  1319. final_zip: Path,
  1320. final_sidecar: Path,
  1321. *,
  1322. expected_zip_sha256: str,
  1323. expected_sidecar: bytes,
  1324. expected_names: set[str],
  1325. inventory: list[dict[str, object]],
  1326. expected_payloads: dict[str, bytes],
  1327. ) -> None:
  1328. digest = hashlib.sha256()
  1329. with open_stable_regular_file(final_zip, final_zip.name) as handle:
  1330. verify_archive(
  1331. handle,
  1332. expected_names=expected_names,
  1333. inventory=inventory,
  1334. expected_payloads=expected_payloads,
  1335. )
  1336. handle.seek(0)
  1337. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  1338. digest.update(chunk)
  1339. if digest.hexdigest() != expected_zip_sha256:
  1340. raise PackagingError("published ZIP SHA256 does not match the verified package")
  1341. with open_stable_regular_file(final_sidecar, final_sidecar.name) as handle:
  1342. actual_sidecar = handle.read()
  1343. if actual_sidecar != expected_sidecar:
  1344. raise PackagingError("published SHA256 sidecar does not match the verified package")
  1345. def scan_snapshot(
  1346. candidates: Iterable[Candidate],
  1347. excluded: Iterable[dict[str, str]],
  1348. context: ScanContext,
  1349. ) -> tuple[tuple[tuple[object, ...], ...], tuple[tuple[str, str], ...], ScanContext]:
  1350. candidate_state = tuple(
  1351. (
  1352. item.relative,
  1353. item.size,
  1354. item.mtime_ns,
  1355. item.device,
  1356. item.inode,
  1357. item.mode,
  1358. )
  1359. for item in candidates
  1360. )
  1361. excluded_state = tuple((item["path"], item["rule"]) for item in excluded)
  1362. return candidate_state, excluded_state, context
  1363. def assert_source_tree_unchanged(
  1364. root: Path,
  1365. candidates: list[Candidate],
  1366. excluded: list[dict[str, str]],
  1367. context: ScanContext,
  1368. inventory: list[dict[str, object]],
  1369. ) -> None:
  1370. current_candidates, current_excluded, current_context = scan_tree(root)
  1371. if scan_snapshot(candidates, excluded, context) != scan_snapshot(
  1372. current_candidates,
  1373. current_excluded,
  1374. current_context,
  1375. ):
  1376. raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
  1377. expected_by_path = {str(item["path"]): item for item in inventory}
  1378. if len(expected_by_path) != len(current_candidates):
  1379. raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
  1380. for candidate in current_candidates:
  1381. current = hash_candidate(candidate)
  1382. expected = expected_by_path.get(candidate.relative)
  1383. if (
  1384. expected is None
  1385. or current["size"] != expected["size"]
  1386. or current["sha256"] != expected["sha256"]
  1387. ):
  1388. raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
  1389. def _build_package_with_zipfile(
  1390. temp_zip: Path,
  1391. *,
  1392. root: Path,
  1393. package_name: str,
  1394. candidates: list[Candidate],
  1395. excluded: list[dict[str, str]],
  1396. context: ScanContext,
  1397. provenance: dict[str, object],
  1398. provenance_artifacts: dict[str, bytes],
  1399. ) -> tuple[list[dict[str, object]], dict[str, bytes], dict[str, bytes]]:
  1400. """Fallback ZIP writer when 7-Zip is not available."""
  1401. inventory: list[dict[str, object]] = []
  1402. with zipfile.ZipFile(temp_zip, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as archive:
  1403. for candidate in candidates:
  1404. inventory.append(write_candidate(archive, candidate))
  1405. metadata_artifacts = build_metadata(
  1406. package_name=package_name,
  1407. inventory=inventory,
  1408. excluded=excluded,
  1409. context=context,
  1410. provenance=provenance,
  1411. )
  1412. for name, payload in sorted({**metadata_artifacts, **provenance_artifacts}.items()):
  1413. write_bytes_entry(archive, name, payload)
  1414. return inventory, metadata_artifacts, provenance_artifacts
  1415. def _build_package_with_7z(
  1416. seven_zip: Path,
  1417. temp_zip: Path,
  1418. *,
  1419. root: Path,
  1420. package_name: str,
  1421. token: str,
  1422. output_dir: Path,
  1423. candidates: list[Candidate],
  1424. excluded: list[dict[str, str]],
  1425. context: ScanContext,
  1426. provenance: dict[str, object],
  1427. provenance_artifacts: dict[str, bytes],
  1428. ) -> tuple[list[dict[str, object]], dict[str, bytes], dict[str, bytes], Path]:
  1429. inventory: list[dict[str, object]] = []
  1430. archive_renames: list[tuple[str, str]] = []
  1431. staging_root = Path(tempfile.mkdtemp(prefix=f".{package_name}.{token}.stage.", dir=output_dir))
  1432. try:
  1433. for number, candidate in enumerate(candidates):
  1434. staging_name = f"candidate-{number:08d}"
  1435. inventory.append(stage_candidate(staging_root, candidate, staging_name))
  1436. archive_renames.append(
  1437. (
  1438. f"{ARCHIVE_ROOT}/{staging_name}",
  1439. f"{ARCHIVE_ROOT}/{candidate.relative}",
  1440. )
  1441. )
  1442. metadata_artifacts = build_metadata(
  1443. package_name=package_name,
  1444. inventory=inventory,
  1445. excluded=excluded,
  1446. context=context,
  1447. provenance=provenance,
  1448. )
  1449. for name, payload in sorted({**metadata_artifacts, **provenance_artifacts}.items()):
  1450. target = staging_root / Path(*name.split("/"))
  1451. target.parent.mkdir(parents=True, exist_ok=True)
  1452. scan_secret_markers(payload, b"", name)
  1453. target.write_bytes(payload)
  1454. run_7zip(
  1455. seven_zip,
  1456. build_7zip_create_command(temp_zip, staging_root),
  1457. cwd=staging_root,
  1458. )
  1459. rename_archive_entries(seven_zip, temp_zip, archive_renames)
  1460. except BaseException:
  1461. shutil.rmtree(staging_root, ignore_errors=True)
  1462. raise
  1463. return inventory, metadata_artifacts, provenance_artifacts, staging_root
  1464. def create_package(
  1465. *,
  1466. root: Path,
  1467. output_dir: Path,
  1468. package_name: str,
  1469. force: bool,
  1470. candidates: list[Candidate],
  1471. excluded: list[dict[str, str]],
  1472. context: ScanContext,
  1473. ) -> dict[str, object]:
  1474. seven_zip = find_7z()
  1475. output_dir.mkdir(parents=True, exist_ok=True)
  1476. final_zip = output_dir / f"{package_name}.zip"
  1477. final_sidecar = output_dir / f"{package_name}.zip.sha256.txt"
  1478. validate_publish_targets((final_zip, final_sidecar), force=force)
  1479. token = f"{os.getpid()}.{uuid.uuid4().hex}"
  1480. temp_zip = output_dir / f".{package_name}.{token}.partial"
  1481. temp_sidecar = output_dir / f".{package_name}.{token}.sha256.partial"
  1482. inventory: list[dict[str, object]] = []
  1483. provenance, provenance_artifacts = collect_git_provenance(root)
  1484. metadata_artifacts: dict[str, bytes] = {}
  1485. staging_root: Path | None = None
  1486. try:
  1487. if seven_zip is None:
  1488. inventory, metadata_artifacts, provenance_artifacts = _build_package_with_zipfile(
  1489. temp_zip,
  1490. root=root,
  1491. package_name=package_name,
  1492. candidates=candidates,
  1493. excluded=excluded,
  1494. context=context,
  1495. provenance=provenance,
  1496. provenance_artifacts=provenance_artifacts,
  1497. )
  1498. else:
  1499. inventory, metadata_artifacts, provenance_artifacts, staging_root = _build_package_with_7z(
  1500. seven_zip,
  1501. temp_zip,
  1502. root=root,
  1503. package_name=package_name,
  1504. token=token,
  1505. output_dir=output_dir,
  1506. candidates=candidates,
  1507. excluded=excluded,
  1508. context=context,
  1509. provenance=provenance,
  1510. provenance_artifacts=provenance_artifacts,
  1511. )
  1512. expected_names = {f"{ARCHIVE_ROOT}/{item['path']}" for item in inventory}
  1513. expected_names.update(metadata_artifacts)
  1514. expected_names.update(provenance_artifacts)
  1515. expected_payloads = {**metadata_artifacts, **provenance_artifacts}
  1516. try:
  1517. with open_stable_regular_file(temp_zip, temp_zip.name) as verified_zip:
  1518. verify_archive(
  1519. verified_zip,
  1520. expected_names=expected_names,
  1521. inventory=inventory,
  1522. expected_payloads=expected_payloads,
  1523. )
  1524. verified_zip.seek(0)
  1525. zip_digest = hashlib.sha256()
  1526. for chunk in iter(lambda: verified_zip.read(1024 * 1024), b""):
  1527. zip_digest.update(chunk)
  1528. zip_sha256 = zip_digest.hexdigest()
  1529. except OSError as exc:
  1530. raise PackagingError("temporary ZIP changed during stable verification") from exc
  1531. assert_source_tree_unchanged(root, candidates, excluded, context, inventory)
  1532. sidecar_payload = f"{zip_sha256} {final_zip.name}\n".encode("ascii")
  1533. temp_sidecar.write_bytes(sidecar_payload)
  1534. def verify_publication() -> None:
  1535. verify_published_artifacts(
  1536. final_zip,
  1537. final_sidecar,
  1538. expected_zip_sha256=zip_sha256,
  1539. expected_sidecar=sidecar_payload,
  1540. expected_names=expected_names,
  1541. inventory=inventory,
  1542. expected_payloads=expected_payloads,
  1543. )
  1544. assert_source_tree_unchanged(root, candidates, excluded, context, inventory)
  1545. cleanup_warnings = publish_artifacts_atomically(
  1546. [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
  1547. force=force,
  1548. verify_published=verify_publication,
  1549. )
  1550. except BaseException as exc:
  1551. try:
  1552. remove_partial_artifacts((temp_zip, temp_sidecar))
  1553. except PackagingError as cleanup_exc:
  1554. raise PackagingError(f"{exc}; additionally, {cleanup_exc}") from exc
  1555. raise
  1556. finally:
  1557. if staging_root is not None:
  1558. shutil.rmtree(staging_root, ignore_errors=True)
  1559. return {
  1560. "status": "pass",
  1561. "mode": "package",
  1562. "package_name": package_name,
  1563. "package_zip": str(final_zip),
  1564. "package_zip_sha256": zip_sha256,
  1565. "sha256_sidecar": str(final_sidecar),
  1566. "included_file_count": len(inventory),
  1567. "included_bytes": sum(int(item["size"]) for item in inventory),
  1568. "excluded_entry_count": len(excluded),
  1569. "warnings": cleanup_warnings,
  1570. }
  1571. def validate_paths(source_root: Path, output_dir: Path) -> tuple[Path, Path]:
  1572. try:
  1573. source = source_root.expanduser().resolve(strict=True)
  1574. except OSError as exc:
  1575. raise PackagingError(f"SourceRoot is unavailable: {source_root}") from exc
  1576. if not source.is_dir():
  1577. raise PackagingError(f"SourceRoot is not a directory: {source_root}")
  1578. output = output_dir.expanduser().resolve(strict=False)
  1579. try:
  1580. output.relative_to(source)
  1581. except ValueError:
  1582. pass
  1583. else:
  1584. raise PackagingError("OutputDir must be outside SourceRoot to prevent recursive packaging")
  1585. return source, output
  1586. def build_parser() -> argparse.ArgumentParser:
  1587. parser = argparse.ArgumentParser(description=__doc__)
  1588. parser.add_argument("--source-root", type=Path, default=ROOT)
  1589. parser.add_argument(
  1590. "--output-dir",
  1591. type=Path,
  1592. default=Path.home() / "Downloads" / "CPLD-agent-handoff",
  1593. )
  1594. parser.add_argument("--package-name")
  1595. parser.add_argument("--force-overwrite", action="store_true")
  1596. parser.add_argument("--audit-only", action="store_true")
  1597. return parser
  1598. def main(argv: list[str] | None = None) -> int:
  1599. args = build_parser().parse_args(argv)
  1600. package_name = args.package_name or datetime.now(timezone.utc).strftime("cpld-agent-handoff-%Y%m%dT%H%M%SZ")
  1601. try:
  1602. portable_package_name = windows_collision_key(package_name)
  1603. except PackagingError:
  1604. portable_package_name = ""
  1605. if (
  1606. not SAFE_PACKAGE_NAME.fullmatch(package_name)
  1607. or package_name in {".", ".."}
  1608. or not portable_package_name
  1609. ):
  1610. print(
  1611. "error: PackageName must be a portable ASCII file name without path separators or Windows-reserved forms",
  1612. file=sys.stderr,
  1613. )
  1614. return 1
  1615. try:
  1616. source, output = validate_paths(args.source_root, args.output_dir)
  1617. candidates, excluded, context = scan_tree(source)
  1618. if args.audit_only:
  1619. audit_inventory = audit_candidates(candidates)
  1620. assert_source_tree_unchanged(source, candidates, excluded, context, audit_inventory)
  1621. rule_counts = Counter(item["rule"] for item in excluded)
  1622. payload = {
  1623. "status": "pass",
  1624. "mode": "audit_only",
  1625. "package_name": package_name,
  1626. "included_file_count": len(candidates),
  1627. "included_bytes": sum(item.size for item in candidates),
  1628. "excluded_entry_count": len(excluded),
  1629. "exclusion_rule_counts": dict(sorted(rule_counts.items())),
  1630. "changxin_temp_uart_version": context.changxin_version,
  1631. }
  1632. else:
  1633. payload = create_package(
  1634. root=source,
  1635. output_dir=output,
  1636. package_name=package_name,
  1637. force=args.force_overwrite,
  1638. candidates=candidates,
  1639. excluded=excluded,
  1640. context=context,
  1641. )
  1642. except (PackagingError, OSError) as exc:
  1643. print(f"error: {exc}", file=sys.stderr)
  1644. return 1
  1645. print(json.dumps(payload, ensure_ascii=False, indent=2))
  1646. return 0
  1647. if __name__ == "__main__":
  1648. raise SystemExit(main())