| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516 |
- #!/usr/bin/env python3
- """Build a ONE-send dual carrier ZIP with exact SHA256SUMS membership.
- The outer carrier is a flat upload ZIP. It is NOT a canonical review package.
- SHA256SUMS (no .txt) is generated last from the actual ordinary files in a
- fresh staging directory, then the ZIP is round-trip verified fail-closed:
- - every SHA256SUMS entry exists in the ZIP
- - every ordinary ZIP member except SHA256SUMS is listed
- - no duplicates, no leftover partials / chatgpt aliases / short-name aliases
- - ``unzip -t`` and ``sha256sum -c SHA256SUMS`` both pass
- Never zip a dirty handoff folder in place.
- """
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import os
- import shutil
- import subprocess
- import sys
- import tempfile
- import zipfile
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any, Iterable
- SUMS_BASENAME = "SHA256SUMS"
- SUMS_ALIASES = frozenset({"SHA256SUMS", "SHA256SUMS.txt", "SHA256SUMS.partial"})
- CANONICAL_TOPIC = "mse-a1"
- DEPRECATED_TOPICS = ("door-percent",)
- class OnesendCarrierError(RuntimeError):
- """Raised when the ONE-send carrier cannot be produced safely."""
- 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 is_partial_name(name: str) -> bool:
- folded = name.casefold()
- return folded.endswith(".partial") or ".partial." in folded
- def is_chatgpt_alias_name(name: str) -> bool:
- return "chatgpt" in name.casefold()
- def is_sums_name(name: str) -> bool:
- return name.casefold() in {item.casefold() for item in SUMS_ALIASES}
- _SIDECAR_SUFFIXES = (".sha256",)
- def _mse_a1_insertions(name: str) -> list[str]:
- parts = name.split("-")
- inserted = [
- "-".join([*parts[:index], CANONICAL_TOPIC, *parts[index:]])
- for index in range(1, len(parts))
- ]
- for topic in DEPRECATED_TOPICS:
- if topic in name:
- inserted.append(name.replace(topic, CANONICAL_TOPIC))
- return inserted
- def canonical_mse_a1_sibling(name: str, present: set[str]) -> str | None:
- """Return the mse-a1 canonical sibling if ``name`` is a short/deprecated alias.
- Sidecars such as ``prod2u-release-set-<hash>.json.sha256`` are residue when the
- canonical ``prod2u-release-set-mse-a1-<hash>.json`` payload exists, even if the
- canonical ``.sha256`` sibling is absent.
- """
- if CANONICAL_TOPIC in name.casefold():
- return None
- probes = [name]
- for suffix in _SIDECAR_SUFFIXES:
- if name.endswith(suffix):
- probes.append(name[: -len(suffix)])
- for probe in probes:
- for candidate in _mse_a1_insertions(probe):
- if candidate == name:
- continue
- if candidate in present:
- return candidate
- if probe != name:
- restored = candidate + name[len(probe) :]
- if restored in present and restored != name:
- return restored
- return None
- def residue_reason(name: str, present: set[str]) -> str | None:
- """Why ``name`` must not be a final carrier member, or None if it may stay."""
- if is_partial_name(name):
- return "partial"
- if is_chatgpt_alias_name(name):
- return "chatgpt_alias"
- sibling = canonical_mse_a1_sibling(name, present)
- if sibling is not None:
- return f"short_alias_of:{sibling}"
- return None
- def parse_sha256sums(text: str) -> tuple[list[str], dict[str, str], list[str]]:
- """Parse GNU text-mode SHA256SUMS. Returns (order, digest_by_name, failures)."""
- order: list[str] = []
- digest_by_name: dict[str, str] = {}
- failures: list[str] = []
- for raw in text.splitlines():
- line = raw.strip()
- if not line or line.startswith("#"):
- continue
- digest, sep, name = line.partition(" ")
- if not sep:
- digest, sep, name = line.partition(" *")
- if len(digest) != 64 or not name or any(ch in name for ch in "/\\"):
- failures.append(f"invalid_sha256sums_line:{line}")
- continue
- if name in digest_by_name:
- failures.append(f"sha256sums_duplicate:{name}")
- continue
- order.append(name)
- digest_by_name[name] = digest.casefold()
- return order, digest_by_name, failures
- def ordinary_file_names(directory: Path) -> list[str]:
- names = [
- path.name
- for path in directory.iterdir()
- if path.is_file() and not path.is_symlink()
- ]
- names.sort(key=str.casefold)
- return names
- def write_sha256sums(directory: Path) -> Path:
- """Write SHA256SUMS covering every ordinary file except SHA256SUMS itself."""
- rows: list[tuple[str, str]] = []
- for name in ordinary_file_names(directory):
- if is_sums_name(name):
- continue
- path = directory / name
- rows.append((sha256_file(path), name))
- text = "".join(f"{digest} {name}\n" for digest, name in rows)
- out = directory / SUMS_BASENAME
- out.write_text(text, encoding="ascii", newline="\n")
- return out
- def verify_sha256sums_exact(directory: Path) -> list[str]:
- """Fail-closed exact membership + hash check for a directory with SHA256SUMS."""
- sums_path = directory / SUMS_BASENAME
- failures: list[str] = []
- if not sums_path.is_file():
- return ["missing_sha256sums"]
- order, digest_by_name, parse_failures = parse_sha256sums(
- sums_path.read_text(encoding="ascii")
- )
- failures.extend(parse_failures)
- listed = set(digest_by_name)
- actual = {
- name
- for name in ordinary_file_names(directory)
- if not is_sums_name(name)
- }
- for name in sorted(listed - actual):
- failures.append(f"sha256sums_missing_file:{name}")
- for name in sorted(actual - listed):
- failures.append(f"sha256sums_unlisted_file:{name}")
- if SUMS_BASENAME in listed:
- failures.append("sha256sums_lists_itself")
- seen_casefold: dict[str, str] = {}
- for name in ordinary_file_names(directory):
- folded = name.casefold()
- if folded in seen_casefold:
- failures.append(f"casefold_duplicate:{seen_casefold[folded]}:{name}")
- else:
- seen_casefold[folded] = name
- reason = residue_reason(name, set(ordinary_file_names(directory)))
- if reason is not None:
- failures.append(f"residue_present:{reason}:{name}")
- for name in order:
- path = directory / name
- if not path.is_file():
- continue
- if sha256_file(path).casefold() != digest_by_name[name]:
- failures.append(f"sha256sums_mismatch:{name}")
- return failures
- def _run_checked(command: list[str], *, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
- completed = subprocess.run(
- command,
- cwd=cwd,
- capture_output=True,
- text=True,
- check=False,
- )
- if completed.returncode != 0:
- detail = (completed.stdout or "") + (completed.stderr or "")
- raise OnesendCarrierError(
- f"command failed ({completed.returncode}): {' '.join(command)}: {detail.strip()}"
- )
- return completed
- def _apply_unique_suffix(output_zip: Path, unique_suffix: str | None) -> Path:
- if unique_suffix is None:
- return output_zip
- token = unique_suffix.strip()
- if not token:
- token = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- if token.startswith("-u"):
- infix = token
- elif token.startswith("u") and len(token) > 1 and token[1].isdigit():
- infix = f"-{token}"
- else:
- infix = f"-u{token}"
- if output_zip.suffix.casefold() != ".zip":
- raise OnesendCarrierError(f"output must be a .zip path: {output_zip}")
- return output_zip.with_name(f"{output_zip.stem}{infix}{output_zip.suffix}")
- def _skip_source_name(name: str, *, skip_names: set[str]) -> bool:
- if name.startswith("."):
- return True
- if is_sums_name(name):
- return True
- if name in skip_names:
- return True
- return False
- def _output_skip_names(*zip_paths: Path) -> set[str]:
- names: set[str] = set()
- for path in zip_paths:
- names.add(path.name)
- names.add(f"{path.name}.sha256")
- return names
- def _intended_members_from_dir(src_dir: Path, *, skip_names: set[str]) -> list[Path]:
- src_dir = src_dir.expanduser().resolve(strict=True)
- if not src_dir.is_dir():
- raise OnesendCarrierError(f"staging source is not a directory: {src_dir}")
- present = {
- path.name
- for path in src_dir.iterdir()
- if path.is_file() and not path.is_symlink()
- }
- members: list[Path] = []
- for path in sorted(src_dir.iterdir(), key=lambda item: item.name.casefold()):
- if not path.is_file() or path.is_symlink():
- continue
- if _skip_source_name(path.name, skip_names=skip_names):
- continue
- if residue_reason(path.name, present) is not None:
- continue
- members.append(path)
- return members
- def _reject_partial_members(members: Iterable[Path]) -> None:
- for path in members:
- if is_partial_name(path.name):
- raise OnesendCarrierError(f"refusing partial member: {path.name}")
- def _copy_members_to_staging(members: list[Path], staging: Path) -> list[str]:
- copied: list[str] = []
- seen_casefold: dict[str, str] = {}
- for src in members:
- src = src.expanduser().resolve(strict=True)
- if not src.is_file() or src.is_symlink():
- raise OnesendCarrierError(f"member is not an ordinary file: {src}")
- if is_partial_name(src.name):
- raise OnesendCarrierError(f"refusing partial member: {src.name}")
- if is_sums_name(src.name):
- continue
- folded = src.name.casefold()
- if folded in seen_casefold:
- raise OnesendCarrierError(
- f"duplicate member basename: {seen_casefold[folded]} vs {src.name}"
- )
- seen_casefold[folded] = src.name
- dest = staging / src.name
- shutil.copy2(src, dest)
- copied.append(src.name)
- return copied
- def _purge_residue(staging: Path) -> list[str]:
- for path in staging.iterdir():
- if path.is_dir():
- raise OnesendCarrierError(f"staging is not flat: {path.name}")
- if path.is_symlink() or not path.is_file():
- raise OnesendCarrierError(f"staging contains non-ordinary path: {path.name}")
- present = set(ordinary_file_names(staging))
- removed: list[str] = []
- for name in sorted(present):
- path = staging / name
- if is_sums_name(name):
- path.unlink()
- removed.append(name)
- continue
- if residue_reason(name, present) is not None:
- path.unlink()
- removed.append(name)
- return removed
- def _write_zip(staging: Path, output_zip: Path) -> list[str]:
- names = ordinary_file_names(staging)
- if SUMS_BASENAME not in names:
- raise OnesendCarrierError("staging is missing SHA256SUMS before zip")
- output_zip.parent.mkdir(parents=True, exist_ok=True)
- if output_zip.exists():
- output_zip.unlink()
- with zipfile.ZipFile(output_zip, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as zf:
- for name in names:
- if is_partial_name(name):
- raise OnesendCarrierError(f"refusing to zip partial residue: {name}")
- zf.write(staging / name, arcname=name)
- return names
- def _verify_zip_roundtrip(output_zip: Path, extract_dir: Path) -> dict[str, Any]:
- if any(extract_dir.iterdir()):
- raise OnesendCarrierError(f"extract directory is not empty: {extract_dir}")
- _run_checked(["unzip", "-t", str(output_zip)])
- _run_checked(["unzip", "-o", "-d", str(extract_dir), str(output_zip)])
- _run_checked(["sha256sum", "-c", SUMS_BASENAME], cwd=extract_dir)
- with zipfile.ZipFile(output_zip, "r") as zf:
- zip_names = list(zf.namelist())
- if len(zip_names) != len(set(zip_names)):
- raise OnesendCarrierError(f"zip has duplicate members: {zip_names}")
- bad = zf.testzip()
- if bad is not None:
- raise OnesendCarrierError(f"zip crc failed: {bad}")
- for name in zip_names:
- if name != Path(name).name or "/" in name or "\\" in name or name.startswith("/"):
- raise OnesendCarrierError(f"zip member is not a flat basename: {name}")
- if is_partial_name(name) or is_chatgpt_alias_name(name):
- raise OnesendCarrierError(f"zip contains residue: {name}")
- extract_names = set(ordinary_file_names(extract_dir))
- zip_set = set(zip_names)
- if extract_names != zip_set:
- raise OnesendCarrierError(
- f"extract membership mismatch zip={sorted(zip_set)} extract={sorted(extract_names)}"
- )
- failures = verify_sha256sums_exact(extract_dir)
- if failures:
- raise OnesendCarrierError(f"extract SHA256SUMS exact membership failed: {failures}")
- listed = {
- name
- for name in parse_sha256sums((extract_dir / SUMS_BASENAME).read_text(encoding="ascii"))[1]
- }
- expected = listed | {SUMS_BASENAME}
- if zip_set != expected:
- raise OnesendCarrierError(
- f"zip membership is not listed∪{{SHA256SUMS}}: "
- f"zip={sorted(zip_set)} expected={sorted(expected)}"
- )
- extra = zip_set - expected
- missing = expected - zip_set
- if extra or missing:
- raise OnesendCarrierError(f"exact membership extra={sorted(extra)} missing={sorted(missing)}")
- return {
- "zip_members": sorted(zip_set, key=str.casefold),
- "sha256sums_listed": sorted(listed, key=str.casefold),
- }
- def build_onesend_carrier(
- src_members: list[Path] | Path,
- output_zip: Path,
- *,
- unique_suffix: str | None = None,
- ) -> dict[str, Any]:
- """Copy intended members into fresh staging, emit SHA256SUMS, zip, round-trip verify."""
- requested_zip = Path(output_zip).expanduser()
- if requested_zip.suffix.casefold() != ".zip":
- raise OnesendCarrierError(f"output must be a .zip path: {requested_zip}")
- output_zip = _apply_unique_suffix(requested_zip, unique_suffix).resolve(strict=False)
- skip_names = _output_skip_names(requested_zip, output_zip)
- directory_mode = False
- if isinstance(src_members, (str, os.PathLike)) and not isinstance(src_members, list):
- src_path = Path(src_members)
- if src_path.is_dir():
- members = _intended_members_from_dir(src_path, skip_names=skip_names)
- directory_mode = True
- else:
- raise OnesendCarrierError(f"staging source is not a directory: {src_path}")
- else:
- members = [Path(path) for path in src_members]
- _reject_partial_members(members)
- if not members:
- raise OnesendCarrierError("no intended final members to pack")
- workdir = Path(tempfile.mkdtemp(prefix="prod2u-onesend-"))
- staging = workdir / "staging"
- extract_dir = workdir / "extract"
- staging.mkdir()
- extract_dir.mkdir()
- if any(staging.iterdir()) or any(extract_dir.iterdir()):
- shutil.rmtree(workdir, ignore_errors=True)
- raise OnesendCarrierError("staging or extract directory was not empty")
- wrote_zip = False
- try:
- copied = _copy_members_to_staging(members, staging)
- removed = _purge_residue(staging)
- payload = [name for name in ordinary_file_names(staging) if not is_sums_name(name)]
- if not payload:
- raise OnesendCarrierError("staging has no payload files after residue purge")
- write_sha256sums(staging)
- staging_failures = verify_sha256sums_exact(staging)
- if staging_failures:
- raise OnesendCarrierError(f"staging SHA256SUMS selftest failed: {staging_failures}")
- _run_checked(["sha256sum", "-c", SUMS_BASENAME], cwd=staging)
- zipped = _write_zip(staging, output_zip)
- wrote_zip = True
- roundtrip = _verify_zip_roundtrip(output_zip, extract_dir)
- report = {
- "schema": "prod2u-onesend-carrier-v1",
- "status": "pass",
- "output_zip": str(output_zip),
- "sha256": sha256_file(output_zip),
- "size": output_zip.stat().st_size,
- "directory_mode": directory_mode,
- "copied": sorted(copied, key=str.casefold),
- "purged_residue": sorted(removed, key=str.casefold),
- "members": roundtrip["zip_members"],
- "sha256sums_listed": roundtrip["sha256sums_listed"],
- "zipped_from_staging": zipped,
- "unique_suffix": unique_suffix,
- }
- return report
- except Exception:
- if wrote_zip:
- output_zip.unlink(missing_ok=True)
- raise
- finally:
- shutil.rmtree(workdir, ignore_errors=True)
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- source = parser.add_mutually_exclusive_group(required=True)
- source.add_argument(
- "--staging-src",
- type=Path,
- help="dirty or clean directory; only intended final members are copied",
- )
- source.add_argument(
- "--member",
- action="append",
- dest="members",
- type=Path,
- help="explicit ordinary file to include (repeatable); partials are rejected",
- )
- parser.add_argument("--output-zip", type=Path, required=True)
- parser.add_argument(
- "--unique-suffix",
- nargs="?",
- const="",
- default=None,
- help="append -u{UTC} (or the given token) to the output zip stem",
- )
- parser.add_argument("--json-out", type=Path)
- return parser
- def main(argv: list[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- src: list[Path] | Path
- if args.staging_src is not None:
- src = args.staging_src
- else:
- src = list(args.members or [])
- try:
- report = build_onesend_carrier(
- src,
- args.output_zip,
- unique_suffix=args.unique_suffix,
- )
- except (OnesendCarrierError, FileNotFoundError, OSError) as exc:
- sys.stderr.write(f"error: {exc}\n")
- return 1
- text = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
- if args.json_out is not None:
- args.json_out.parent.mkdir(parents=True, exist_ok=True)
- args.json_out.write_text(text, encoding="utf-8")
- sys.stdout.write(text)
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|