| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- #!/usr/bin/env python3
- """Package committed source and collected evidence; never invent verification results."""
- from __future__ import annotations
- import argparse
- from datetime import datetime, timezone
- import hashlib
- import io
- import json
- import os
- from pathlib import Path
- import re
- import subprocess
- import tarfile
- import zipfile
- ROOT = Path(__file__).resolve().parents[1]
- def git(*args: str) -> str:
- return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
- def private_path(path: str) -> bool:
- """Exclude runtime credentials and private keys, keeping empty example templates."""
- name = Path(path).name.lower()
- if name.endswith(".example"):
- return False
- return (name == ".env" or name.startswith(".env.") or name.endswith(".env")
- or name.endswith((".local.env", ".key", ".pem", ".p12", ".pfx"))
- or name in {"id_rsa", "id_ed25519", "id_ecdsa"})
- def file_hash(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as stream:
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def write_archive(path: Path, files, metadata: dict, secrets: list[bytes]) -> dict:
- """Hash the actual archived bytes, including ignored raw evidence files."""
- entries = []
- overlap = max((len(value) for value in secrets), default=1) - 1
- try:
- with zipfile.ZipFile(path, "x", zipfile.ZIP_DEFLATED) as archive:
- for name, source, mode in files:
- digest, size, tail = hashlib.sha256(), 0, b""
- stream = io.BytesIO(source) if isinstance(source, bytes) else source.open("rb")
- entry = zipfile.ZipInfo(name)
- entry.create_system = 3
- entry.external_attr = (0o100000 | mode) << 16
- entry.compress_type = zipfile.ZIP_DEFLATED
- with stream, archive.open(entry, "w") as output:
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
- scanned = tail + chunk
- if any(value in scanned for value in secrets):
- raise ValueError(f"Runtime credential found in {name}; archive not retained")
- tail = scanned[-overlap:] if overlap else b""
- digest.update(chunk)
- size += len(chunk)
- output.write(chunk)
- entries.append({"path": name, "bytes": size, "sha256": digest.hexdigest()})
- manifest = {**metadata, "file_count": len(entries), "files": entries}
- archive.writestr("MANIFEST.json", json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
- archive.writestr("SHA256SUMS", "".join(f"{e['sha256']} {e['path']}\n" for e in entries))
- except FileExistsError:
- raise
- except Exception:
- path.unlink(missing_ok=True)
- raise
- return {"path": str(path), "file": path.name, "bytes": path.stat().st_size,
- "sha256": file_hash(path), "kind": metadata["archive_type"]}
- def source_files() -> list[tuple[str, bytes, int]]:
- data = subprocess.check_output(["git", "archive", "--format=tar", "HEAD"], cwd=ROOT)
- files = []
- with tarfile.open(fileobj=io.BytesIO(data)) as archive:
- for item in archive:
- if item.isdir():
- continue
- if not item.isfile():
- raise ValueError(f"Unexpected non-file in source tree: {item.name}")
- if private_path(item.name):
- raise ValueError(f"Remove tracked runtime credentials before release: {item.name}")
- files.append(("source/" + item.name, archive.extractfile(item).read(),
- 0o755 if item.mode & 0o111 else 0o644))
- return files
- def evidence_files(data_dir: Path, extra_dirs: list[Path]):
- roots = [data_dir / "evidence",
- data_dir / "runs", data_dir / "artifacts", data_dir / "diagnostics", *extra_dirs]
- files, skipped, seen = [], [], set()
- for index, folder in enumerate(roots):
- if not folder.is_dir():
- continue
- try:
- prefix = folder.relative_to(ROOT).as_posix()
- except ValueError:
- prefix = f"external-{index}/{folder.name}"
- for path in sorted(folder.rglob("*")):
- if path.is_dir():
- continue
- name = prefix + "/" + path.relative_to(folder).as_posix()
- if path.is_symlink() or private_path(name):
- skipped.append(name)
- continue
- if not path.is_file() or path.resolve() in seen:
- continue
- seen.add(path.resolve())
- files.append(("evidence/" + name, path, 0o644))
- for path in sorted(data_dir.glob("*.log")):
- if path.is_file() and not path.is_symlink() and path.resolve() not in seen:
- files.append(("evidence/data/" + path.name, path, 0o644))
- return files, skipped
- def main() -> None:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--output-dir", type=Path, default=ROOT / "dist")
- parser.add_argument("--data-dir", type=Path, default=ROOT / "data")
- parser.add_argument("--evidence-dir", action="append", type=Path, default=[])
- parser.add_argument("--session", help="Session label; defaults to the UTC packaging timestamp")
- parser.add_argument("--mode", choices=("hardware", "simulated", "mixed"), default="mixed")
- parser.add_argument("--secret-env", action="append", default=[],
- help="Also reject file bytes containing the value of this environment variable")
- args = parser.parse_args()
- try:
- if git("branch", "--show-current") != "dev":
- raise ValueError("Release from the dev branch")
- if git("status", "--porcelain", "--untracked-files=normal"):
- raise ValueError("Commit source changes before packaging; ignored data/logs may remain")
- commit = git("rev-parse", "HEAD")
- version = git("show", "HEAD:VERSION")
- if not re.fullmatch(r"\d+\.\d+\.\d+", version):
- raise ValueError("Committed VERSION must be X.Y.Z")
- now = datetime.now(timezone.utc)
- stamp = now.strftime("%Y%m%dT%H%M%SZ")
- session = args.session or stamp
- if not re.fullmatch(r"[A-Za-z0-9_.-]+", session):
- raise ValueError("Use letters, digits, dot, dash or underscore in the session label")
- secret_names = [f"STL_BMC_S{i}_PASSWORD" for i in range(1, 5)] + args.secret_env
- secrets = [os.environ[name].encode() for name in secret_names if os.environ.get(name)]
- metadata = {
- "version": version, "commit": commit, "branch": "dev",
- "tag": f"v{version}" if f"v{version}" in git("tag", "--points-at", "HEAD").splitlines() else None,
- "working_tree_dirty": False, "created_utc": now.isoformat(), "session": session,
- "mode": args.mode, "verification": "See the included review and raw evidence; packaging does not verify hardware",
- "push_status": "pending_push" if not git("remote") else "not_checked",
- "windows_transfer": "not_performed_by_this_script",
- "history_bundle": "omitted; earlier history contains runtime credentials",
- }
- source = source_files()
- source = [item for item in source if item[0] != "source/COMMIT"]
- source.extend([("source/COMMIT", (commit + "\n").encode(), 0o644),
- ("COMMIT", (commit + "\n").encode(), 0o644)])
- debug, skipped = evidence_files(args.data_dir.resolve(), [p.resolve() for p in args.evidence_dir])
- args.output_dir.mkdir(parents=True, exist_ok=True)
- prefix = f"xjkj-stl-v{version}-{commit[:7]}-{stamp}"
- archives = [write_archive(args.output_dir / f"{prefix}-source-analysis.zip", source,
- {**metadata, "archive_type": "source_and_analysis"}, secrets),
- write_archive(args.output_dir / f"{prefix}-{session}-debug-logs.zip", debug,
- {**metadata, "archive_type": "raw_debug_logs", "skipped_files": skipped}, secrets)]
- summary = {**metadata, "archives": archives}
- receipt = args.output_dir / f"{prefix}-delivery.json"
- receipt.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
- print(json.dumps({**summary, "receipt": str(receipt)}, ensure_ascii=False, indent=2))
- except (OSError, ValueError, subprocess.CalledProcessError) as exc:
- parser.exit(1, f"Packaging failed: {exc}\n")
- if __name__ == "__main__":
- main()
|