#!/usr/bin/env python3 """Record real internal-RP discovery plus minute RRDP observations on one host.""" from __future__ import annotations import argparse from concurrent.futures import ThreadPoolExecutor, as_completed import json import os from pathlib import Path import re import signal import subprocess import threading import tempfile import time import urllib.parse import uuid from common import Archive, SCHEMA, atomic_json, file_sha256, now_ms, read_json from rrdp import notification, payload_view, view_digest class Collector: def __init__(self, archive: Archive): self.archive = archive self.verified: set[str] = set() self.lock = threading.Lock() self.sequence = 0 def reference(self, ref: dict) -> dict: path = self.archive.blob_path(ref["sha256"]) if path.is_file(): with self.lock: if ref["sha256"] not in self.verified: self.archive.verify_blob({"sha256": ref["sha256"], "size": path.stat().st_size}) self.verified.add(ref["sha256"]) return {**ref, "available": True, "size": path.stat().st_size, "cache": True} events = [] for _ in range(self.archive.limits.get("attempts", 2)): event = self.archive.fetch(ref["uri"], ref["kind"]) events.append(event["id"]) if event["complete"] and event["body"]["sha256"] == ref["sha256"]: return {**ref, "available": True, "size": event["body"]["size"], "event_ids": events} return {**ref, "available": False, "event_ids": events, "error": "reference unavailable or hash mismatch"} def observe(self, uri: str, previous: dict | None = None) -> dict: archive = self.archive observation = {"id": str(uuid.uuid4()), "uri": uri, "started_ms": now_ms(), "complete": False} with self.lock: self.sequence += 1 observation["sequence"] = self.sequence if previous and previous.get("complete"): observation["base_observation_id"] = previous["id"] try: event = archive.fetch(uri, "notification", previous.get("http") if previous else None) observation["http"] = event if not event["complete"]: raise ValueError(event["error"]) parsed = notification(archive.blob_path(event["body"]["sha256"]), uri) observation.update(session=parsed["session"], serial=parsed["serial"], notification=event["body"]) # Snapshot first: preserve an independent starting point and fallback. refs = sorted(parsed["references"], key=lambda r: (r["kind"] != "snapshot", r["serial"])) deadline = time.monotonic() + archive.limits.get("observation_deadline_secs", 600) captured = [] for ref in refs: if time.monotonic() > deadline: captured.append({**ref, "available": False, "error": "observation deadline exceeded"}) else: captured.append(self.reference(ref)) refs = captured observation["references"] = refs snapshot = next(ref for ref in refs if ref["kind"] == "snapshot") if not snapshot["available"]: raise ValueError("current snapshot is missing") same = previous and previous.get("complete") and previous.get("session") == parsed["session"] if same and previous["serial"] == parsed["serial"]: old_snapshot = next(ref for ref in previous["references"] if ref["kind"] == "snapshot") if old_snapshot["sha256"] != snapshot["sha256"]: raise ValueError("snapshot changed without session/serial advancement") observation.update(view=previous["view"], object_count=previous["object_count"], chain="no_change") else: view = payload_view(archive.blob_path(snapshot["sha256"]), "snapshot", parsed["session"], parsed["serial"]) view_hash = view_digest(view) atomic_json(archive.root / "views" / f"{view_hash}.json", view) observation.update(view=view_hash, object_count=len(view), chain="initial_snapshot") if same: if parsed["serial"] < previous["serial"]: raise ValueError("serial rollback within the same session") old_view = read_json(archive.root / "views" / f"{previous['view']}.json") deltas = {ref["serial"]: ref for ref in refs if ref["kind"] == "delta"} needed = range(previous["serial"] + 1, parsed["serial"] + 1) if parsed["serial"] - previous["serial"] > 10000: raise ValueError("required delta chain exceeds bound") for serial in needed: delta = deltas.get(serial) if not delta or not delta["available"]: raise ValueError(f"required delta {serial} missing") old_view = payload_view(archive.blob_path(delta["sha256"]), "delta", parsed["session"], serial, old_view) if old_view != view: raise ValueError("applied delta chain differs from snapshot") observation["chain"] = "delta_matches_snapshot" elif previous and previous.get("complete"): observation["chain"] = "session_reset_snapshot" observation["complete"] = True except Exception as exc: observation["error"] = f"{type(exc).__name__}: {exc}" observation["completed_ms"] = now_ms() atomic_json(archive.root / "observations" / f"{observation['id']}.json", observation) print(json.dumps({k: observation.get(k) for k in ("uri", "serial", "complete", "chain", "error")}), flush=True) return observation def select_epoch(root: Path, registry: dict, cutoff: int) -> dict: selected, latest, missing, blocked = {}, {}, [], [] for path in (root / "observations").glob("*.json"): item = read_json(path) if item["completed_ms"] > cutoff: continue uri = item["uri"] order = (item["completed_ms"], item.get("sequence", 0)) if uri not in latest or order > (latest[uri]["completed_ms"], latest[uri].get("sequence", 0)): latest[uri] = item if item["complete"] and (uri not in selected or order > (selected[uri]["completed_ms"], selected[uri].get("sequence", 0))): selected[uri] = item for uri, entry in registry.items(): if entry["first_seen_ms"] <= cutoff and uri not in selected: missing.append(uri) elif entry["first_seen_ms"] <= cutoff and not latest[uri]["complete"]: blocked.append(uri) # Bind real TA HTTP/rsync-object versions and complete rsync module views. objects, rsync = {}, {} for path in (root / "events").glob("*.json"): event = read_json(path) if not event["complete"] or event["completed_ms"] > cutoff or event["source"] not in ("rpki", "ta_refresh"): continue target = rsync if event["transport"] == "rsync" and event["kind"] == "view" else objects if event["kind"] not in ("object", "view"): continue if event["uri"] not in target or target[event["uri"]]["completed_ms"] < event["completed_ms"]: target[event["uri"]] = event contract = root / "contract.json" return {"schema": SCHEMA, "validation_time_ms": cutoff, "complete": not missing and not blocked, "contract_sha256": file_sha256(contract) if contract.is_file() else None, "repositories": {u: {k: o[k] for k in ("id", "session", "serial", "notification", "view", "completed_ms")} for u, o in selected.items()}, "latest_attempts": {u: {k: o.get(k) for k in ("id", "complete", "completed_ms", "error")} for u, o in latest.items()}, "missing": sorted(missing), "blocked_latest_attempts": sorted(blocked), "ta_object_events": {u: e["id"] for u, e in objects.items()}, "rsync_view_events": {u: e["id"] for u, e in rsync.items()}} class Capture: def __init__(self, config: dict): self.config = config poll, step, duration = config.get("poll_secs", 60), config.get("step_secs", 300), config.get("duration_secs", 3600) if poll < 60 or step < poll or duration < step or duration % step: raise ValueError("require poll>=60, step>=poll, duration>=step and a whole number of steps") if not 1 <= config.get("workers", 4) <= 8: raise ValueError("capture workers must be between 1 and 8") if len(config["tals"]) != 5 or len(set(config["tals"])) != 5: raise ValueError("main capture requires five distinct real TAL paths") if config.get("bootstrap_gap_policy", "abort") not in ("abort", "record-with-gaps"): raise ValueError("bootstrap_gap_policy must be abort or record-with-gaps") self.root = Path(config["archive_root"]).resolve() if self.root.exists() and any(self.root.iterdir()): raise ValueError("capture root already exists; use a new capture ID") self.archive = Archive(self.root, config.get("limits")) self.collector = Collector(self.archive) self.registry, self.latest, self.seen_events = {}, {}, set() self.rp = None self.run_number = 0 self.stopping = False self.metadata = {"schema": SCHEMA, "status": "bootstrap", "started_ms": now_ms(), "config": config, "binary_sha256": file_sha256(Path(config["binary"])), "runs": []} self.metadata["scripts_sha256"] = {p.name: file_sha256(p) for p in Path(__file__).parent.glob("*.py")} self.metadata["machine"] = {"uname": list(os.uname()), "cpus": os.cpu_count()} self.pin_inputs() self.save() def pin_inputs(self) -> None: tals = [] for name in self.config["tals"]: source = Path(name) data = source.read_bytes() body = self.archive.put_stream(__import__("io").BytesIO(data)) target = self.root / "inputs" / source.name target.parent.mkdir(exist_ok=True) target.write_bytes(data) item = {"path": str(target), **body} # CIR requires an HTTP(S) locator even for file TAL inputs. This is # an explicit content-addressed label, never a download endpoint. item["cir_tal_uri"] = f"https://capture.rpki187.invalid/tal/{body['sha256']}/{source.name}" constraint = source.with_suffix(".constraints") if constraint.exists(): target.with_suffix(".constraints").write_bytes(constraint.read_bytes()) item["constraints_sha256"] = file_sha256(constraint) tals.append(item) self.metadata["tals"] = tals def save(self) -> None: atomic_json(self.root / "capture.json", self.metadata) atomic_json(self.root / "registry.json", self.registry) def discover(self) -> None: for path in (self.root / "events").glob("*.json"): if path.name in self.seen_events: continue event = read_json(path) self.seen_events.add(path.name) if event["source"] == "rpki" and event["kind"] == "notification": self.registry.setdefault(event["uri"], {"first_seen_ms": event["started_ms"]}) if len(self.registry) > self.config.get("max_repositories", 1000): raise RuntimeError("repository count limit exceeded") def start_rp(self) -> None: self.archive.guard() self.run_number += 1 run = self.root / "discovery" / f"run_{self.run_number:04d}" run.mkdir(parents=True) (self.root / "discovery/state").mkdir(parents=True, exist_ok=True) (run / "ta").mkdir() ta_versions = [] for tal in self.metadata["tals"]: ta_versions.append(self.refresh_ta(Path(tal["path"]), run / "ta")) command = [self.config["binary"], "--db", str(self.root / "discovery/state/db"), "--record-transport-dir", str(self.root), "--rsync-mirror-root", str(self.root / "discovery/mirror"), "--report-json", str(run / "report.json"), "--report-json-compact", "--validation-contract-out", str(run / "validation-contract.json"), "--ccr-out", str(run / "result.ccr"), "--cir-enable", "--cir-out", str(run / "input.cir"), "--analyze", "--analysis-out", str(run / "analysis")] for tal, ta in zip(self.metadata["tals"], ta_versions): command += ["--tal-path", tal["path"], "--ta-path", ta["path"], "--cir-tal-uri", tal["cir_tal_uri"]] command += self.config.get("rp_args", []) env = dict(os.environ, TMPDIR=str(self.root / "partial")) self.rp_started = time.monotonic() with (run / "stdout.log").open("wb") as out, (run / "stderr.log").open("wb") as err: self.rp = subprocess.Popen(command, stdout=out, stderr=err, env=env, start_new_session=True) self.metadata["runs"].append({"path": str(run), "command": command, "started_ms": now_ms(), "pid": self.rp.pid, "ta_versions": ta_versions}) self.save() def refresh_ta(self, tal: Path, destination: Path) -> dict: """Existing internal CLI file mode requires an explicit, genuine TA file. Refresh from original TAL endpoints before each run, then let the real RP verify the DER/SPKI, validity and trust-anchor profile as usual. """ uris = [line.strip() for line in tal.read_text().splitlines() if line.strip().startswith(("https://", "rsync://"))] uris.sort(key=lambda uri: not uri.startswith("https://")) for uri in uris: if uri.startswith("https://"): event = self.archive.fetch(uri, "object", source="ta_refresh") ref = event.get("body") else: event = {"source": "ta_refresh", "transport": "rsync", "kind": "object", "uri": uri, "started_ms": now_ms(), "complete": False, "objects": {}} ref = None try: with tempfile.TemporaryDirectory(dir=self.root / "partial") as name: result = subprocess.run(["rsync", "-rt", "--contimeout=15", "--timeout=30", "--", uri, name + "/"], capture_output=True, timeout=60) if result.returncode: raise ValueError(result.stderr.decode(errors="replace")[:2000]) path = Path(name) / Path(urllib.parse.urlsplit(uri).path).name with path.open("rb") as stream: ref = self.archive.put_stream(stream) event.update(complete=True, objects={uri: ref}) except Exception as exc: event["error"] = f"{type(exc).__name__}: {exc}" self.archive.event(event) if event["complete"]: target = destination / (tal.stem + ".cer") target.write_bytes(self.archive.blob_path(ref["sha256"]).read_bytes()) return {"path": str(target), "uri": uri, "event_id": event["id"], **ref} raise RuntimeError(f"could not download genuine TA from TAL endpoints: {tal}") def check_rp(self) -> None: if self.rp is None: return if time.monotonic() - self.rp_started > self.config.get("rp_timeout_secs", 1800): self.stop_rp() raise RuntimeError("discovery RP exceeded wall-clock timeout") status = self.rp.poll() if status is not None: run = self.metadata["runs"][-1] run.update(exit_code=status, completed_ms=now_ms()) self.rp = None self.save() if status != 0: raise RuntimeError(f"real discovery RP failed: {status}") stderr = (Path(run["path"]) / "stderr.log").read_text(errors="replace") anchors = re.findall(r"wrote CIR: .*?trust_anchors=(\d+)", stderr) if not anchors or int(anchors[-1]) != len(self.metadata["tals"]): raise RuntimeError("discovery did not produce a CIR with all five genuine trust anchors") stdout = (Path(run["path"]) / "stdout.log").read_text(errors="replace") counts = {key: int(value) for key, value in re.findall(r"^(vrps|aspas|rrdp_repos_unique|audit_publication_points)=(\d+)$", stdout, re.MULTILINE)} run.update(trust_anchors=int(anchors[-1]), counts=counts) self.save() def stop_rp(self) -> None: if self.rp is not None and self.rp.poll() is None: os.killpg(self.rp.pid, signal.SIGTERM) try: self.rp.wait(timeout=10) except subprocess.TimeoutExpired: os.killpg(self.rp.pid, signal.SIGKILL) self.rp.wait(timeout=10) if self.metadata["runs"]: self.metadata["runs"][-1].update(exit_code=self.rp.returncode, completed_ms=now_ms(), stopped_by_controller=True) self.rp = None def run(self) -> None: workers = self.config.get("workers", 4) self.start_rp() while self.rp is not None and not self.stopping: self.archive.guard() self.check_rp() self.discover() time.sleep(1) self.discover() if self.stopping: raise RuntimeError("capture stopped during bootstrap") if not self.registry: raise RuntimeError("internal RP discovered no RRDP repositories") normal_contract = read_json(Path(self.metadata["runs"][0]["path"]) / "validation-contract.json") atomic_json(self.root / "contract.json", {"schema": SCHEMA, "binary_sha256": self.metadata["binary_sha256"], "scripts_sha256": self.metadata["scripts_sha256"], "machine": self.metadata["machine"], "tals": self.metadata["tals"], "normal_validation_contract": normal_contract, "rp_args": self.config.get("rp_args", [])}) # Bounded bootstrap retries. A partial starting point is never relabelled complete. with ThreadPoolExecutor(max_workers=workers) as pool: for _ in range(self.config.get("bootstrap_attempts", 3)): pending = {pool.submit(self.collector.observe, uri, self.latest.get(uri)): uri for uri in self.registry if not self.latest.get(uri, {}).get("complete")} for future in as_completed(pending): self.latest[pending[future]] = future.result() if all(self.latest.get(uri, {}).get("complete") for uri in self.registry): break t0 = now_ms() initial = select_epoch(self.root, self.registry, t0) atomic_json(self.root / "epochs/epoch_0000.json", initial) self.metadata.update(bootstrap_complete=initial["complete"], bootstrap_missing=initial["missing"], bootstrap_blocked_latest_attempts=initial["blocked_latest_attempts"]) if not initial["complete"] and self.config.get("bootstrap_gap_policy", "abort") == "abort": self.metadata.update(status="bootstrap_incomplete", missing=initial["missing"]) self.save() return duration = self.config.get("duration_secs", 3600) poll_secs = self.config.get("poll_secs", 60) step_secs = self.config.get("step_secs", 300) self.metadata.update(status="recording" if initial["complete"] else "recording_with_gaps", t0_ms=t0, end_ms=t0 + duration * 1000) self.save() end = time.monotonic() + duration next_rp = time.monotonic() + step_secs due = {uri: time.monotonic() + poll_secs for uri in self.registry} in_flight = {} while time.monotonic() < end and not self.stopping: self.archive.guard() self.check_rp() self.discover() moment = time.monotonic() if moment >= next_rp and self.rp is None: self.start_rp() next_rp = moment + step_secs for uri in self.registry: due.setdefault(uri, moment) if uri not in in_flight and moment >= due[uri]: in_flight[uri] = pool.submit(self.collector.observe, uri, self.latest.get(uri)) due[uri] = moment + poll_secs for uri, future in list(in_flight.items()): if future.done(): item = future.result() # Keep the last complete base for chain validation after a failed observation. if item["complete"]: self.latest[uri] = item del in_flight[uri] self.save() time.sleep(1) # Requests have per-body deadlines. Drained responses keep their real completion time. for future in in_flight.values(): future.result() self.stop_rp() captured_secs = min(duration, max(0, (now_ms() - t0) // 1000)) for index, offset in enumerate(range(0, captured_secs + 1, step_secs)): epoch = select_epoch(self.root, self.registry, t0 + offset * 1000) atomic_json(self.root / "epochs" / f"epoch_{index:04d}.json", epoch) status = "recorded" if initial["complete"] else "recorded_with_gaps" self.metadata.update(status="interrupted" if self.stopping else status, finished_ms=now_ms(), repositories=len(self.registry), captured_secs=captured_secs) self.save() def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", type=Path, required=True) args = parser.parse_args() capture = Capture(read_json(args.config)) def stop(*_): capture.stopping = True signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) try: capture.run() except Exception as exc: capture.metadata.update(status="failed", error=f"{type(exc).__name__}: {exc}", finished_ms=now_ms()) raise finally: capture.stop_rp() capture.save() return 0 if capture.metadata["status"] in ("recorded", "recorded_with_gaps") else 2 if __name__ == "__main__": raise SystemExit(main())