"""Immutable transport capture primitives shared by collection and replay.""" from __future__ import annotations import gzip import hashlib import json import os from pathlib import Path import shutil import tempfile import time import urllib.error import urllib.parse import urllib.request import uuid SCHEMA = "rpki-transport-capture-v1" HEADERS = ("etag", "last-modified", "content-type", "content-length", "content-encoding", "date", "location") def now_ms() -> int: return time.time_ns() // 1_000_000 def atomic_json(path: Path, value: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) fd, name = tempfile.mkstemp(prefix=".pending-", dir=path.parent) try: with os.fdopen(fd, "w", encoding="utf-8") as stream: json.dump(value, stream, sort_keys=True, separators=(",", ":"), ensure_ascii=True) stream.flush() os.replace(name, path) finally: Path(name).unlink(missing_ok=True) def read_json(path: Path) -> object: return json.loads(path.read_text(encoding="utf-8")) def digest_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def file_sha256(path: Path) -> str: with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def origin(uri: str) -> tuple[str, str, int]: url = urllib.parse.urlsplit(uri) if url.scheme not in ("http", "https") or not url.hostname or url.username or url.password or url.fragment: raise ValueError(f"invalid HTTP URI: {uri}") return url.scheme, url.hostname.lower(), url.port or (443 if url.scheme == "https" else 80) class SameOriginRedirect(urllib.request.HTTPRedirectHandler): def __init__(self, allowed: tuple[str, str, int]): self.allowed = allowed def redirect_request(self, req, fp, code, msg, headers, newurl): if origin(newurl) != self.allowed: raise ValueError(f"cross-origin redirect rejected: {newurl}") return super().redirect_request(req, fp, code, msg, headers, newurl) class TaRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): if origin(newurl)[0] != "https": raise ValueError("TA redirect downgraded HTTPS") return super().redirect_request(req, fp, code, msg, headers, newurl) class Archive: def __init__(self, root: Path, limits: dict | None = None, *, read_only: bool = False): self.root = root self.limits = limits or {} self.read_only = read_only self.initial_free = shutil.disk_usage(root.parent).free if not read_only: for name in ("blobs/sha256", "events", "partial", "observations", "views", "epochs"): (root / name).mkdir(parents=True, exist_ok=True) def guard(self) -> None: if self.read_only: raise ValueError("archive is read-only") free = shutil.disk_usage(self.root).free if free < self.limits.get("min_free_bytes", 0): raise RuntimeError(f"archive disk guard: {free} bytes free") if self.initial_free - free > self.limits.get("max_growth_bytes", 200 * 1024**3): raise RuntimeError("capture total disk-growth budget exceeded") if os.statvfs("/").f_favail < self.limits.get("min_root_free_inodes", 0): raise RuntimeError("root filesystem inode guard") def blob_path(self, sha256: str) -> Path: if len(sha256) != 64 or any(c not in "0123456789abcdef" for c in sha256): raise ValueError("invalid SHA-256") return self.root / "blobs/sha256" / sha256[:2] / sha256 def put_stream(self, stream) -> dict: self.guard() maximum = self.limits.get("max_body_bytes", 2 * 1024**3) deadline = time.monotonic() + self.limits.get("body_deadline_secs", 240) fd, name = tempfile.mkstemp(dir=self.root / "partial") digest, size = hashlib.sha256(), 0 try: with os.fdopen(fd, "wb") as output: while True: chunk = stream.read(65536) if not chunk: break size += len(chunk) if size > maximum or time.monotonic() > deadline: raise ValueError("body size or wall-clock limit exceeded") digest.update(chunk) output.write(chunk) sha256 = digest.hexdigest() path = self.blob_path(sha256) path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): Path(name).unlink() else: os.replace(name, path) return {"sha256": sha256, "size": size} finally: Path(name).unlink(missing_ok=True) def event(self, value: dict) -> dict: if self.read_only: raise ValueError("archive is read-only") value.setdefault("schema", SCHEMA) value.setdefault("id", str(uuid.uuid4())) value.setdefault("completed_ms", now_ms()) atomic_json(self.root / "events" / f"{value['id']}.json", value) return value def fetch(self, uri: str, kind: str, previous: dict | None = None, source: str = "poller") -> dict: """Keep failed requests; 304 explicitly binds the prior entity hash.""" self.guard() allowed = origin(uri) if allowed[0] != "https" and not self.limits.get("allow_test_http", False): raise ValueError("live capture requires HTTPS") event = {"source": source, "transport": "http", "kind": kind, "uri": uri, "started_ms": now_ms(), "complete": False} headers = {"User-Agent": "panda-rpki-evaluation-recorder/1", "Accept-Encoding": "identity"} if previous: old_headers = previous.get("headers", {}) if old_headers.get("etag"): headers["If-None-Match"] = old_headers["etag"] if old_headers.get("last-modified"): headers["If-Modified-Since"] = old_headers["last-modified"] request = urllib.request.Request(uri, headers=headers) # Ignore machine proxy variables: record direct origin traffic on 186. redirect = TaRedirect() if kind == "object" else SameOriginRedirect(allowed) opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), redirect) try: try: response = opener.open(request, timeout=self.limits.get("request_timeout_secs", 30)) except urllib.error.HTTPError as exc: response = exc with response: event.update(status=response.code, final_uri=response.url, headers={k: response.headers[k] for k in HEADERS if k in response.headers}) if response.code == 304: if not previous or not previous.get("body"): raise ValueError("304 without a prior body") if not self.blob_path(previous["body"]["sha256"]).is_file(): raise ValueError("304 prior body is missing") event.update(body=previous["body"], prior_event_id=previous["id"], complete=True) elif response.code == 200: encoding = response.headers.get("Content-Encoding", "identity").lower() if encoding not in ("identity", "gzip"): raise ValueError(f"unsupported content encoding: {encoding}") body = gzip.GzipFile(fileobj=response) if encoding == "gzip" else response blob = self.put_stream(body) if encoding == "identity" and response.headers.get("Content-Length") is not None: if blob["size"] != int(response.headers["Content-Length"]): raise ValueError("truncated HTTP entity") event.update(body=blob, complete=True) else: raise ValueError(f"HTTP {response.code}") except Exception as exc: event["error"] = f"{type(exc).__name__}: {exc}" return self.event(event) def verify_blob(self, ref: dict) -> None: path = self.blob_path(ref["sha256"]) digest, size = hashlib.sha256(), 0 with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) size += len(chunk) if digest.hexdigest() != ref["sha256"] or size != ref["size"]: raise ValueError(f"corrupt archive blob: {ref['sha256']}")