build_onesend_carrier.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. #!/usr/bin/env python3
  2. """Build a ONE-send dual carrier ZIP with exact SHA256SUMS membership.
  3. The outer carrier is a flat upload ZIP. It is NOT a canonical review package.
  4. SHA256SUMS (no .txt) is generated last from the actual ordinary files in a
  5. fresh staging directory, then the ZIP is round-trip verified fail-closed:
  6. - every SHA256SUMS entry exists in the ZIP
  7. - every ordinary ZIP member except SHA256SUMS is listed
  8. - no duplicates, no leftover partials / chatgpt aliases / short-name aliases
  9. - ``unzip -t`` and ``sha256sum -c SHA256SUMS`` both pass
  10. Never zip a dirty handoff folder in place.
  11. """
  12. from __future__ import annotations
  13. import argparse
  14. import hashlib
  15. import json
  16. import os
  17. import shutil
  18. import subprocess
  19. import sys
  20. import tempfile
  21. import zipfile
  22. from datetime import datetime, timezone
  23. from pathlib import Path
  24. from typing import Any, Iterable
  25. SUMS_BASENAME = "SHA256SUMS"
  26. SUMS_ALIASES = frozenset({"SHA256SUMS", "SHA256SUMS.txt", "SHA256SUMS.partial"})
  27. CANONICAL_TOPIC = "mse-a1"
  28. DEPRECATED_TOPICS = ("door-percent",)
  29. class OnesendCarrierError(RuntimeError):
  30. """Raised when the ONE-send carrier cannot be produced safely."""
  31. def sha256_file(path: Path) -> str:
  32. digest = hashlib.sha256()
  33. with path.open("rb") as handle:
  34. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  35. digest.update(chunk)
  36. return digest.hexdigest()
  37. def is_partial_name(name: str) -> bool:
  38. folded = name.casefold()
  39. return folded.endswith(".partial") or ".partial." in folded
  40. def is_chatgpt_alias_name(name: str) -> bool:
  41. return "chatgpt" in name.casefold()
  42. def is_sums_name(name: str) -> bool:
  43. return name.casefold() in {item.casefold() for item in SUMS_ALIASES}
  44. _SIDECAR_SUFFIXES = (".sha256",)
  45. def _mse_a1_insertions(name: str) -> list[str]:
  46. parts = name.split("-")
  47. inserted = [
  48. "-".join([*parts[:index], CANONICAL_TOPIC, *parts[index:]])
  49. for index in range(1, len(parts))
  50. ]
  51. for topic in DEPRECATED_TOPICS:
  52. if topic in name:
  53. inserted.append(name.replace(topic, CANONICAL_TOPIC))
  54. return inserted
  55. def canonical_mse_a1_sibling(name: str, present: set[str]) -> str | None:
  56. """Return the mse-a1 canonical sibling if ``name`` is a short/deprecated alias.
  57. Sidecars such as ``prod2u-release-set-<hash>.json.sha256`` are residue when the
  58. canonical ``prod2u-release-set-mse-a1-<hash>.json`` payload exists, even if the
  59. canonical ``.sha256`` sibling is absent.
  60. """
  61. if CANONICAL_TOPIC in name.casefold():
  62. return None
  63. probes = [name]
  64. for suffix in _SIDECAR_SUFFIXES:
  65. if name.endswith(suffix):
  66. probes.append(name[: -len(suffix)])
  67. for probe in probes:
  68. for candidate in _mse_a1_insertions(probe):
  69. if candidate == name:
  70. continue
  71. if candidate in present:
  72. return candidate
  73. if probe != name:
  74. restored = candidate + name[len(probe) :]
  75. if restored in present and restored != name:
  76. return restored
  77. return None
  78. def residue_reason(name: str, present: set[str]) -> str | None:
  79. """Why ``name`` must not be a final carrier member, or None if it may stay."""
  80. if is_partial_name(name):
  81. return "partial"
  82. if is_chatgpt_alias_name(name):
  83. return "chatgpt_alias"
  84. sibling = canonical_mse_a1_sibling(name, present)
  85. if sibling is not None:
  86. return f"short_alias_of:{sibling}"
  87. return None
  88. def parse_sha256sums(text: str) -> tuple[list[str], dict[str, str], list[str]]:
  89. """Parse GNU text-mode SHA256SUMS. Returns (order, digest_by_name, failures)."""
  90. order: list[str] = []
  91. digest_by_name: dict[str, str] = {}
  92. failures: list[str] = []
  93. for raw in text.splitlines():
  94. line = raw.strip()
  95. if not line or line.startswith("#"):
  96. continue
  97. digest, sep, name = line.partition(" ")
  98. if not sep:
  99. digest, sep, name = line.partition(" *")
  100. if len(digest) != 64 or not name or any(ch in name for ch in "/\\"):
  101. failures.append(f"invalid_sha256sums_line:{line}")
  102. continue
  103. if name in digest_by_name:
  104. failures.append(f"sha256sums_duplicate:{name}")
  105. continue
  106. order.append(name)
  107. digest_by_name[name] = digest.casefold()
  108. return order, digest_by_name, failures
  109. def ordinary_file_names(directory: Path) -> list[str]:
  110. names = [
  111. path.name
  112. for path in directory.iterdir()
  113. if path.is_file() and not path.is_symlink()
  114. ]
  115. names.sort(key=str.casefold)
  116. return names
  117. def write_sha256sums(directory: Path) -> Path:
  118. """Write SHA256SUMS covering every ordinary file except SHA256SUMS itself."""
  119. rows: list[tuple[str, str]] = []
  120. for name in ordinary_file_names(directory):
  121. if is_sums_name(name):
  122. continue
  123. path = directory / name
  124. rows.append((sha256_file(path), name))
  125. text = "".join(f"{digest} {name}\n" for digest, name in rows)
  126. out = directory / SUMS_BASENAME
  127. out.write_text(text, encoding="ascii", newline="\n")
  128. return out
  129. def verify_sha256sums_exact(directory: Path) -> list[str]:
  130. """Fail-closed exact membership + hash check for a directory with SHA256SUMS."""
  131. sums_path = directory / SUMS_BASENAME
  132. failures: list[str] = []
  133. if not sums_path.is_file():
  134. return ["missing_sha256sums"]
  135. order, digest_by_name, parse_failures = parse_sha256sums(
  136. sums_path.read_text(encoding="ascii")
  137. )
  138. failures.extend(parse_failures)
  139. listed = set(digest_by_name)
  140. actual = {
  141. name
  142. for name in ordinary_file_names(directory)
  143. if not is_sums_name(name)
  144. }
  145. for name in sorted(listed - actual):
  146. failures.append(f"sha256sums_missing_file:{name}")
  147. for name in sorted(actual - listed):
  148. failures.append(f"sha256sums_unlisted_file:{name}")
  149. if SUMS_BASENAME in listed:
  150. failures.append("sha256sums_lists_itself")
  151. seen_casefold: dict[str, str] = {}
  152. for name in ordinary_file_names(directory):
  153. folded = name.casefold()
  154. if folded in seen_casefold:
  155. failures.append(f"casefold_duplicate:{seen_casefold[folded]}:{name}")
  156. else:
  157. seen_casefold[folded] = name
  158. reason = residue_reason(name, set(ordinary_file_names(directory)))
  159. if reason is not None:
  160. failures.append(f"residue_present:{reason}:{name}")
  161. for name in order:
  162. path = directory / name
  163. if not path.is_file():
  164. continue
  165. if sha256_file(path).casefold() != digest_by_name[name]:
  166. failures.append(f"sha256sums_mismatch:{name}")
  167. return failures
  168. def _run_checked(command: list[str], *, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
  169. completed = subprocess.run(
  170. command,
  171. cwd=cwd,
  172. capture_output=True,
  173. text=True,
  174. check=False,
  175. )
  176. if completed.returncode != 0:
  177. detail = (completed.stdout or "") + (completed.stderr or "")
  178. raise OnesendCarrierError(
  179. f"command failed ({completed.returncode}): {' '.join(command)}: {detail.strip()}"
  180. )
  181. return completed
  182. def _apply_unique_suffix(output_zip: Path, unique_suffix: str | None) -> Path:
  183. if unique_suffix is None:
  184. return output_zip
  185. token = unique_suffix.strip()
  186. if not token:
  187. token = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  188. if token.startswith("-u"):
  189. infix = token
  190. elif token.startswith("u") and len(token) > 1 and token[1].isdigit():
  191. infix = f"-{token}"
  192. else:
  193. infix = f"-u{token}"
  194. if output_zip.suffix.casefold() != ".zip":
  195. raise OnesendCarrierError(f"output must be a .zip path: {output_zip}")
  196. return output_zip.with_name(f"{output_zip.stem}{infix}{output_zip.suffix}")
  197. def _skip_source_name(name: str, *, skip_names: set[str]) -> bool:
  198. if name.startswith("."):
  199. return True
  200. if is_sums_name(name):
  201. return True
  202. if name in skip_names:
  203. return True
  204. return False
  205. def _output_skip_names(*zip_paths: Path) -> set[str]:
  206. names: set[str] = set()
  207. for path in zip_paths:
  208. names.add(path.name)
  209. names.add(f"{path.name}.sha256")
  210. return names
  211. def _intended_members_from_dir(src_dir: Path, *, skip_names: set[str]) -> list[Path]:
  212. src_dir = src_dir.expanduser().resolve(strict=True)
  213. if not src_dir.is_dir():
  214. raise OnesendCarrierError(f"staging source is not a directory: {src_dir}")
  215. present = {
  216. path.name
  217. for path in src_dir.iterdir()
  218. if path.is_file() and not path.is_symlink()
  219. }
  220. members: list[Path] = []
  221. for path in sorted(src_dir.iterdir(), key=lambda item: item.name.casefold()):
  222. if not path.is_file() or path.is_symlink():
  223. continue
  224. if _skip_source_name(path.name, skip_names=skip_names):
  225. continue
  226. if residue_reason(path.name, present) is not None:
  227. continue
  228. members.append(path)
  229. return members
  230. def _reject_partial_members(members: Iterable[Path]) -> None:
  231. for path in members:
  232. if is_partial_name(path.name):
  233. raise OnesendCarrierError(f"refusing partial member: {path.name}")
  234. def _copy_members_to_staging(members: list[Path], staging: Path) -> list[str]:
  235. copied: list[str] = []
  236. seen_casefold: dict[str, str] = {}
  237. for src in members:
  238. src = src.expanduser().resolve(strict=True)
  239. if not src.is_file() or src.is_symlink():
  240. raise OnesendCarrierError(f"member is not an ordinary file: {src}")
  241. if is_partial_name(src.name):
  242. raise OnesendCarrierError(f"refusing partial member: {src.name}")
  243. if is_sums_name(src.name):
  244. continue
  245. folded = src.name.casefold()
  246. if folded in seen_casefold:
  247. raise OnesendCarrierError(
  248. f"duplicate member basename: {seen_casefold[folded]} vs {src.name}"
  249. )
  250. seen_casefold[folded] = src.name
  251. dest = staging / src.name
  252. shutil.copy2(src, dest)
  253. copied.append(src.name)
  254. return copied
  255. def _purge_residue(staging: Path) -> list[str]:
  256. for path in staging.iterdir():
  257. if path.is_dir():
  258. raise OnesendCarrierError(f"staging is not flat: {path.name}")
  259. if path.is_symlink() or not path.is_file():
  260. raise OnesendCarrierError(f"staging contains non-ordinary path: {path.name}")
  261. present = set(ordinary_file_names(staging))
  262. removed: list[str] = []
  263. for name in sorted(present):
  264. path = staging / name
  265. if is_sums_name(name):
  266. path.unlink()
  267. removed.append(name)
  268. continue
  269. if residue_reason(name, present) is not None:
  270. path.unlink()
  271. removed.append(name)
  272. return removed
  273. def _write_zip(staging: Path, output_zip: Path) -> list[str]:
  274. names = ordinary_file_names(staging)
  275. if SUMS_BASENAME not in names:
  276. raise OnesendCarrierError("staging is missing SHA256SUMS before zip")
  277. output_zip.parent.mkdir(parents=True, exist_ok=True)
  278. if output_zip.exists():
  279. output_zip.unlink()
  280. with zipfile.ZipFile(output_zip, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as zf:
  281. for name in names:
  282. if is_partial_name(name):
  283. raise OnesendCarrierError(f"refusing to zip partial residue: {name}")
  284. zf.write(staging / name, arcname=name)
  285. return names
  286. def _verify_zip_roundtrip(output_zip: Path, extract_dir: Path) -> dict[str, Any]:
  287. if any(extract_dir.iterdir()):
  288. raise OnesendCarrierError(f"extract directory is not empty: {extract_dir}")
  289. _run_checked(["unzip", "-t", str(output_zip)])
  290. _run_checked(["unzip", "-o", "-d", str(extract_dir), str(output_zip)])
  291. _run_checked(["sha256sum", "-c", SUMS_BASENAME], cwd=extract_dir)
  292. with zipfile.ZipFile(output_zip, "r") as zf:
  293. zip_names = list(zf.namelist())
  294. if len(zip_names) != len(set(zip_names)):
  295. raise OnesendCarrierError(f"zip has duplicate members: {zip_names}")
  296. bad = zf.testzip()
  297. if bad is not None:
  298. raise OnesendCarrierError(f"zip crc failed: {bad}")
  299. for name in zip_names:
  300. if name != Path(name).name or "/" in name or "\\" in name or name.startswith("/"):
  301. raise OnesendCarrierError(f"zip member is not a flat basename: {name}")
  302. if is_partial_name(name) or is_chatgpt_alias_name(name):
  303. raise OnesendCarrierError(f"zip contains residue: {name}")
  304. extract_names = set(ordinary_file_names(extract_dir))
  305. zip_set = set(zip_names)
  306. if extract_names != zip_set:
  307. raise OnesendCarrierError(
  308. f"extract membership mismatch zip={sorted(zip_set)} extract={sorted(extract_names)}"
  309. )
  310. failures = verify_sha256sums_exact(extract_dir)
  311. if failures:
  312. raise OnesendCarrierError(f"extract SHA256SUMS exact membership failed: {failures}")
  313. listed = {
  314. name
  315. for name in parse_sha256sums((extract_dir / SUMS_BASENAME).read_text(encoding="ascii"))[1]
  316. }
  317. expected = listed | {SUMS_BASENAME}
  318. if zip_set != expected:
  319. raise OnesendCarrierError(
  320. f"zip membership is not listed∪{{SHA256SUMS}}: "
  321. f"zip={sorted(zip_set)} expected={sorted(expected)}"
  322. )
  323. extra = zip_set - expected
  324. missing = expected - zip_set
  325. if extra or missing:
  326. raise OnesendCarrierError(f"exact membership extra={sorted(extra)} missing={sorted(missing)}")
  327. return {
  328. "zip_members": sorted(zip_set, key=str.casefold),
  329. "sha256sums_listed": sorted(listed, key=str.casefold),
  330. }
  331. def build_onesend_carrier(
  332. src_members: list[Path] | Path,
  333. output_zip: Path,
  334. *,
  335. unique_suffix: str | None = None,
  336. ) -> dict[str, Any]:
  337. """Copy intended members into fresh staging, emit SHA256SUMS, zip, round-trip verify."""
  338. requested_zip = Path(output_zip).expanduser()
  339. if requested_zip.suffix.casefold() != ".zip":
  340. raise OnesendCarrierError(f"output must be a .zip path: {requested_zip}")
  341. output_zip = _apply_unique_suffix(requested_zip, unique_suffix).resolve(strict=False)
  342. skip_names = _output_skip_names(requested_zip, output_zip)
  343. directory_mode = False
  344. if isinstance(src_members, (str, os.PathLike)) and not isinstance(src_members, list):
  345. src_path = Path(src_members)
  346. if src_path.is_dir():
  347. members = _intended_members_from_dir(src_path, skip_names=skip_names)
  348. directory_mode = True
  349. else:
  350. raise OnesendCarrierError(f"staging source is not a directory: {src_path}")
  351. else:
  352. members = [Path(path) for path in src_members]
  353. _reject_partial_members(members)
  354. if not members:
  355. raise OnesendCarrierError("no intended final members to pack")
  356. workdir = Path(tempfile.mkdtemp(prefix="prod2u-onesend-"))
  357. staging = workdir / "staging"
  358. extract_dir = workdir / "extract"
  359. staging.mkdir()
  360. extract_dir.mkdir()
  361. if any(staging.iterdir()) or any(extract_dir.iterdir()):
  362. shutil.rmtree(workdir, ignore_errors=True)
  363. raise OnesendCarrierError("staging or extract directory was not empty")
  364. wrote_zip = False
  365. try:
  366. copied = _copy_members_to_staging(members, staging)
  367. removed = _purge_residue(staging)
  368. payload = [name for name in ordinary_file_names(staging) if not is_sums_name(name)]
  369. if not payload:
  370. raise OnesendCarrierError("staging has no payload files after residue purge")
  371. write_sha256sums(staging)
  372. staging_failures = verify_sha256sums_exact(staging)
  373. if staging_failures:
  374. raise OnesendCarrierError(f"staging SHA256SUMS selftest failed: {staging_failures}")
  375. _run_checked(["sha256sum", "-c", SUMS_BASENAME], cwd=staging)
  376. zipped = _write_zip(staging, output_zip)
  377. wrote_zip = True
  378. roundtrip = _verify_zip_roundtrip(output_zip, extract_dir)
  379. report = {
  380. "schema": "prod2u-onesend-carrier-v1",
  381. "status": "pass",
  382. "output_zip": str(output_zip),
  383. "sha256": sha256_file(output_zip),
  384. "size": output_zip.stat().st_size,
  385. "directory_mode": directory_mode,
  386. "copied": sorted(copied, key=str.casefold),
  387. "purged_residue": sorted(removed, key=str.casefold),
  388. "members": roundtrip["zip_members"],
  389. "sha256sums_listed": roundtrip["sha256sums_listed"],
  390. "zipped_from_staging": zipped,
  391. "unique_suffix": unique_suffix,
  392. }
  393. return report
  394. except Exception:
  395. if wrote_zip:
  396. output_zip.unlink(missing_ok=True)
  397. raise
  398. finally:
  399. shutil.rmtree(workdir, ignore_errors=True)
  400. def build_parser() -> argparse.ArgumentParser:
  401. parser = argparse.ArgumentParser(description=__doc__)
  402. source = parser.add_mutually_exclusive_group(required=True)
  403. source.add_argument(
  404. "--staging-src",
  405. type=Path,
  406. help="dirty or clean directory; only intended final members are copied",
  407. )
  408. source.add_argument(
  409. "--member",
  410. action="append",
  411. dest="members",
  412. type=Path,
  413. help="explicit ordinary file to include (repeatable); partials are rejected",
  414. )
  415. parser.add_argument("--output-zip", type=Path, required=True)
  416. parser.add_argument(
  417. "--unique-suffix",
  418. nargs="?",
  419. const="",
  420. default=None,
  421. help="append -u{UTC} (or the given token) to the output zip stem",
  422. )
  423. parser.add_argument("--json-out", type=Path)
  424. return parser
  425. def main(argv: list[str] | None = None) -> int:
  426. args = build_parser().parse_args(argv)
  427. src: list[Path] | Path
  428. if args.staging_src is not None:
  429. src = args.staging_src
  430. else:
  431. src = list(args.members or [])
  432. try:
  433. report = build_onesend_carrier(
  434. src,
  435. args.output_zip,
  436. unique_suffix=args.unique_suffix,
  437. )
  438. except (OnesendCarrierError, FileNotFoundError, OSError) as exc:
  439. sys.stderr.write(f"error: {exc}\n")
  440. return 1
  441. text = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
  442. if args.json_out is not None:
  443. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  444. args.json_out.write_text(text, encoding="utf-8")
  445. sys.stdout.write(text)
  446. return 0
  447. if __name__ == "__main__":
  448. raise SystemExit(main())