"""Protocol-focused tests; no public network or genuine TA substitutes as evidence.""" import base64 import gzip from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import io import json from pathlib import Path import tempfile import threading import sys import time import unittest from unittest.mock import Mock, patch from capture import Capture, Collector, select_epoch from common import Archive, atomic_json, digest_bytes, file_sha256, now_ms from rrdp import notification, payload_view, view_digest from verify import verify SESSION = "11111111-1111-4111-8111-111111111111" OTHER_SESSION = "22222222-2222-4222-8222-222222222222" OBJECT = "rsync://repo.example/module/a.roa" OTHER_OBJECT = "rsync://repo.example/module/b.roa" def publish(uri, data, previous=None): attr = f' hash="{digest_bytes(previous)}"' if previous is not None else "" return f'{base64.b64encode(data).decode()}' def xml(kind, serial, content, session=SESSION): return (f'<{kind} xmlns="http://www.ripe.net/rpki/rrdp" version="1" session_id="{session}" serial="{serial}">' f'{content}').encode() class CaptureTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.resources = {} self.requests = [] resources, requests = self.resources, self.requests class Handler(BaseHTTPRequestHandler): def log_message(self, *_): pass def do_GET(self): requests.append((self.path, self.headers.get("If-None-Match"))) resource = resources.get(self.path) if resource is None: self.send_error(404) return body, headers = resource status = 304 if headers.get("ETag") == self.headers.get("If-None-Match") and headers.get("ETag") else headers.get("status", 200) self.send_response(status) for key, value in headers.items(): if key not in ("status", "Content-Length"): self.send_header(key, value) self.send_header("Content-Length", headers.get("Content-Length", str(len(body)))) self.end_headers() if status != 304: self.wfile.write(body) self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) self.thread.start() self.addCleanup(self.server.server_close) self.addCleanup(self.server.shutdown) self.base = f"http://127.0.0.1:{self.server.server_port}" self.uri = self.base + "/notification.xml" self.archive = Archive(Path(self.tmp.name) / "archive", {"allow_test_http": True, "attempts": 1, "request_timeout_secs": 1}) self.collector = Collector(self.archive) def install(self, serial, snapshot, deltas=None, session=SESSION, etag=None): self.resources["/snapshot.xml"] = (snapshot, {}) content = f'' for number, body in (deltas or {}).items(): self.resources[f"/delta-{number}.xml"] = (body, {}) content += f'' self.resources["/notification.xml"] = (xml("notification", serial, content, session), {"ETag": etag} if etag else {}) def initial(self): self.install(1, xml("snapshot", 1, publish(OBJECT, b"a")), etag='"one"') observation = self.collector.observe(self.uri) self.assertTrue(observation["complete"], observation) return observation def test_initial_and_304_reuse_exact_body(self): first = self.initial() second = self.collector.observe(self.uri, first) self.assertTrue(second["complete"]) self.assertEqual(second["http"]["status"], 304) self.assertEqual(first["notification"], second["notification"]) self.assertEqual(second["chain"], "no_change") self.assertEqual(sum(path == "/snapshot.xml" for path, _ in self.requests), 1) def test_multiple_delta_replacement_and_withdrawal_match_snapshot(self): first = self.initial() d2 = xml("delta", 2, publish(OBJECT, b"changed", b"a") + publish(OTHER_OBJECT, b"b")) d3 = xml("delta", 3, f'') self.install(3, xml("snapshot", 3, publish(OBJECT, b"changed")), {2: d2, 3: d3}) final = self.collector.observe(self.uri, first) self.assertTrue(final["complete"], final) self.assertEqual(final["chain"], "delta_matches_snapshot") self.assertTrue(self.archive.blob_path(first["notification"]["sha256"]).exists()) def test_missing_required_delta_rejects_observation(self): first = self.initial() self.install(3, xml("snapshot", 3, publish(OBJECT, b"a")), {3: xml("delta", 3, "")}) result = self.collector.observe(self.uri, first) self.assertFalse(result["complete"]) self.assertIn("required delta 2 missing", result["error"]) def test_wrong_previous_hash_rejects_delta(self): first = self.initial() self.install(2, xml("snapshot", 2, publish(OBJECT, b"new")), {2: xml("delta", 2, publish(OBJECT, b"new", b"wrong"))}) self.assertIn("previous hash mismatch", self.collector.observe(self.uri, first)["error"]) def test_delta_snapshot_disagreement_rejects_observation(self): first = self.initial() self.install(2, xml("snapshot", 2, publish(OBJECT, b"other")), {2: xml("delta", 2, publish(OBJECT, b"new", b"a"))}) self.assertIn("differs from snapshot", self.collector.observe(self.uri, first)["error"]) def test_session_reset_uses_real_new_snapshot(self): first = self.initial() self.install(1, xml("snapshot", 1, publish(OTHER_OBJECT, b"b"), OTHER_SESSION), session=OTHER_SESSION) result = self.collector.observe(self.uri, first) self.assertTrue(result["complete"], result) self.assertEqual(result["chain"], "session_reset_snapshot") def test_snapshot_reference_hash_mismatch_is_not_complete(self): self.initial() self.resources["/snapshot.xml"] = (b"corrupt", {}) # New archive prevents a valid previously saved body satisfying the reference. other = Archive(Path(self.tmp.name) / "other", self.archive.limits) self.assertFalse(Collector(other).observe(self.uri)["complete"]) def test_same_serial_changed_snapshot_rejected(self): first = self.initial() self.install(1, xml("snapshot", 1, publish(OBJECT, b"changed"))) self.assertIn("without session/serial", self.collector.observe(self.uri, first)["error"]) def test_old_optional_delta_failure_is_reported_but_initial_usable(self): self.install(2, xml("snapshot", 2, publish(OBJECT, b"a")), {1: xml("delta", 1, "")}) del self.resources["/delta-1.xml"] result = self.collector.observe(self.uri) self.assertTrue(result["complete"], result) self.assertFalse(next(r for r in result["references"] if r["kind"] == "delta")["available"]) def test_304_without_prior_entity_is_failure(self): self.resources["/x"] = (b"", {"status": 304}) result = self.archive.fetch(self.base + "/x", "notification") self.assertFalse(result["complete"]) def test_http_gzip_preserves_decoded_entity(self): raw = b"signed content" self.resources["/gzip"] = (gzip.compress(raw), {"Content-Encoding": "gzip"}) result = self.archive.fetch(self.base + "/gzip", "snapshot") self.assertTrue(result["complete"], result) self.assertEqual(result["body"]["sha256"], digest_bytes(raw)) def test_truncated_body_is_failure(self): self.resources["/short"] = (b"short", {"Content-Length": "100"}) self.assertFalse(self.archive.fetch(self.base + "/short", "snapshot")["complete"]) def test_cross_origin_redirect_never_follows(self): self.resources["/redirect"] = (b"", {"status": 302, "Location": "http://localhost:1/forbidden"}) result = self.archive.fetch(self.base + "/redirect", "notification") self.assertFalse(result["complete"]) self.assertIn("cross-origin", result["error"]) def test_cross_origin_reference_rejected(self): body = xml("notification", 1, f'') ref = self.archive.put_stream(io.BytesIO(body)) with self.assertRaisesRegex(ValueError, "cross-origin"): notification(self.archive.blob_path(ref["sha256"]), self.uri) def test_future_completion_never_used_for_earlier_epoch(self): first = self.initial() registry = {self.uri: {"first_seen_ms": 0}} early = select_epoch(self.archive.root, registry, first["completed_ms"] - 1) self.assertFalse(early["complete"]) exact = select_epoch(self.archive.root, registry, first["completed_ms"]) self.assertTrue(exact["complete"]) self.assertEqual(exact["repositories"][self.uri]["id"], first["id"]) def test_latest_failure_cannot_silently_turn_into_a_successful_noop_epoch(self): first = self.initial() self.resources.pop("/notification.xml") failed = self.collector.observe(self.uri, first) self.assertFalse(failed["complete"]) epoch = select_epoch(self.archive.root, {self.uri: {"first_seen_ms": 0}}, now_ms()) self.assertFalse(epoch["complete"]) self.assertEqual(epoch["blocked_latest_attempts"], [self.uri]) self.assertEqual(epoch["repositories"][self.uri]["id"], first["id"]) def test_closure_verifier_detects_corrupt_blob(self): first = self.initial() epoch = select_epoch(self.archive.root, {self.uri: {"first_seen_ms": 0}}, now_ms()) atomic_json(self.archive.root / "epochs/epoch_0000.json", epoch) self.assertTrue(verify(self.archive.root)["pass"]) self.archive.blob_path(first["notification"]["sha256"]).write_bytes(b"corrupt") self.assertFalse(verify(self.archive.root)["pass"]) def test_epoch_rejects_changed_capture_policy_contract(self): self.initial() contract = self.archive.root / "contract.json" atomic_json(contract, {"tals": [], "policy": "fixed"}) epoch = select_epoch(self.archive.root, {self.uri: {"first_seen_ms": 0}}, now_ms()) atomic_json(self.archive.root / "epochs/epoch_0000.json", epoch) self.assertTrue(verify(self.archive.root)["pass"]) atomic_json(contract, {"tals": [], "policy": "different"}) self.assertFalse(verify(self.archive.root)["pass"]) def test_zero_exit_with_only_four_anchors_never_qualifies_main_capture(self): tals = [] for index in range(5): path = Path(self.tmp.name) / f"fixture-{index}.tal" path.write_text(f"https://fixture.example/{index}.cer\n\nunit-test-input\n") tals.append(str(path)) capture = Capture({"archive_root": str(Path(self.tmp.name) / "main"), "binary": sys.executable, "tals": tals}) run = capture.root / "unit-run" run.mkdir() (run / "stderr.log").write_text("wrote CIR: unit (objects=1, trust_anchors=4, total_ms=1)\n") (run / "stdout.log").write_text("vrps=100\n") capture.metadata["runs"] = [{"path": str(run)}] capture.rp = Mock() capture.rp.poll.return_value = 0 capture.rp_started = time.monotonic() with self.assertRaisesRegex(RuntimeError, "all five"): capture.check_rp() def test_ta_refresh_event_is_bound_to_the_epoch(self): ref = self.archive.put_stream(io.BytesIO(b"unit TA entity")) uri = "https://ta.example/real-endpoint.cer" event = self.archive.event({"source": "ta_refresh", "transport": "http", "kind": "object", "uri": uri, "started_ms": now_ms(), "complete": True, "body": ref}) epoch = select_epoch(self.archive.root, {}, now_ms()) self.assertEqual(epoch["ta_object_events"][uri], event["id"]) def test_gap_recording_keeps_incomplete_epochs_and_strict_default_gate(self): # Exercise controller policy only; the real five-TA acceptance is remote. tals = [] for index in range(5): tal = Path(self.tmp.name) / f"policy-{index}.tal" tal.write_text(f"https://fixture.example/{index}.cer\n\nunit-input\n") tals.append(str(tal)) for policy in ("abort", "record-with-gaps"): with self.subTest(policy=policy): config = {"archive_root": str(Path(self.tmp.name) / policy), "binary": sys.executable, "tals": tals, "duration_secs": 300, "bootstrap_attempts": 1} if policy != "abort": config["bootstrap_gap_policy"] = policy capture = Capture(config) run = capture.root / "controller-unit-run" run.mkdir() atomic_json(run / "validation-contract.json", {"test_only": True}) capture.start_rp = lambda: capture.metadata["runs"].append({"path": str(run)}) capture.discover = lambda: capture.registry.update({self.base + "/unreachable.xml": {"first_seen_ms": 0}}) clock = Mock() clock.monotonic.side_effect = iter(range(0, 10000, 1000)) with patch("capture.time", clock): capture.run() expected = "bootstrap_incomplete" if policy == "abort" else "recorded_with_gaps" self.assertEqual(capture.metadata["status"], expected) self.assertFalse(capture.metadata["bootstrap_complete"]) self.assertEqual(capture.metadata["bootstrap_missing"], [self.base + "/unreachable.xml"]) epoch = json.loads((capture.root / "epochs/epoch_0000.json").read_text()) self.assertFalse(epoch["complete"]) self.assertFalse(verify(capture.root)["pass"]) self.assertEqual("t0_ms" in capture.metadata, policy != "abort") def test_ta_refresh_tries_next_original_uri_and_pins_exact_entity(self): # A controller unit test; genuine SPKI/crypto acceptance is covered by the remote RP smoke. capture = Capture.__new__(Capture) capture.archive, capture.root = self.archive, self.archive.root tal = Path(self.tmp.name) / "test.tal" tal.write_text("https://ta.example/unavailable.cer\nhttps://ta.example/current.cer\n\nunit-input\n") destination = Path(self.tmp.name) / "ta" destination.mkdir() ref = self.archive.put_stream(io.BytesIO(b"exact downloaded TA bytes")) calls = [] def download(uri, kind, previous=None, source="poller"): calls.append(uri) return self.archive.event({"source": source, "transport": "http", "kind": kind, "uri": uri, "started_ms": now_ms(), "complete": len(calls) == 2, "body": ref}) capture.archive.fetch = download result = capture.refresh_ta(tal, destination) self.assertEqual(calls, ["https://ta.example/unavailable.cer", "https://ta.example/current.cer"]) self.assertEqual(Path(result["path"]).read_bytes(), b"exact downloaded TA bytes") self.assertEqual(result["sha256"], ref["sha256"]) def test_dtd_and_duplicate_snapshot_objects_rejected(self): for body in (b']>', xml("snapshot", 1, publish(OBJECT, b"a") + publish(OBJECT, b"b"))): ref = self.archive.put_stream(io.BytesIO(body)) with self.assertRaises(ValueError): payload_view(self.archive.blob_path(ref["sha256"]), "snapshot", SESSION, 1) def test_blob_path_traversal_and_size_guard(self): with self.assertRaises(ValueError): self.archive.blob_path("../escape") small = Archive(Path(self.tmp.name) / "small", {"max_body_bytes": 2}) with self.assertRaises(ValueError): small.put_stream(io.BytesIO(b"large")) self.assertFalse(list((small.root / "partial").iterdir())) if __name__ == "__main__": unittest.main()