#!/usr/bin/env python3 """Release-validation aggregator for MSE dual packages. Fail-closed: missing/skipped/not_provided/unknown/fail all make the top-level fail. Does not upload. """ from __future__ import annotations import argparse import hashlib import json import zipfile from datetime import datetime, timezone from pathlib import Path from typing import Any try: from compact_package_selftest import run_compact_zip_selftest from cross_package_verify import verify_cross_package except ImportError: # pytest imports tools.release_validation from tools.compact_package_selftest import run_compact_zip_selftest from tools.cross_package_verify import verify_cross_package SELFTEST_SIDECAR_LABELS = frozenset( { "review_selftest_sidecar", "firmware_selftest_sidecar", "review_detached_replay_sidecar", } ) REQUIRED_PARTS = ( "cross_package", "review_standalone_selftest", "review_selftest_sidecar", "firmware_selftest_sidecar", "external_release_set", ) def _sha256_file(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as fh: for chunk in iter(lambda: fh.read(1024 * 1024), b""): h.update(chunk) return h.hexdigest() def _status_ok(value: Any) -> bool: return str(value or "").casefold() in {"pass", "true"} def validate_release( *, review_zip: Path, firmware_zip: Path, review_selftest_json: Path | None = None, firmware_selftest_json: Path | None = None, release_set_json: Path | None = None, review_detached_replay_json: Path | None = None, ) -> dict[str, Any]: failures: list[str] = [] parts: dict[str, Any] = {} try: cross = verify_cross_package(review_zip, firmware_zip) except Exception as exc: # noqa: BLE001 cross = {"status": "fail", "failures": [f"exception:{exc}"]} parts["cross_package"] = cross if not _status_ok(cross.get("status")): failures.append("cross_package_fail") failures.extend(f"cross:{x}" for x in (cross.get("failures") or [])[:20]) try: review_st = run_compact_zip_selftest(review_zip) parts["review_standalone_selftest"] = review_st if not isinstance(review_st, dict) or not _status_ok(review_st.get("status")): failures.append("review_standalone_selftest_fail") except Exception as exc: # noqa: BLE001 failures.append(f"review_selftest_error:{exc}") parts["review_standalone_selftest"] = {"status": "fail", "error": str(exc)} sidecar_specs = ( ("review_selftest_sidecar", review_selftest_json), ("firmware_selftest_sidecar", firmware_selftest_json), ("external_release_set", release_set_json), ("review_detached_replay_sidecar", review_detached_replay_json), ) for label, path in sidecar_specs: if path is None: failures.append(f"{label}_not_provided") parts[label] = {"status": "not_provided"} continue if not path.is_file(): failures.append(f"missing_{label}") parts[label] = {"status": "missing", "path": str(path)} continue try: doc = json.loads(path.read_text(encoding="utf-8")) except Exception as exc: # noqa: BLE001 failures.append(f"{label}_unreadable") parts[label] = {"status": "fail", "error": str(exc)} continue st = str(doc.get("status") or "").casefold() parts[label] = { "status": st or "present", "path": str(path), "sha256": _sha256_file(path), } if label in SELFTEST_SIDECAR_LABELS or label == "external_release_set": if st in {"", "skipped", "not_provided", "missing", "unknown", "incompatible"}: failures.append(f"{label}_not_pass:{st or 'empty'}") elif st != "pass": failures.append(f"{label}_not_pass") for label, zpath in (("review", review_zip), ("firmware", firmware_zip)): if not zpath.is_file(): failures.append(f"missing_{label}_zip") continue with zipfile.ZipFile(zpath) as zf: for name in zf.namelist(): n = name.replace("\\", "/") if n.startswith("/") or n.startswith("../") or "/../" in n: failures.append(f"{label}_unsafe_zip_path:{n}") for name in REQUIRED_PARTS: part = parts.get(name) or {} st = str(part.get("status") or "").casefold() if st in {"skipped", "not_provided", "missing", "unknown"}: failures.append(f"{name}_{st}") # unique failures = list(dict.fromkeys(failures)) status = "fail" if failures else "pass" return { "schema": "prod2u-mse-release-validation-v1", "generated_utc": datetime.now(timezone.utc).isoformat(), "status": status, "failures": failures, "parts": parts, "review_zip": str(review_zip), "firmware_zip": str(firmware_zip), "review_sha256": _sha256_file(review_zip) if review_zip.is_file() else None, "firmware_sha256": _sha256_file(firmware_zip) if firmware_zip.is_file() else None, "hardware_validation": "NOT RUN", "dev_merge": "FORBIDDEN", } def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--review-zip", type=Path, required=True) parser.add_argument("--firmware-zip", type=Path, required=True) parser.add_argument("--review-selftest-json", type=Path, default=None) parser.add_argument("--firmware-selftest-json", type=Path, default=None) parser.add_argument("--release-set-json", type=Path, default=None) parser.add_argument("--review-detached-replay-json", type=Path, default=None) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args(argv) result = validate_release( review_zip=args.review_zip, firmware_zip=args.firmware_zip, review_selftest_json=args.review_selftest_json, firmware_selftest_json=args.firmware_selftest_json, release_set_json=args.release_set_json, review_detached_replay_json=args.review_detached_replay_json, ) args.output.parent.mkdir(parents=True, exist_ok=True) text = json.dumps(result, indent=2) + "\n" args.output.write_text(text, encoding="utf-8") sha = hashlib.sha256(text.encode("utf-8")).hexdigest() args.output.with_suffix(args.output.suffix + ".sha256").write_text( f"{sha} {args.output.name}\n", encoding="utf-8" ) print(json.dumps({"status": result["status"], "output": str(args.output)})) return 0 if result["status"] == "pass" else 1 if __name__ == "__main__": raise SystemExit(main())