package_agent_handoff.py 70 KB

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