| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639 |
- #!/usr/bin/env python3
- """Create a comprehensive, sanitized CPLD workspace handoff archive."""
- from __future__ import annotations
- import argparse
- import gzip
- import hashlib
- import importlib.util
- import io
- import json
- import os
- import re
- import shutil
- import stat
- import subprocess
- import sys
- import tarfile
- import tempfile
- import tomllib
- import unicodedata
- import uuid
- import zipfile
- from collections import Counter
- from contextlib import contextmanager
- from dataclasses import dataclass
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import BinaryIO, Callable, Iterable, Iterator, cast
- ROOT = Path(__file__).resolve().parents[1]
- ARCHIVE_ROOT = "CPLD"
- METADATA_ROOT = f"{ARCHIVE_ROOT}/HANDOFF-METADATA"
- SECRET_SCAN_OVERLAP = 512
- MAX_ARCHIVE_DEPTH = 3
- MAX_ARCHIVE_MEMBERS = 100_000
- MAX_ARCHIVE_UNCOMPRESSED_BYTES = 8 * 1024 * 1024 * 1024
- SECRET_PATTERNS = (
- (
- "private key",
- re.compile(
- rb"-----BEGIN "
- + rb"(?:ENCRYPTED |RSA |DSA |EC |OPENSSH )?"
- + rb"PRIVATE KEY-----"
- + rb"|-----BEGIN PGP "
- + rb"PRIVATE KEY BLOCK-----"
- ),
- ),
- (
- "GitHub token",
- re.compile(
- rb"(?<![A-Za-z0-9_])(?:gh[pousr]_[A-Za-z0-9]{36,255}"
- rb"|github_pat_[A-Za-z0-9_]{60,255})(?![A-Za-z0-9_])"
- ),
- ),
- (
- "AWS secret access key",
- re.compile(
- rb"(?<![A-Za-z0-9_])aws_"
- + rb"(?:secret_access_key|secret_key)[\"']?\s*[:=]\s*[\"']?"
- + rb"[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])",
- re.IGNORECASE,
- ),
- ),
- (
- "AWS session token",
- re.compile(
- rb"(?<![A-Za-z0-9_])aws_"
- + rb"(?:session_token|security_token)[\"']?\s*[:=]\s*[\"']?"
- + rb"[A-Za-z0-9/+=]{32,2048}(?![A-Za-z0-9/+=])",
- re.IGNORECASE,
- ),
- ),
- (
- "OpenAI API key",
- re.compile(
- rb"(?<![A-Za-z0-9_-])sk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,255}"
- rb"(?![A-Za-z0-9_-])"
- ),
- ),
- (
- "Slack token",
- re.compile(rb"(?<![A-Za-z0-9-])xox[baprs]-[A-Za-z0-9-]{20,255}(?![A-Za-z0-9-])"),
- ),
- )
- SAFE_PACKAGE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$")
- TD_BUILD_EVIDENCE_SUFFIXES = {".qor", ".area", ".timing", ".rpt", ".log", ".logw"}
- WINDOWS_RESERVED_NAMES = {
- "con",
- "prn",
- "aux",
- "nul",
- *(f"com{index}" for index in range(1, 10)),
- *(f"lpt{index}" for index in range(1, 10)),
- }
- WINDOWS_INVALID_FILENAME_CHARS = frozenset('<>:"/\\|?*')
- class PackagingError(RuntimeError):
- """Raised when a handoff archive cannot be produced safely."""
- @dataclass(frozen=True)
- class Candidate:
- absolute: Path
- relative: str
- size: int
- mtime_ns: int
- device: int
- inode: int
- mode: int
- @dataclass
- class CandidateSnapshot:
- stream: BinaryIO
- inventory: dict[str, object]
- @dataclass
- class ArchiveScanBudget:
- member_count: int = 0
- uncompressed_bytes: int = 0
- @dataclass(frozen=True)
- class ScanContext:
- changxin_version: str | None
- def utc_now() -> str:
- return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
- def validate_windows_component(component: str, relative: str) -> str:
- if component.endswith((" ", ".")):
- raise PackagingError(f"path component has a Windows-unsafe trailing character: {relative}")
- if any(ord(character) < 32 or character in WINDOWS_INVALID_FILENAME_CHARS for character in component):
- raise PackagingError(f"path component contains a Windows-invalid character: {relative}")
- normalized = component.casefold()
- if normalized.split(".", 1)[0] in WINDOWS_RESERVED_NAMES:
- raise PackagingError(f"Windows reserved device name is not portable: {relative}")
- return normalized
- def normalize_relative(parts: Iterable[str]) -> str:
- try:
- relative = unicodedata.normalize("NFC", "/".join(parts))
- relative.encode("utf-8", errors="strict")
- except UnicodeError as exc:
- raise PackagingError("path is not valid UTF-8") from exc
- components = relative.split("/")
- if not relative or relative.startswith("/") or any(part in {"", ".", ".."} for part in components):
- raise PackagingError(f"unsafe relative path: {relative!r}")
- for component in components:
- validate_windows_component(component, relative)
- return relative
- def windows_collision_key(relative: str) -> str:
- components = []
- for component in unicodedata.normalize("NFC", relative).split("/"):
- if not component:
- raise PackagingError(f"path component is empty after Windows normalization: {relative}")
- normalized = validate_windows_component(component, relative)
- components.append(normalized)
- return "/".join(components)
- def is_under(relative: str, prefix: str) -> bool:
- return relative == prefix or relative.startswith(prefix + "/")
- def load_scan_context(root: Path) -> ScanContext:
- pyproject = root / "tools" / "changxin-temp-uart" / "pyproject.toml"
- version: str | None = None
- try:
- raw_payload = read_stable_regular_bytes(
- pyproject,
- "Changxin pyproject",
- max_bytes=1024 * 1024,
- )
- payload = tomllib.loads(raw_payload.decode("utf-8-sig", errors="strict"))
- value = payload.get("project", {}).get("version")
- if isinstance(value, str) and value.strip():
- version = value.strip()
- except (PackagingError, UnicodeError, tomllib.TOMLDecodeError):
- version = None
- return ScanContext(version)
- def secret_path_reason(relative: str, *, is_dir: bool) -> str | None:
- if is_dir:
- return None
- name = relative.rsplit("/", 1)[-1].casefold()
- parts = relative.casefold().split("/")
- suffix = Path(name).suffix.casefold()
- if name == ".env" or (
- name.startswith(".env.")
- and not name.endswith((".example", ".sample", ".template", ".dist"))
- ):
- return "secret_environment_file"
- if name in {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"} or name.startswith("id_rsa."):
- return "private_key_file"
- if name in {".netrc", "_netrc", ".pypirc", ".npmrc", ".git-credentials"}:
- return "credential_configuration_file"
- if len(parts) >= 2 and parts[-2:] == [".aws", "credentials"]:
- return "cloud_credential_file"
- if len(parts) >= 2 and parts[-2:] == [".docker", "config.json"]:
- return "container_registry_credential_file"
- if len(parts) >= 2 and parts[-2:] == ["gcloud", "application_default_credentials.json"]:
- return "cloud_credential_file"
- if suffix in {".key", ".pfx", ".p12", ".lic"}:
- return "credential_or_license_file"
- return None
- def common_file_exclusion_reason(relative: str) -> str | None:
- lower = relative.casefold()
- name = lower.rsplit("/", 1)[-1]
- suffix = Path(name).suffix.casefold()
- if suffix in {".pyc", ".pyo"}:
- return "python_bytecode"
- if suffix in {".tmp", ".partial", ".part", ".swp", ".swo"} or name.endswith("~"):
- return "atomic_or_editor_temporary_file"
- if suffix == ".dmp" or name.startswith("minidump-"):
- return "crash_dump"
- if name == "a.out" or (name.startswith("tmp_last_pkg") and name.endswith(".txt")):
- return "temporary_build_artifact"
- if name in {".ds_store", "thumbs.db", "desktop.ini"}:
- return "os_metadata_cache"
- if name in {".coverage", "coverage.xml"}:
- return "coverage_cache"
- if name.startswith(".coverage."):
- return "coverage_cache"
- if lower.startswith("td/td_") and suffix in {".log", ".logw"}:
- return "td_root_runtime_log"
- if "/" not in lower and lower.startswith("td_") and suffix in {".log", ".logw"}:
- return "td_root_runtime_log"
- generated_binary_suffixes = {".bit", ".bid", ".data", ".db", ".vvp"}
- if suffix in generated_binary_suffixes and not (
- is_under(lower, "reference/original") or is_under(lower, "tests/fixtures")
- ):
- return "generated_binary_artifact"
- return None
- def exclusion_reason(relative: str, *, is_dir: bool, context: ScanContext) -> str | None:
- lower = relative.casefold()
- parts = lower.split("/")
- name = parts[-1]
- if parts[0] == "handoff-metadata":
- raise PackagingError(f"source uses reserved package path: {relative}")
- secret_reason = secret_path_reason(relative, is_dir=is_dir)
- if secret_reason:
- return secret_reason
- explicit_roots = {
- ".git": "raw_git_metadata",
- ".codegraph": "external_codegraph_cache",
- ".omo": "agent_session_runtime",
- ".hypothesis": "hypothesis_cache",
- ".pytest_cache": "pytest_cache",
- "workspace": "deprecated_workspace",
- "_archive": "deprecated_archive",
- "unused": "unused_workspace_area",
- "log": "runtime_log_directory",
- "dist": "generated_handoff_output",
- "anlogic_cd": "vendor_installer_payload",
- "reference/original/local_archives": "restricted_local_archive",
- "reference/original/vendor": "restricted_vendor_payload",
- "receipts/local": "local_runtime_receipt",
- "j6-binary921-deliverables": "generated_delivery_package",
- "j6tmp-v2-tailfix-package": "generated_delivery_package",
- "cpld-deliverables": "generated_delivery_package",
- }
- for prefix, reason in explicit_roots.items():
- if is_under(lower, prefix):
- return reason
- if lower in {"td/project/.lock.f", "td/project/.recent_user_depot.ini"}:
- return "td_gui_runtime_state"
- if is_under(lower, "td/project/log"):
- return "td_gui_runtime_log"
- if is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
- return "td_gui_runtime_run"
- if lower == "tests/cocotb/results.xml":
- return "cocotb_transient_result"
- if not is_dir:
- common_reason = common_file_exclusion_reason(relative)
- retained_tmp_reasons = {
- "atomic_or_editor_temporary_file",
- "crash_dump",
- "coverage_cache",
- }
- if common_reason and not (
- is_under(lower, "tmp") and common_reason in retained_tmp_reasons
- ):
- return common_reason
- cache_components = {
- "__pycache__": "python_bytecode_cache",
- ".pytest_cache": "pytest_cache",
- ".hypothesis": "hypothesis_cache",
- ".mypy_cache": "mypy_cache",
- ".ruff_cache": "ruff_cache",
- ".tox": "tox_environment",
- ".nox": "nox_environment",
- ".venv": "virtual_environment",
- "venv": "virtual_environment",
- "htmlcov": "coverage_report",
- "sim_build": "simulation_build",
- "obj_dir": "verilator_build",
- }
- for component in parts:
- if component in cache_components:
- return cache_components[component]
- if component.endswith(".egg-info"):
- return "python_package_metadata"
- if component == ".logs":
- return "td_generated_run_directory"
- if lower == ".codex":
- return None
- if is_under(lower, ".codex/reports"):
- return None
- if is_under(lower, ".codex/cleanup_manifests"):
- return "duplicated_cleanup_runtime_manifest"
- if is_under(lower, ".codex"):
- return "codex_local_runtime"
- if is_under(lower, "tools/changxin-temp-uart/build"):
- return "python_package_build_copy"
- if is_under(lower, "tools/changxin-temp-uart/pyinstaller-build"):
- return "pyinstaller_build_cache"
- if is_under(lower, "tools/changxin-temp-uart/pyinstaller-spec"):
- return "pyinstaller_spec_cache"
- if lower in {
- "tools/changxin-temp-uart/pyinstaller-entry.py",
- "tools/changxin-temp-uart/linux-onefile-build.json",
- "tools/changxin-temp-uart/changxin-temp-uart-static",
- }:
- return "pyinstaller_generated_output"
- if lower == "tools/changxin-temp-uart/dist":
- return None
- if is_under(lower, "tools/changxin-temp-uart/dist"):
- return None
- if lower == "td/build":
- return None
- if is_under(lower, "td/build"):
- build_parts = parts[2:]
- if any(component in {"src", "constraints", "td_user_env"} for component in build_parts):
- return "td_staged_source_or_runtime_copy"
- if is_dir:
- return None
- suffix = Path(name).suffix.casefold()
- if (
- name == "source-manifest.json"
- or name.endswith("_elaboration_plan.json")
- or suffix in TD_BUILD_EVIDENCE_SUFFIXES
- ):
- return None
- return "td_generated_non_evidence"
- if lower == "tmp":
- return None
- if is_under(lower, "tmp"):
- transient_tmp_roots = {
- "tmp/rtl_sim": "compiled_rtl_simulation",
- "tmp/cocotb": "cocotb_runtime",
- "tmp/detector_selftest": "detector_selftest_runtime",
- "tmp/toolchain_probe": "toolchain_probe_runtime",
- }
- for prefix, reason in transient_tmp_roots.items():
- if is_under(lower, prefix):
- return reason
- for evidence_prefix in (
- "tmp/resource_audit",
- "tmp/pwm_executor_probe",
- ):
- if is_under(lower, evidence_prefix):
- evidence_parts = parts[len(evidence_prefix.split("/")) :]
- if "td_user_env" in evidence_parts:
- return "td_staged_source_or_runtime_copy"
- return None
- return None
- return None
- def stat_is_reparse_point(file_stat: os.stat_result) -> bool:
- attributes = int(getattr(file_stat, "st_file_attributes", 0))
- reparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
- return stat.S_ISLNK(file_stat.st_mode) or bool(reparse_flag and attributes & reparse_flag)
- def is_reparse_point(entry: os.DirEntry[str], file_stat: os.stat_result) -> bool:
- return entry.is_symlink() or stat_is_reparse_point(file_stat)
- def invalid_receipt_reason(path: Path, relative: str, size: int) -> str | None:
- if not relative.casefold().startswith("receipts/") or not relative.casefold().endswith(".json"):
- return None
- if size == 0:
- return "empty_receipt"
- if size <= 32:
- try:
- if path.read_bytes().strip().lower() == b"null":
- return "null_receipt"
- except OSError as exc:
- raise PackagingError(f"unable to inspect receipt {relative}: {exc}") from exc
- return None
- def scan_tree(
- root: Path,
- *,
- exclusion_resolver: Callable[..., str | None] | None = None,
- ) -> tuple[list[Candidate], list[dict[str, str]], ScanContext]:
- context = load_scan_context(root)
- resolve_exclusion = exclusion_resolver or exclusion_reason
- included: list[Candidate] = []
- excluded: list[dict[str, str]] = []
- collision_paths: dict[str, str] = {}
- def record_exclusion(relative: str, reason: str) -> None:
- excluded.append({"path": relative, "rule": reason})
- def walk(directory: Path, relative_parts: tuple[str, ...]) -> None:
- try:
- with os.scandir(directory) as iterator:
- entries = sorted(
- list(iterator),
- key=lambda item: unicodedata.normalize("NFC", item.name).casefold(),
- )
- except OSError as exc:
- relative = "/".join(relative_parts) or "."
- raise PackagingError(f"unable to enumerate {relative}: {exc}") from exc
- for entry in entries:
- relative = normalize_relative((*relative_parts, entry.name))
- scan_secret_markers(relative.encode("utf-8"), b"", "[source path]")
- try:
- file_stat = os.lstat(entry.path)
- except OSError as exc:
- raise PackagingError(f"unable to inspect {relative}: {exc}") from exc
- is_directory = stat.S_ISDIR(file_stat.st_mode)
- reason = resolve_exclusion(relative, is_dir=is_directory, context=context)
- if is_reparse_point(entry, file_stat):
- if reason:
- record_exclusion(relative, reason)
- continue
- raise PackagingError(f"undeclared reparse point refuses packaging: {relative}")
- if reason:
- record_exclusion(relative, reason)
- continue
- if is_directory:
- walk(Path(entry.path), (*relative_parts, entry.name))
- continue
- if not stat.S_ISREG(file_stat.st_mode):
- raise PackagingError(f"unsupported non-regular file: {relative}")
- receipt_reason = invalid_receipt_reason(Path(entry.path), relative, file_stat.st_size)
- if receipt_reason:
- record_exclusion(relative, receipt_reason)
- continue
- key = windows_collision_key(relative)
- previous = collision_paths.get(key)
- if previous is not None:
- raise PackagingError(f"Windows ZIP path collision: {previous} and {relative}")
- collision_paths[key] = relative
- if int(file_stat.st_dev) == 0 or int(file_stat.st_ino) == 0:
- raise PackagingError(f"filesystem does not expose a stable file identity: {relative}")
- included.append(
- Candidate(
- Path(entry.path),
- relative,
- file_stat.st_size,
- file_stat.st_mtime_ns,
- int(file_stat.st_dev),
- int(file_stat.st_ino),
- int(file_stat.st_mode),
- )
- )
- walk(root, ())
- included.sort(key=lambda item: windows_collision_key(item.relative))
- excluded.sort(key=lambda item: (windows_collision_key(item["path"]), item["rule"]))
- return included, excluded, context
- def sha256_file(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def scan_secret_markers(chunk: bytes, tail: bytes, relative: str) -> bytes:
- combined = tail + chunk
- for label, pattern in SECRET_PATTERNS:
- if pattern.search(combined):
- raise PackagingError(f"high-confidence {label} secret found in {relative}")
- return combined[-SECRET_SCAN_OVERLAP:]
- def candidate_stat_matches(file_stat: os.stat_result, candidate: Candidate) -> bool:
- return (
- stat.S_ISREG(file_stat.st_mode)
- and not stat_is_reparse_point(file_stat)
- and int(file_stat.st_dev) == candidate.device
- and int(file_stat.st_ino) == candidate.inode
- and (os.name == "nt" or int(file_stat.st_mode) == candidate.mode)
- and file_stat.st_size == candidate.size
- and file_stat.st_mtime_ns == candidate.mtime_ns
- )
- @contextmanager
- def open_candidate(candidate: Candidate) -> Iterator[BinaryIO]:
- try:
- before = os.lstat(candidate.absolute)
- except OSError as exc:
- raise PackagingError(f"unable to inspect {candidate.relative} before packaging: {exc}") from exc
- if not candidate_stat_matches(before, candidate):
- raise PackagingError(f"source changed after enumeration: {candidate.relative}")
- flags = os.O_RDONLY
- flags |= int(getattr(os, "O_BINARY", 0))
- flags |= int(getattr(os, "O_NOINHERIT", 0))
- flags |= int(getattr(os, "O_NOFOLLOW", 0))
- try:
- file_descriptor = os.open(candidate.absolute, flags)
- except OSError as exc:
- raise PackagingError(f"unable to open {candidate.relative} without following links: {exc}") from exc
- source: BinaryIO | None = None
- try:
- try:
- opened = os.fstat(file_descriptor)
- except OSError as exc:
- raise PackagingError(f"unable to inspect opened source {candidate.relative}: {exc}") from exc
- if not candidate_stat_matches(opened, candidate):
- raise PackagingError(f"source identity changed while opening: {candidate.relative}")
- source = os.fdopen(file_descriptor, "rb", closefd=True)
- file_descriptor = -1
- try:
- yield source
- try:
- opened_after = os.fstat(source.fileno())
- except OSError as exc:
- raise PackagingError(f"unable to inspect opened source {candidate.relative} after reading: {exc}") from exc
- finally:
- source.close()
- if not candidate_stat_matches(opened_after, candidate):
- raise PackagingError(f"source changed while reading: {candidate.relative}")
- finally:
- if file_descriptor >= 0:
- os.close(file_descriptor)
- try:
- after = os.lstat(candidate.absolute)
- except OSError as exc:
- raise PackagingError(f"unable to inspect {candidate.relative} after packaging: {exc}") from exc
- if not candidate_stat_matches(after, candidate):
- raise PackagingError(f"source changed during packaging: {candidate.relative}")
- @contextmanager
- def snapshot_candidate(
- candidate: Candidate,
- *,
- allow_disk: bool,
- ) -> Iterator[CandidateSnapshot]:
- snapshot = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO())
- try:
- digest = hashlib.sha256()
- total = 0
- secret_tail = b""
- with open_candidate(candidate) as source:
- while True:
- chunk = source.read(1024 * 1024)
- if not chunk:
- break
- secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative)
- snapshot.write(chunk)
- digest.update(chunk)
- total += len(chunk)
- if total != candidate.size:
- raise PackagingError(f"source size changed during packaging: {candidate.relative}")
- snapshot.seek(0)
- yield CandidateSnapshot(
- stream=snapshot,
- inventory={"path": candidate.relative, "size": total, "sha256": digest.hexdigest()},
- )
- except MemoryError as exc:
- raise PackagingError(f"insufficient memory to audit source file: {candidate.relative}") from exc
- finally:
- snapshot.close()
- def archive_kind(name: str) -> str | None:
- lower = name.casefold()
- if lower.endswith((".zip", ".whl", ".jar", ".apk", ".nupkg")):
- return "zip"
- if lower.endswith((".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".tar")):
- return "tar"
- if lower.endswith(".gz"):
- return "gzip"
- if lower.endswith((".rar", ".7z")):
- return "unsupported"
- return None
- def detect_archive_kind(source: BinaryIO, name: str) -> str | None:
- position = source.tell()
- try:
- source.seek(0)
- prefix = source.read(512)
- source.seek(0)
- if zipfile.is_zipfile(source):
- return "zip"
- hint = archive_kind(name)
- if prefix.startswith((b"7z\xbc\xaf'\x1c", b"Rar!\x1a\x07", b"(\xb5/\xfd", b"\x04\x22\x4d\x18")):
- return "unsupported"
- if prefix.startswith((b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")):
- return "zip"
- if prefix.startswith(b"\x1f\x8b"):
- return "tar" if hint == "tar" else "gzip"
- if prefix.startswith((b"BZh", b"\xfd7zXZ\x00")):
- return "tar"
- if len(prefix) >= 262 and prefix[257:262] == b"ustar":
- return "tar"
- if prefix.startswith((b"!<arch>\n", b"MSCF", b"xar!")):
- return "unsupported"
- return hint
- finally:
- source.seek(position)
- def archive_member_label(archive_label: str, member_name: str) -> str:
- normalized = unicodedata.normalize("NFC", member_name)
- if (
- "\\" in normalized
- or "\x00" in normalized
- or normalized.startswith("/")
- or re.match(r"^[A-Za-z]:", normalized)
- ):
- raise PackagingError(f"unsafe archive member path in {archive_label}")
- normalized = normalized.removesuffix("/")
- if not normalized:
- raise PackagingError(f"unsafe archive member path in {archive_label}")
- parts = normalized.split("/")
- if any(part in {"", ".", ".."} for part in parts):
- raise PackagingError(f"unsafe archive member path in {archive_label}")
- scan_secret_markers(normalized.encode("utf-8"), b"", f"{archive_label} member path")
- return f"{archive_label}!/{normalized}"
- def scan_archive_metadata(value: str | bytes, label: str) -> None:
- try:
- payload = value if isinstance(value, bytes) else value.encode("utf-8", errors="strict")
- except UnicodeError as exc:
- raise PackagingError(f"archive metadata is not valid UTF-8 in {label}") from exc
- scan_secret_markers(payload, b"", label)
- def account_archive_member(budget: ArchiveScanBudget, label: str) -> None:
- budget.member_count += 1
- if budget.member_count > MAX_ARCHIVE_MEMBERS:
- raise PackagingError(f"archive scan resource limit exceeded in {label}")
- def ensure_archive_bytes_available(budget: ArchiveScanBudget, size: int, label: str) -> None:
- if size < 0 or budget.uncompressed_bytes + size > MAX_ARCHIVE_UNCOMPRESSED_BYTES:
- raise PackagingError(f"archive scan resource limit exceeded in {label}")
- def scan_archive_member_stream(
- source: BinaryIO,
- *,
- member_name: str,
- label: str,
- depth: int,
- budget: ArchiveScanBudget,
- allow_disk: bool,
- ) -> None:
- sensitive_reason = secret_path_reason(member_name.removesuffix("/"), is_dir=False)
- if sensitive_reason is not None:
- raise PackagingError(
- f"credential or license path found in archive member: {label} ({sensitive_reason})"
- )
- nested = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO())
- try:
- secret_tail = b""
- while True:
- chunk = source.read(1024 * 1024)
- if not chunk:
- break
- ensure_archive_bytes_available(budget, len(chunk), label)
- budget.uncompressed_bytes += len(chunk)
- secret_tail = scan_secret_markers(chunk, secret_tail, label)
- nested.write(chunk)
- nested.seek(0)
- if detect_archive_kind(nested, member_name) is not None:
- scan_archive_stream(
- nested,
- name=member_name,
- label=label,
- depth=depth + 1,
- budget=budget,
- allow_disk=allow_disk,
- )
- except MemoryError as exc:
- raise PackagingError(f"insufficient memory to audit archive member: {label}") from exc
- finally:
- nested.close()
- def scan_archive_stream(
- source: BinaryIO,
- *,
- name: str,
- label: str,
- depth: int,
- budget: ArchiveScanBudget,
- allow_disk: bool,
- ) -> None:
- kind = detect_archive_kind(source, name)
- if kind is None:
- return
- if kind == "unsupported":
- raise PackagingError(f"unsupported archive format cannot be secret-scanned: {label}")
- if depth > MAX_ARCHIVE_DEPTH:
- raise PackagingError(f"archive scan resource limit exceeded in {label}")
- try:
- if kind == "zip":
- with zipfile.ZipFile(source) as archive:
- scan_archive_metadata(archive.comment, f"{label} archive comment")
- for zip_member in archive.infolist():
- account_archive_member(budget, label)
- member_label = archive_member_label(label, zip_member.filename)
- member_mode = (zip_member.external_attr >> 16) & 0xFFFF
- member_type = stat.S_IFMT(member_mode)
- scan_archive_metadata(zip_member.comment, f"{member_label} comment")
- scan_archive_metadata(zip_member.extra, f"{member_label} extra metadata")
- if zip_member.flag_bits & 0x1:
- raise PackagingError(f"unsafe archive member type in {member_label}")
- if zip_member.is_dir():
- if (
- zip_member.file_size != 0
- or zip_member.compress_size != 0
- or member_type not in {0, stat.S_IFDIR}
- ):
- raise PackagingError(f"unsafe archive member type in {member_label}")
- continue
- if member_type not in {0, stat.S_IFREG}:
- raise PackagingError(f"unsafe archive member type in {member_label}")
- ensure_archive_bytes_available(budget, zip_member.file_size, member_label)
- with archive.open(zip_member, "r") as zip_member_source:
- scan_archive_member_stream(
- cast(BinaryIO, zip_member_source),
- member_name=zip_member.filename,
- label=member_label,
- depth=depth,
- budget=budget,
- allow_disk=allow_disk,
- )
- return
- if kind == "tar":
- with tarfile.open(fileobj=source, mode="r:*") as archive:
- for key, value in archive.pax_headers.items():
- scan_archive_metadata(key, f"{label} global pax key")
- scan_archive_metadata(value, f"{label} global pax value")
- for tar_member in archive:
- account_archive_member(budget, label)
- member_label = archive_member_label(label, tar_member.name)
- for field_name, value in (
- ("linkname", tar_member.linkname),
- ("uname", tar_member.uname),
- ("gname", tar_member.gname),
- ):
- scan_archive_metadata(value, f"{member_label} {field_name}")
- for key, value in tar_member.pax_headers.items():
- scan_archive_metadata(key, f"{member_label} pax key")
- scan_archive_metadata(value, f"{member_label} pax value")
- if tar_member.isdir():
- if tar_member.size != 0:
- raise PackagingError(f"unsafe archive member type in {member_label}")
- continue
- if not tar_member.isfile():
- raise PackagingError(f"unsafe archive member type in {member_label}")
- ensure_archive_bytes_available(budget, tar_member.size, member_label)
- tar_member_source = archive.extractfile(tar_member)
- if tar_member_source is None:
- raise PackagingError(f"unable to inspect archive member in {member_label}")
- with tar_member_source:
- scan_archive_member_stream(
- cast(BinaryIO, tar_member_source),
- member_name=tar_member.name,
- label=member_label,
- depth=depth,
- budget=budget,
- allow_disk=allow_disk,
- )
- return
- with gzip.GzipFile(fileobj=source, mode="rb") as gzip_member_source:
- scan_archive_member_stream(
- cast(BinaryIO, gzip_member_source),
- member_name=name.removesuffix(".gz"),
- label=f"{label}!/<gzip>",
- depth=depth,
- budget=budget,
- allow_disk=allow_disk,
- )
- except PackagingError:
- raise
- except (OSError, EOFError, RuntimeError, tarfile.TarError, zipfile.BadZipFile) as exc:
- raise PackagingError(f"unable to inspect archive safely: {label} ({type(exc).__name__})") from exc
- def scan_candidate_archive(candidate: Candidate) -> None:
- with snapshot_candidate(candidate, allow_disk=True) as snapshot:
- scan_archive_stream(
- snapshot.stream,
- name=candidate.relative,
- label=candidate.relative,
- depth=0,
- budget=ArchiveScanBudget(),
- allow_disk=True,
- )
- def audit_candidates(candidates: Iterable[Candidate]) -> list[dict[str, object]]:
- inventory = []
- for candidate in candidates:
- inventory.append(stream_candidate(candidate))
- return inventory
- def zip_info(name: str, mode: int = stat.S_IFREG | 0o644) -> zipfile.ZipInfo:
- info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
- info.compress_type = zipfile.ZIP_DEFLATED
- info.create_system = 3
- info.external_attr = ((stat.S_IFREG | (mode & 0o777)) & 0xFFFF) << 16
- return info
- def stream_candidate(
- candidate: Candidate,
- target: BinaryIO | None = None,
- *,
- allow_disk: bool = True,
- ) -> dict[str, object]:
- with snapshot_candidate(candidate, allow_disk=allow_disk) as snapshot:
- scan_archive_stream(
- snapshot.stream,
- name=candidate.relative,
- label=candidate.relative,
- depth=0,
- budget=ArchiveScanBudget(),
- allow_disk=allow_disk,
- )
- if target is not None:
- snapshot.stream.seek(0)
- shutil.copyfileobj(snapshot.stream, target, length=1024 * 1024)
- return snapshot.inventory
- def hash_candidate(candidate: Candidate) -> dict[str, object]:
- digest = hashlib.sha256()
- total = 0
- secret_tail = b""
- with open_candidate(candidate) as source:
- for chunk in iter(lambda: source.read(1024 * 1024), b""):
- secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative)
- digest.update(chunk)
- total += len(chunk)
- if total != candidate.size:
- raise PackagingError(f"source size changed during packaging: {candidate.relative}")
- return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
- def write_candidate(archive: zipfile.ZipFile, candidate: Candidate) -> dict[str, object]:
- entry_name = f"{ARCHIVE_ROOT}/{candidate.relative}"
- try:
- with archive.open(zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
- return stream_candidate(candidate, target)
- except OSError as exc:
- raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
- def write_bytes_entry(archive: zipfile.ZipFile, name: str, payload: bytes) -> None:
- scan_secret_markers(payload, b"", name)
- with archive.open(zip_info(name), "w", force_zip64=True) as handle:
- handle.write(payload)
- def json_bytes(payload: object) -> bytes:
- return (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
- def path_contains_reparse_point(root: Path, candidate: Path) -> bool:
- root_absolute = Path(os.path.abspath(root))
- candidate_absolute = Path(os.path.abspath(candidate))
- try:
- relative = candidate_absolute.relative_to(root_absolute)
- except ValueError:
- return True
- current = root_absolute
- for component in relative.parts:
- current /= component
- try:
- file_stat = os.lstat(current)
- except OSError:
- return True
- if stat_is_reparse_point(file_stat):
- return True
- return False
- def resolve_git_dir(root: Path) -> Path | None:
- marker = root / ".git"
- try:
- marker_stat = os.lstat(marker)
- except OSError:
- return None
- if stat_is_reparse_point(marker_stat):
- return None
- root_resolved = root.resolve(strict=True)
- if stat.S_ISDIR(marker_stat.st_mode):
- try:
- candidate = marker.resolve(strict=True)
- candidate.relative_to(root_resolved)
- except (OSError, RuntimeError, ValueError):
- return None
- return candidate
- if stat.S_ISREG(marker_stat.st_mode):
- try:
- text = read_stable_regular_bytes(marker, ".git marker", max_bytes=4096).decode(
- "utf-8",
- errors="strict",
- ).strip()
- except (PackagingError, UnicodeError):
- return None
- if text.startswith("gitdir:"):
- raw_candidate = root / text.split(":", 1)[1].strip()
- try:
- candidate = raw_candidate.resolve(strict=True)
- candidate.relative_to(root_resolved)
- except (OSError, RuntimeError, ValueError):
- return None
- if path_contains_reparse_point(root_resolved, raw_candidate):
- return None
- try:
- candidate_stat = os.lstat(candidate)
- except OSError:
- return None
- return candidate if stat.S_ISDIR(candidate_stat.st_mode) and not stat_is_reparse_point(candidate_stat) else None
- return None
- def read_head_metadata(git_dir: Path) -> tuple[str | None, str | None]:
- try:
- head = read_stable_regular_bytes(git_dir / "HEAD", "Git HEAD", max_bytes=4096).decode(
- "ascii",
- errors="strict",
- ).strip()
- except (PackagingError, UnicodeError):
- return None, None
- if not head.startswith("ref: "):
- return None, head if re.fullmatch(r"[0-9a-fA-F]{40}", head) else None
- ref = head[5:].strip()
- ref_parts = ref.split("/")
- if (
- not ref.startswith("refs/")
- or "\\" in ref
- or any(part in {"", ".", ".."} for part in ref_parts)
- or ".." in ref
- or "@{" in ref
- or ref.endswith((".", "/", ".lock"))
- or re.fullmatch(r"[A-Za-z0-9._/-]+", ref) is None
- ):
- return None, None
- branch = ref.removeprefix("refs/heads/") if ref.startswith("refs/heads/") else ref
- ref_file = git_dir.joinpath(*ref_parts)
- commit: str | None = None
- if os.path.lexists(ref_file):
- if path_contains_reparse_point(git_dir, ref_file):
- return branch, None
- try:
- commit = read_stable_regular_bytes(ref_file, f"Git ref {ref}", max_bytes=4096).decode(
- "ascii",
- errors="strict",
- ).strip()
- except (PackagingError, UnicodeError):
- return branch, None
- if commit is None:
- commit = None
- packed_refs = git_dir / "packed-refs"
- if os.path.lexists(packed_refs) and not path_contains_reparse_point(git_dir, packed_refs):
- try:
- packed_text = read_stable_regular_bytes(
- packed_refs,
- "Git packed-refs",
- max_bytes=16 * 1024 * 1024,
- ).decode("ascii", errors="strict")
- except (PackagingError, UnicodeError):
- packed_text = ""
- for line in packed_text.splitlines():
- if not line or line.startswith(("#", "^")):
- continue
- sha, _, packed_ref = line.partition(" ")
- if packed_ref == ref:
- commit = sha
- break
- if commit and not re.fullmatch(r"[0-9a-fA-F]{40}", commit):
- commit = None
- return branch, commit
- def run_capture(command: list[str], *, cwd: Path, timeout: int = 60) -> tuple[int, bytes]:
- try:
- completed = subprocess.run(
- command,
- cwd=cwd,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- timeout=timeout,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired):
- return 1, b""
- return completed.returncode, completed.stdout
- def collect_git_provenance(root: Path) -> tuple[dict[str, object], dict[str, bytes]]:
- git_dir = resolve_git_dir(root)
- if git_dir is None:
- return {"status": "not_a_git_worktree", "branch": None, "head": None, "tool": None}, {}
- branch, head = read_head_metadata(git_dir)
- tool: str | None = None
- status_command: list[str] | None = None
- git = shutil.which("git")
- if git:
- tool = "git"
- status_command = [
- git,
- "--no-optional-locks",
- "-c",
- "core.fsmonitor=false",
- "-c",
- "core.untrackedCache=false",
- "status",
- "--short",
- "--branch",
- "--untracked-files=all",
- ]
- elif importlib.util.find_spec("dulwich") is not None:
- tool = "dulwich"
- status_command = [sys.executable, "-I", "-m", "dulwich", "status"]
- if status_command is None:
- return {"status": "blocked_missing_git_tool", "branch": branch, "head": head, "tool": None}, {}
- status_code, status_payload = run_capture(status_command, cwd=root)
- artifacts: dict[str, bytes] = {}
- if status_code == 0:
- artifacts[f"{METADATA_ROOT}/git-status.txt"] = status_payload
- capture_status = "pass" if status_code == 0 else "partial"
- return {
- "status": capture_status,
- "branch": branch,
- "head": head,
- "tool": tool,
- "status_captured": status_code == 0,
- }, artifacts
- def build_metadata(
- *,
- package_name: str,
- inventory: list[dict[str, object]],
- excluded: list[dict[str, str]],
- context: ScanContext,
- provenance: dict[str, object],
- ) -> dict[str, bytes]:
- rule_counts = Counter(item["rule"] for item in excluded)
- manifest = {
- "schema": "cpld-agent-handoff-v1",
- "status": "pass",
- "created_at": utc_now(),
- "package_name": package_name,
- "archive_root": ARCHIVE_ROOT,
- "source_name": ARCHIVE_ROOT,
- "included_file_count": len(inventory),
- "included_bytes": sum(int(item["size"]) for item in inventory),
- "excluded_entry_count": len(excluded),
- "exclusion_rule_counts": dict(sorted(rule_counts.items())),
- "changxin_temp_uart_version": context.changxin_version,
- "git_provenance": provenance,
- "archive_scan_limits": {
- "max_depth": MAX_ARCHIVE_DEPTH,
- "max_members": MAX_ARCHIVE_MEMBERS,
- "max_uncompressed_bytes": MAX_ARCHIVE_UNCOMPRESSED_BYTES,
- "source_file_size_limit": None,
- },
- "privacy": {
- "manifest_contains_absolute_source_path": False,
- "note": "Repository files are preserved byte-for-byte; review document and receipt contents before crossing a trust boundary.",
- },
- "authority_boundary": (
- "This archive is an analysis handoff of source, requirements, tests, original references, and retained evidence. "
- "It excludes credentials, private archives, raw Git objects, and declared reconstructable runtime outputs."
- ),
- }
- exclusions_payload = {
- "schema": "cpld-agent-handoff-exclusions-v1",
- "excluded": excluded,
- "rule_counts": dict(sorted(rule_counts.items())),
- }
- inventory_payload = {
- "schema": "cpld-agent-handoff-sha256-inventory-v1",
- "inventory": inventory,
- }
- return {
- f"{METADATA_ROOT}/manifest.json": json_bytes(manifest),
- f"{METADATA_ROOT}/exclusions.json": json_bytes(exclusions_payload),
- f"{METADATA_ROOT}/sha256-inventory.json": json_bytes(inventory_payload),
- }
- def validate_zip_entry(name: str) -> str:
- if not name.startswith(ARCHIVE_ROOT + "/") or "\\" in name or name.startswith("/"):
- raise PackagingError(f"unsafe ZIP entry: {name}")
- relative = name[len(ARCHIVE_ROOT) + 1 :]
- normalize_relative(relative.split("/"))
- return windows_collision_key(name)
- def verify_archive(
- path: Path | BinaryIO,
- *,
- expected_names: set[str],
- inventory: list[dict[str, object]],
- expected_payloads: dict[str, bytes] | None = None,
- ) -> None:
- try:
- with zipfile.ZipFile(path, "r", allowZip64=True) as archive:
- names = archive.namelist()
- if len(names) != len(set(names)):
- raise PackagingError("ZIP contains duplicate entry names")
- collision_keys: dict[str, str] = {}
- for name in names:
- key = validate_zip_entry(name)
- previous = collision_keys.get(key)
- if previous is not None and previous != name:
- raise PackagingError(f"ZIP contains a Windows path collision: {previous} and {name}")
- collision_keys[key] = name
- if set(names) != expected_names:
- missing = sorted(expected_names - set(names))
- unexpected = sorted(set(names) - expected_names)
- raise PackagingError(f"ZIP entry verification failed; missing={missing}, unexpected={unexpected}")
- bad = archive.testzip()
- if bad is not None:
- raise PackagingError(f"ZIP CRC verification failed for {bad}")
- for item in inventory:
- entry_name = f"{ARCHIVE_ROOT}/{item['path']}"
- digest = hashlib.sha256()
- total = 0
- with archive.open(entry_name, "r") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- total += len(chunk)
- if total != item["size"] or digest.hexdigest() != item["sha256"]:
- raise PackagingError(f"ZIP SHA256 verification failed for {item['path']}")
- for name, expected_payload in (expected_payloads or {}).items():
- if archive.read(name) != expected_payload:
- raise PackagingError(f"ZIP generated metadata verification failed for {name}")
- except (OSError, zipfile.BadZipFile) as exc:
- raise PackagingError(f"unable to verify ZIP archive: {exc}") from exc
- def publish_target_identity(file_stat: os.stat_result) -> tuple[int, int, int, int, int]:
- return (
- int(file_stat.st_dev),
- int(file_stat.st_ino),
- int(file_stat.st_mode),
- int(file_stat.st_size),
- int(file_stat.st_mtime_ns),
- )
- def stat_is_windows_read_only(file_stat: os.stat_result) -> bool:
- attributes = int(getattr(file_stat, "st_file_attributes", 0))
- read_only_flag = int(getattr(stat, "FILE_ATTRIBUTE_READONLY", 0))
- return bool(read_only_flag and attributes & read_only_flag)
- def stat_is_read_only(file_stat: os.stat_result) -> bool:
- return stat_is_windows_read_only(file_stat) or (int(file_stat.st_mode) & 0o222) == 0
- def validate_publish_targets(paths: Iterable[Path], *, force: bool) -> dict[Path, tuple[int, int, int, int, int]]:
- existing: dict[Path, tuple[int, int, int, int, int]] = {}
- for path in paths:
- if not os.path.lexists(path):
- continue
- if not force:
- raise PackagingError(f"package artifact already exists: {path.name}")
- try:
- file_stat = os.lstat(path)
- except OSError as exc:
- raise PackagingError(f"unable to inspect existing package artifact {path.name}: {exc}") from exc
- if not stat.S_ISREG(file_stat.st_mode) or stat_is_reparse_point(file_stat):
- raise PackagingError(f"existing package artifact is not a regular file: {path.name}")
- if stat_is_read_only(file_stat):
- raise PackagingError(f"existing package artifact is read-only: {path.name}")
- existing[path] = publish_target_identity(file_stat)
- return existing
- def publish_artifacts_atomically(
- artifacts: list[tuple[Path, Path]],
- *,
- force: bool,
- verify_published: Callable[[], None] | None = None,
- ) -> list[str]:
- backups: dict[Path, Path] = {}
- published: list[Path] = []
- final_paths = [final_path for _, final_path in artifacts]
- existing = validate_publish_targets(final_paths, force=force)
- try:
- for _, final_path in artifacts:
- expected_identity = existing.get(final_path)
- if expected_identity is not None:
- try:
- current = os.lstat(final_path)
- except OSError as exc:
- raise PackagingError(f"existing package artifact changed before publication: {final_path.name}") from exc
- if (
- not stat.S_ISREG(current.st_mode)
- or stat_is_reparse_point(current)
- or stat_is_read_only(current)
- or publish_target_identity(current) != expected_identity
- ):
- raise PackagingError(f"existing package artifact changed before publication: {final_path.name}")
- backup = final_path.with_name(f".{final_path.name}.{uuid.uuid4().hex}.backup")
- os.replace(final_path, backup)
- backups[final_path] = backup
- elif os.path.lexists(final_path):
- raise PackagingError(f"package artifact appeared during publication: {final_path.name}")
- for temp_path, final_path in artifacts:
- os.link(temp_path, final_path)
- published.append(final_path)
- if verify_published is not None:
- verify_published()
- except BaseException as exc:
- rollback_errors: list[str] = []
- for final_path in reversed(published):
- if final_path in backups:
- continue
- try:
- final_path.unlink(missing_ok=True)
- except OSError as rollback_exc:
- rollback_errors.append(
- f"remove {final_path.name} ({type(rollback_exc).__name__})"
- )
- for final_path, backup in backups.items():
- if os.path.lexists(backup):
- try:
- os.replace(backup, final_path)
- except OSError as rollback_exc:
- rollback_errors.append(
- f"restore {final_path.name} from {backup.name} ({type(rollback_exc).__name__})"
- )
- if rollback_errors:
- recovery_paths = sorted(
- str(path)
- for path in (*backups.values(), *published)
- if os.path.lexists(path)
- )
- recovery = ", ".join(recovery_paths) if recovery_paths else "none"
- details = "; ".join(rollback_errors)
- raise PackagingError(
- f"package publication failed and rollback was incomplete: {details}; "
- f"manual recovery paths: {recovery}"
- ) from exc
- if isinstance(exc, PackagingError):
- raise
- if isinstance(exc, OSError):
- raise PackagingError(f"unable to publish package artifacts atomically: {exc}") from exc
- raise
- cleanup_warnings: list[str] = []
- for temp_path, _ in artifacts:
- try:
- temp_path.unlink(missing_ok=True)
- except OSError as exc:
- cleanup_warnings.append(
- f"published temporary artifact could not be removed: {temp_path.name} ({type(exc).__name__})"
- )
- for backup in backups.values():
- try:
- backup.unlink(missing_ok=True)
- except OSError as exc:
- cleanup_warnings.append(
- f"published artifact backup could not be removed: {backup.name} ({type(exc).__name__})"
- )
- return cleanup_warnings
- def remove_partial_artifacts(paths: Iterable[Path]) -> None:
- failures: list[str] = []
- for path in paths:
- try:
- path.unlink(missing_ok=True)
- except OSError:
- failures.append(path.name)
- if failures:
- names = ", ".join(sorted(failures))
- raise PackagingError(f"unable to remove partial package artifacts: {names}")
- @contextmanager
- def open_stable_regular_file(path: Path, label: str) -> Iterator[BinaryIO]:
- try:
- before = os.lstat(path)
- except OSError as exc:
- raise PackagingError(f"unable to inspect {label}: {exc}") from exc
- if not stat.S_ISREG(before.st_mode) or stat_is_reparse_point(before):
- raise PackagingError(f"published artifact is not a regular file: {label}")
- flags = os.O_RDONLY
- flags |= int(getattr(os, "O_BINARY", 0))
- flags |= int(getattr(os, "O_NOINHERIT", 0))
- flags |= int(getattr(os, "O_NOFOLLOW", 0))
- try:
- descriptor = os.open(path, flags)
- except OSError as exc:
- raise PackagingError(f"unable to open {label} without following links: {exc}") from exc
- handle: BinaryIO | None = None
- try:
- opened = os.fstat(descriptor)
- if publish_target_identity(opened) != publish_target_identity(before):
- raise PackagingError(f"published artifact changed while opening: {label}")
- handle = os.fdopen(descriptor, "rb", closefd=True)
- descriptor = -1
- yield handle
- opened_after = os.fstat(handle.fileno())
- if publish_target_identity(opened_after) != publish_target_identity(opened):
- raise PackagingError(f"published artifact changed while reading: {label}")
- finally:
- if handle is not None:
- handle.close()
- if descriptor >= 0:
- os.close(descriptor)
- try:
- after = os.lstat(path)
- except OSError as exc:
- raise PackagingError(f"unable to re-inspect {label}: {exc}") from exc
- if publish_target_identity(after) != publish_target_identity(before):
- raise PackagingError(f"published artifact changed during verification: {label}")
- def read_stable_regular_bytes(path: Path, label: str, *, max_bytes: int) -> bytes:
- with open_stable_regular_file(path, label) as handle:
- payload = handle.read(max_bytes + 1)
- if len(payload) > max_bytes:
- raise PackagingError(f"regular file exceeds safe metadata read limit: {label}")
- return payload
- def verify_published_artifacts(
- final_zip: Path,
- final_sidecar: Path,
- *,
- expected_zip_sha256: str,
- expected_sidecar: bytes,
- expected_names: set[str],
- inventory: list[dict[str, object]],
- expected_payloads: dict[str, bytes],
- ) -> None:
- digest = hashlib.sha256()
- with open_stable_regular_file(final_zip, final_zip.name) as handle:
- verify_archive(
- handle,
- expected_names=expected_names,
- inventory=inventory,
- expected_payloads=expected_payloads,
- )
- handle.seek(0)
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- if digest.hexdigest() != expected_zip_sha256:
- raise PackagingError("published ZIP SHA256 does not match the verified package")
- with open_stable_regular_file(final_sidecar, final_sidecar.name) as handle:
- actual_sidecar = handle.read()
- if actual_sidecar != expected_sidecar:
- raise PackagingError("published SHA256 sidecar does not match the verified package")
- def scan_snapshot(
- candidates: Iterable[Candidate],
- excluded: Iterable[dict[str, str]],
- context: ScanContext,
- ) -> tuple[tuple[tuple[object, ...], ...], tuple[tuple[str, str], ...], ScanContext]:
- candidate_state = tuple(
- (
- item.relative,
- item.size,
- item.mtime_ns,
- item.device,
- item.inode,
- item.mode,
- )
- for item in candidates
- )
- excluded_state = tuple((item["path"], item["rule"]) for item in excluded)
- return candidate_state, excluded_state, context
- def assert_source_tree_unchanged(
- root: Path,
- candidates: list[Candidate],
- excluded: list[dict[str, str]],
- context: ScanContext,
- inventory: list[dict[str, object]],
- ) -> None:
- current_candidates, current_excluded, current_context = scan_tree(root)
- if scan_snapshot(candidates, excluded, context) != scan_snapshot(
- current_candidates,
- current_excluded,
- current_context,
- ):
- raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
- expected_by_path = {str(item["path"]): item for item in inventory}
- if len(expected_by_path) != len(current_candidates):
- raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
- for candidate in current_candidates:
- current = hash_candidate(candidate)
- expected = expected_by_path.get(candidate.relative)
- if (
- expected is None
- or current["size"] != expected["size"]
- or current["sha256"] != expected["sha256"]
- ):
- raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
- def create_package(
- *,
- root: Path,
- output_dir: Path,
- package_name: str,
- force: bool,
- candidates: list[Candidate],
- excluded: list[dict[str, str]],
- context: ScanContext,
- ) -> dict[str, object]:
- output_dir.mkdir(parents=True, exist_ok=True)
- final_zip = output_dir / f"{package_name}.zip"
- final_sidecar = output_dir / f"{package_name}.zip.sha256.txt"
- validate_publish_targets((final_zip, final_sidecar), force=force)
- token = f"{os.getpid()}.{uuid.uuid4().hex}"
- temp_zip = output_dir / f".{package_name}.{token}.partial"
- temp_sidecar = output_dir / f".{package_name}.{token}.sha256.partial"
- inventory: list[dict[str, object]] = []
- provenance, provenance_artifacts = collect_git_provenance(root)
- metadata_artifacts: dict[str, bytes] = {}
- try:
- with zipfile.ZipFile(
- temp_zip,
- "x",
- compression=zipfile.ZIP_DEFLATED,
- compresslevel=6,
- allowZip64=True,
- strict_timestamps=False,
- ) as archive:
- for candidate in candidates:
- inventory.append(write_candidate(archive, candidate))
- metadata_artifacts = build_metadata(
- package_name=package_name,
- inventory=inventory,
- excluded=excluded,
- context=context,
- provenance=provenance,
- )
- for name, payload in sorted({**metadata_artifacts, **provenance_artifacts}.items()):
- write_bytes_entry(archive, name, payload)
- expected_names = {f"{ARCHIVE_ROOT}/{item['path']}" for item in inventory}
- expected_names.update(metadata_artifacts)
- expected_names.update(provenance_artifacts)
- expected_payloads = {**metadata_artifacts, **provenance_artifacts}
- try:
- with open_stable_regular_file(temp_zip, temp_zip.name) as verified_zip:
- verify_archive(
- verified_zip,
- expected_names=expected_names,
- inventory=inventory,
- expected_payloads=expected_payloads,
- )
- verified_zip.seek(0)
- zip_digest = hashlib.sha256()
- for chunk in iter(lambda: verified_zip.read(1024 * 1024), b""):
- zip_digest.update(chunk)
- zip_sha256 = zip_digest.hexdigest()
- except OSError as exc:
- raise PackagingError("temporary ZIP changed during stable verification") from exc
- assert_source_tree_unchanged(root, candidates, excluded, context, inventory)
- sidecar_payload = f"{zip_sha256} {final_zip.name}\n".encode("ascii")
- temp_sidecar.write_bytes(sidecar_payload)
- def verify_publication() -> None:
- verify_published_artifacts(
- final_zip,
- final_sidecar,
- expected_zip_sha256=zip_sha256,
- expected_sidecar=sidecar_payload,
- expected_names=expected_names,
- inventory=inventory,
- expected_payloads=expected_payloads,
- )
- assert_source_tree_unchanged(root, candidates, excluded, context, inventory)
- cleanup_warnings = publish_artifacts_atomically(
- [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
- force=force,
- verify_published=verify_publication,
- )
- except BaseException as exc:
- try:
- remove_partial_artifacts((temp_zip, temp_sidecar))
- except PackagingError as cleanup_exc:
- raise PackagingError(f"{exc}; additionally, {cleanup_exc}") from exc
- raise
- return {
- "status": "pass",
- "mode": "package",
- "package_name": package_name,
- "package_zip": str(final_zip),
- "package_zip_sha256": zip_sha256,
- "sha256_sidecar": str(final_sidecar),
- "included_file_count": len(inventory),
- "included_bytes": sum(int(item["size"]) for item in inventory),
- "excluded_entry_count": len(excluded),
- "warnings": cleanup_warnings,
- }
- def validate_paths(source_root: Path, output_dir: Path) -> tuple[Path, Path]:
- try:
- source = source_root.expanduser().resolve(strict=True)
- except OSError as exc:
- raise PackagingError(f"SourceRoot is unavailable: {source_root}") from exc
- if not source.is_dir():
- raise PackagingError(f"SourceRoot is not a directory: {source_root}")
- output = output_dir.expanduser().resolve(strict=False)
- try:
- output.relative_to(source)
- except ValueError:
- pass
- else:
- raise PackagingError("OutputDir must be outside SourceRoot to prevent recursive packaging")
- return source, output
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--source-root", type=Path, default=ROOT)
- parser.add_argument(
- "--output-dir",
- type=Path,
- default=Path.home() / "Downloads" / "CPLD-agent-handoff",
- )
- parser.add_argument("--package-name")
- parser.add_argument("--force-overwrite", action="store_true")
- parser.add_argument("--audit-only", action="store_true")
- return parser
- def main(argv: list[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- package_name = args.package_name or datetime.now(timezone.utc).strftime("cpld-agent-handoff-%Y%m%dT%H%M%SZ")
- try:
- portable_package_name = windows_collision_key(package_name)
- except PackagingError:
- portable_package_name = ""
- if (
- not SAFE_PACKAGE_NAME.fullmatch(package_name)
- or package_name in {".", ".."}
- or not portable_package_name
- ):
- print(
- "error: PackageName must be a portable ASCII file name without path separators or Windows-reserved forms",
- file=sys.stderr,
- )
- return 1
- try:
- source, output = validate_paths(args.source_root, args.output_dir)
- candidates, excluded, context = scan_tree(source)
- if args.audit_only:
- audit_inventory = audit_candidates(candidates)
- assert_source_tree_unchanged(source, candidates, excluded, context, audit_inventory)
- rule_counts = Counter(item["rule"] for item in excluded)
- payload = {
- "status": "pass",
- "mode": "audit_only",
- "package_name": package_name,
- "included_file_count": len(candidates),
- "included_bytes": sum(item.size for item in candidates),
- "excluded_entry_count": len(excluded),
- "exclusion_rule_counts": dict(sorted(rule_counts.items())),
- "changxin_temp_uart_version": context.changxin_version,
- }
- else:
- payload = create_package(
- root=source,
- output_dir=output,
- package_name=package_name,
- force=args.force_overwrite,
- candidates=candidates,
- excluded=excluded,
- context=context,
- )
- except (PackagingError, OSError) as exc:
- print(f"error: {exc}", file=sys.stderr)
- return 1
- print(json.dumps(payload, ensure_ascii=False, indent=2))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|