#!/usr/bin/env python3 """Check blob integrity, selected observation closure and time boundaries.""" from __future__ import annotations import argparse import json from pathlib import Path from common import Archive, atomic_json, file_sha256, read_json from rrdp import notification, payload_view, view_digest def verify(root: Path, scope_path: Path | None = None, report_path: Path | None = None) -> dict: scope = None if scope_path is not None: from scope import load_scope, outside_archive scope = load_scope(root, scope_path) report_path = report_path or scope_path.with_name("scoped-closure-report.json") outside_archive(root, report_path) if report_path.resolve() == scope_path.resolve(): raise ValueError("scoped report cannot overwrite scope") archive = Archive(root, read_only=True) checked, errors, epochs = {}, [], [] def check(ref): if ref["sha256"] in checked and checked[ref["sha256"]] != ref["size"]: raise ValueError("inconsistent blob size references") if ref["sha256"] not in checked: archive.verify_blob(ref) checked[ref["sha256"]] = ref["size"] # Check even unselected successful content and preserved failed/partial views. events = {} for path in (root / "events").glob("*.json"): event = read_json(path) events[event["id"]] = event try: if event.get("body"): check(event["body"]) for ref in event.get("objects", {}).values(): check(ref) except Exception as exc: errors.append({"event": event["id"], "error": str(exc)}) observations = {p.stem: read_json(p) for p in (root / "observations").glob("*.json")} contract_hash = None if (root / "contract.json").exists(): contract_hash = file_sha256(root / "contract.json") try: contract = read_json(root / "contract.json") for tal in contract["tals"]: check(tal) pinned = root / "inputs" / Path(tal["path"]).name if file_sha256(pinned) != tal["sha256"]: raise ValueError("pinned TAL content mismatch") if tal.get("constraints_sha256") and file_sha256(pinned.with_suffix(".constraints")) != tal["constraints_sha256"]: raise ValueError("pinned constraints mismatch") except Exception as exc: errors.append({"contract": "contract.json", "error": str(exc)}) # Independently recheck every accepted transition, including minute states # between selected five-minute epochs. Never just trust the collector's label. for item in observations.values(): if not item["complete"] or not item.get("base_observation_id"): continue try: base = observations[item["base_observation_id"]] if not base["complete"] or base["uri"] != item["uri"] or base["completed_ms"] > item["started_ms"]: raise ValueError("invalid observation predecessor") if base["session"] != item["session"]: if item["chain"] != "session_reset_snapshot": raise ValueError("session reset not recorded") continue if item["serial"] < base["serial"]: raise ValueError("serial rollback") view = read_json(root / "views" / f"{base['view']}.json") if item["serial"] - base["serial"] > 10000: raise ValueError("delta chain size bound") deltas = {r["serial"]: r for r in item["references"] if r["kind"] == "delta"} for serial in range(base["serial"] + 1, item["serial"] + 1): ref = deltas[serial] if not ref["available"]: raise ValueError("required delta missing") check({"sha256": ref["sha256"], "size": ref["size"]}) view = payload_view(archive.blob_path(ref["sha256"]), "delta", item["session"], serial, view) if view_digest(view) != item["view"]: raise ValueError("delta transition view mismatch") except Exception as exc: errors.append({"observation": item["id"], "error": str(exc)}) views_checked = set() for path in sorted((root / "epochs").glob("epoch_*.json")): epoch = read_json(path) epoch_errors = [] if epoch.get("contract_sha256") != contract_hash: epoch_errors.append("capture contract hash mismatch") if not epoch["complete"] and scope is None: epoch_errors.append(f"missing repositories: {epoch['missing']}") if epoch.get("blocked_latest_attempts"): epoch_errors.append(f"latest observations failed: {epoch['blocked_latest_attempts']}") for uri, binding in epoch["repositories"].items(): try: observation = observations[binding["id"]] if not observation["complete"] or observation["completed_ms"] > epoch["validation_time_ms"]: raise ValueError("incomplete/future observation selected") for key in ("uri", "session", "serial", "notification", "view", "completed_ms"): expected = uri if key == "uri" else binding[key] if observation[key] != expected: raise ValueError(f"observation binding mismatch: {key}") check(observation["notification"]) parsed = notification(archive.blob_path(observation["notification"]["sha256"]), uri) if parsed["session"] != binding["session"] or parsed["serial"] != binding["serial"]: raise ValueError("notification binding mismatch") refs = {(r["kind"], r["serial"], r["uri"], r["sha256"]) for r in parsed["references"]} recorded = {(r["kind"], r["serial"], r["uri"], r["sha256"]) for r in observation["references"]} if refs != recorded: raise ValueError("notification reference list mismatch") for ref in observation["references"]: if ref["available"]: check({"sha256": ref["sha256"], "size": ref["size"]}) snapshot = next(r for r in observation["references"] if r["kind"] == "snapshot") identity = (snapshot["sha256"], binding["view"]) if identity not in views_checked: view = payload_view(archive.blob_path(snapshot["sha256"]), "snapshot", binding["session"], binding["serial"]) if view_digest(view) != binding["view"]: raise ValueError("snapshot view digest mismatch") if read_json(root / "views" / f"{binding['view']}.json") != view: raise ValueError("stored view differs from snapshot") views_checked.add(identity) except Exception as exc: epoch_errors.append({"uri": uri, "error": str(exc)}) for uri, event_id in list(epoch["ta_object_events"].items()) + list(epoch["rsync_view_events"].items()): event = events.get(event_id) if not event or event["uri"] != uri or not event["complete"] or event["completed_ms"] > epoch["validation_time_ms"]: epoch_errors.append({"event": event_id, "error": "missing/incomplete/future transport view"}) epochs.append({"epoch": path.name, "repositories": len(epoch["repositories"]), "pass": not epoch_errors, "errors": epoch_errors}) if not epochs: errors.append({"error": "no epochs"}) result = {"pass": not errors and all(e["pass"] for e in epochs), "checked_blobs": len(checked), "events": len(events), "observations": len(observations), "epochs": epochs, "errors": errors} if scope is not None: result.update(scope_sha256=file_sha256(scope_path), source_contract_sha256=contract_hash, coverage=scope["coverage"], excluded_repositories=scope["excluded_repositories"], original_complete=False) atomic_json(report_path or root / "closure-report.json", result) return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--archive", type=Path, required=True) parser.add_argument("--scope", type=Path) parser.add_argument("--out", type=Path) args = parser.parse_args() result = verify(args.archive, args.scope, args.out) print(json.dumps(result)) return 0 if result["pass"] else 2 if __name__ == "__main__": raise SystemExit(main())