package_delivery.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #!/usr/bin/env python3
  2. """Package committed source and collected evidence; never invent verification results."""
  3. from __future__ import annotations
  4. import argparse
  5. from datetime import datetime, timezone
  6. import hashlib
  7. import io
  8. import json
  9. import os
  10. from pathlib import Path
  11. import re
  12. import subprocess
  13. import tarfile
  14. import zipfile
  15. ROOT = Path(__file__).resolve().parents[1]
  16. def git(*args: str) -> str:
  17. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  18. def private_path(path: str) -> bool:
  19. """Exclude runtime credentials and private keys, keeping empty example templates."""
  20. name = Path(path).name.lower()
  21. if name.endswith(".example"):
  22. return False
  23. return (name == ".env" or name.startswith(".env.") or name.endswith(".env")
  24. or name.endswith((".local.env", ".key", ".pem", ".p12", ".pfx"))
  25. or name in {"id_rsa", "id_ed25519", "id_ecdsa"})
  26. def file_hash(path: Path) -> str:
  27. digest = hashlib.sha256()
  28. with path.open("rb") as stream:
  29. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  30. digest.update(chunk)
  31. return digest.hexdigest()
  32. def write_archive(path: Path, files, metadata: dict, secrets: list[bytes]) -> dict:
  33. """Hash the actual archived bytes, including ignored raw evidence files."""
  34. entries = []
  35. overlap = max((len(value) for value in secrets), default=1) - 1
  36. try:
  37. with zipfile.ZipFile(path, "x", zipfile.ZIP_DEFLATED) as archive:
  38. for name, source, mode in files:
  39. digest, size, tail = hashlib.sha256(), 0, b""
  40. stream = io.BytesIO(source) if isinstance(source, bytes) else source.open("rb")
  41. entry = zipfile.ZipInfo(name)
  42. entry.create_system = 3
  43. entry.external_attr = (0o100000 | mode) << 16
  44. entry.compress_type = zipfile.ZIP_DEFLATED
  45. with stream, archive.open(entry, "w") as output:
  46. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  47. scanned = tail + chunk
  48. if any(value in scanned for value in secrets):
  49. raise ValueError(f"Runtime credential found in {name}; archive not retained")
  50. tail = scanned[-overlap:] if overlap else b""
  51. digest.update(chunk)
  52. size += len(chunk)
  53. output.write(chunk)
  54. entries.append({"path": name, "bytes": size, "sha256": digest.hexdigest()})
  55. manifest = {**metadata, "file_count": len(entries), "files": entries}
  56. archive.writestr("MANIFEST.json", json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
  57. archive.writestr("SHA256SUMS", "".join(f"{e['sha256']} {e['path']}\n" for e in entries))
  58. except FileExistsError:
  59. raise
  60. except Exception:
  61. path.unlink(missing_ok=True)
  62. raise
  63. return {"path": str(path), "file": path.name, "bytes": path.stat().st_size,
  64. "sha256": file_hash(path), "kind": metadata["archive_type"]}
  65. def source_files() -> list[tuple[str, bytes, int]]:
  66. data = subprocess.check_output(["git", "archive", "--format=tar", "HEAD"], cwd=ROOT)
  67. files = []
  68. with tarfile.open(fileobj=io.BytesIO(data)) as archive:
  69. for item in archive:
  70. if item.isdir():
  71. continue
  72. if not item.isfile():
  73. raise ValueError(f"Unexpected non-file in source tree: {item.name}")
  74. if private_path(item.name):
  75. raise ValueError(f"Remove tracked runtime credentials before release: {item.name}")
  76. files.append(("source/" + item.name, archive.extractfile(item).read(),
  77. 0o755 if item.mode & 0o111 else 0o644))
  78. return files
  79. def evidence_files(data_dir: Path, extra_dirs: list[Path]):
  80. roots = [ROOT / "docs/hardware-evidence", data_dir / "evidence",
  81. data_dir / "runs", data_dir / "artifacts", *extra_dirs]
  82. files, skipped, seen = [], [], set()
  83. for index, folder in enumerate(roots):
  84. if not folder.is_dir():
  85. continue
  86. try:
  87. prefix = folder.relative_to(ROOT).as_posix()
  88. except ValueError:
  89. prefix = f"external-{index}/{folder.name}"
  90. for path in sorted(folder.rglob("*")):
  91. if path.is_dir():
  92. continue
  93. name = prefix + "/" + path.relative_to(folder).as_posix()
  94. if path.is_symlink() or private_path(name):
  95. skipped.append(name)
  96. continue
  97. if not path.is_file() or path.resolve() in seen:
  98. continue
  99. seen.add(path.resolve())
  100. files.append(("evidence/" + name, path, 0o644))
  101. for path in sorted(data_dir.glob("*.log")):
  102. if path.is_file() and not path.is_symlink() and path.resolve() not in seen:
  103. files.append(("evidence/data/" + path.name, path, 0o644))
  104. return files, skipped
  105. def main() -> None:
  106. parser = argparse.ArgumentParser(description=__doc__)
  107. parser.add_argument("--output-dir", type=Path, default=ROOT / "dist")
  108. parser.add_argument("--data-dir", type=Path, default=ROOT / "data")
  109. parser.add_argument("--evidence-dir", action="append", type=Path, default=[])
  110. parser.add_argument("--session", help="Session label; defaults to the UTC packaging timestamp")
  111. parser.add_argument("--mode", choices=("hardware", "simulated", "mixed"), default="mixed")
  112. parser.add_argument("--secret-env", action="append", default=[],
  113. help="Also reject file bytes containing the value of this environment variable")
  114. args = parser.parse_args()
  115. try:
  116. if git("branch", "--show-current") != "dev":
  117. raise ValueError("Release from the dev branch")
  118. if git("status", "--porcelain", "--untracked-files=normal"):
  119. raise ValueError("Commit source changes before packaging; ignored data/logs may remain")
  120. commit = git("rev-parse", "HEAD")
  121. version = git("show", "HEAD:VERSION")
  122. if not re.fullmatch(r"\d+\.\d+\.\d+", version):
  123. raise ValueError("Committed VERSION must be X.Y.Z")
  124. now = datetime.now(timezone.utc)
  125. stamp = now.strftime("%Y%m%dT%H%M%SZ")
  126. session = args.session or stamp
  127. if not re.fullmatch(r"[A-Za-z0-9_.-]+", session):
  128. raise ValueError("Use letters, digits, dot, dash or underscore in the session label")
  129. secret_names = [f"STL_BMC_S{i}_PASSWORD" for i in range(1, 5)] + args.secret_env
  130. secrets = [os.environ[name].encode() for name in secret_names if os.environ.get(name)]
  131. metadata = {
  132. "version": version, "commit": commit, "branch": "dev",
  133. "tag": f"v{version}" if f"v{version}" in git("tag", "--points-at", "HEAD").splitlines() else None,
  134. "working_tree_dirty": False, "created_utc": now.isoformat(), "session": session,
  135. "mode": args.mode, "verification": "See the included review and raw evidence; packaging does not verify hardware",
  136. "push_status": "pending_push" if not git("remote") else "not_checked",
  137. "windows_transfer": "not_performed_by_this_script",
  138. "history_bundle": "omitted; earlier history contains runtime credentials",
  139. }
  140. source = source_files()
  141. source = [item for item in source if item[0] != "source/COMMIT"]
  142. source.extend([("source/COMMIT", (commit + "\n").encode(), 0o644),
  143. ("COMMIT", (commit + "\n").encode(), 0o644)])
  144. debug, skipped = evidence_files(args.data_dir.resolve(), [p.resolve() for p in args.evidence_dir])
  145. args.output_dir.mkdir(parents=True, exist_ok=True)
  146. prefix = f"xjkj-stl-v{version}-{commit[:7]}-{stamp}"
  147. archives = [write_archive(args.output_dir / f"{prefix}-source-analysis.zip", source,
  148. {**metadata, "archive_type": "source_and_analysis"}, secrets),
  149. write_archive(args.output_dir / f"{prefix}-{session}-debug-logs.zip", debug,
  150. {**metadata, "archive_type": "raw_debug_logs", "skipped_files": skipped}, secrets)]
  151. summary = {**metadata, "archives": archives}
  152. receipt = args.output_dir / f"{prefix}-delivery.json"
  153. receipt.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  154. print(json.dumps({**summary, "receipt": str(receipt)}, ensure_ascii=False, indent=2))
  155. except (OSError, ValueError, subprocess.CalledProcessError) as exc:
  156. parser.exit(1, f"Packaging failed: {exc}\n")
  157. if __name__ == "__main__":
  158. main()