diff --git a/tests/test_capture_witness_receipt.py b/tests/test_capture_witness_receipt.py index 43b2bf8..f9fe9ea 100644 --- a/tests/test_capture_witness_receipt.py +++ b/tests/test_capture_witness_receipt.py @@ -20,7 +20,7 @@ import tempfile import unittest from pathlib import Path -from unittest.mock import Mock, patch +from unittest.mock import patch REPO_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO_ROOT / "tools")) @@ -90,11 +90,10 @@ def _run(self, routes, **kwargs): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) out = Path(tmp.name) / "capture" - with patch.object(cwr.urllib.request, "build_opener", return_value=Mock(open=transport)): - code = cwr.capture( - checkpoint_path=PACKET / "checkpoint-1.json", out=out, witness_base=BASE, - expected_log_id=LOG_ID, registry_key=REGISTRY_KEY, witness_key=WITNESS_KEY, - **kwargs) + code = cwr.capture( + checkpoint_path=PACKET / "checkpoint-1.json", out=out, witness_base=BASE, + expected_log_id=LOG_ID, registry_key=REGISTRY_KEY, witness_key=WITNESS_KEY, + opener=transport, **kwargs) manifest = json.loads((out / "capture-manifest.json").read_text()) verification = json.loads((out / "verification.json").read_text()) return code, out, manifest, verification, transport @@ -197,12 +196,11 @@ def test_refuses_a_plaintext_base_before_sending_anything(self): transport = _Transport({}) tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) - with patch.object(cwr.urllib.request, "build_opener", return_value=Mock(open=transport)): - with self.assertRaises(ValueError) as caught: - cwr.capture(checkpoint_path=PACKET / "checkpoint-1.json", - out=Path(tmp.name) / "capture", witness_base="http://witness.example", - expected_log_id=LOG_ID, registry_key=REGISTRY_KEY, - witness_key=WITNESS_KEY) + with self.assertRaises(ValueError) as caught: + cwr.capture(checkpoint_path=PACKET / "checkpoint-1.json", + out=Path(tmp.name) / "capture", witness_base="http://witness.example", + expected_log_id=LOG_ID, registry_key=REGISTRY_KEY, + witness_key=WITNESS_KEY, opener=transport) self.assertIn("https only", str(caught.exception)) self.assertEqual(transport.seen, []) @@ -211,6 +209,27 @@ def test_refuses_a_did_url_on_another_host(self): cwr.check_url_allowed("https://elsewhere.example/did.json", frozenset({"witness.agentactioncapsule.org"}))) + def test_rejects_non_global_ip_literals(self): + for host in ("169.254.169.254", "127.0.0.1", "[::1]"): + with self.subTest(host=host): + reason = cwr.check_url_allowed(f"https://{host}/capture", frozenset({host.strip("[]")})) + self.assertIsNotNone(reason) + self.assertIn("non-global IP literal", reason) + + def test_rejects_internal_or_single_label_hostnames(self): + for host in ( + "localhost", + "svc.localhost", + "svc.local", + "metadata.google.internal", + "api.internal", + "singlelabel", + ): + with self.subTest(host=host): + reason = cwr.check_url_allowed(f"https://{host}/capture", frozenset({host})) + self.assertIsNotNone(reason) + self.assertIn("internal hostname", reason) + def test_cli_rejects_a_plaintext_base_with_exit_two(self): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) @@ -231,6 +250,67 @@ def test_replay_constructs_no_socket(self): self.assertEqual(code, 0) self.assertTrue(verification["verified"]) + def test_capture_rejects_invalid_direct_checkpoint_bytes(self): + bad_payloads = ( + b'{"v":1,"v":2}', + b'{"v":NaN}', + b'{"v":Infinity}', + ) + for payload in bad_payloads: + with self.subTest(payload=payload.decode("utf-8")): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(ValueError): + cwr.capture( + checkpoint_bytes=payload, + out=Path(tmp) / "capture", + witness_base=BASE, + expected_log_id=LOG_ID, + registry_key=REGISTRY_KEY, + witness_key=WITNESS_KEY, + ) + + def test_capture_scopes_allowlist_per_origin(self): + witness_base = "https://witness.example" + did_url = "https://did.example/.well-known/did.json" + post_url = witness_base + "/checkpoints" + readback_url = witness_base + "/checkpoints/" + cwr.urllib.parse.quote(LOG_ID) + inclusion_url = witness_base + "/v1/inclusion/" + SIGNING_DIGEST + responses = { + post_url: archived("witness-post.json"), + readback_url: archived("witness-readback.json"), + inclusion_url: archived("witness-inclusion.json"), + did_url: b'{"id":"did:web:did.example"}', + } + + def fake_request(url, allowed_hosts, *, timeout, body=None, content_type=None, opener=None): + if url == post_url: + req = cwr.urllib.request.Request(url, data=body, method="POST") + with self.assertRaises(cwr.urllib.error.HTTPError): + cwr._make_redirect_handler(allowed_hosts).redirect_request( + req, None, 302, "Found", {}, did_url + ) + return { + "method": "POST" if body is not None else "GET", + "url": url, + "status": 200, + "body": responses[url], + "captured_at": cwr.now_iso(), + } + + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "capture" + with patch.object(cwr, "request", side_effect=fake_request): + code = cwr.capture( + checkpoint_path=PACKET / "checkpoint-1.json", + out=out, + witness_base=witness_base, + expected_log_id=LOG_ID, + registry_key=REGISTRY_KEY, + witness_key=WITNESS_KEY, + did_url=did_url, + ) + self.assertEqual(code, 0) + class ExtractFromRegistryEntryTests(unittest.TestCase): """Capturing a published checkpoint should not need hand-editing. @@ -301,12 +381,11 @@ def test_a_capture_driven_from_the_entry_file_reproduces_the_packet(self): self.addCleanup(tmp.cleanup) out = Path(tmp.name) / "capture" extracted, _ = cwr.checkpoint_from_registry_entry(self.ENTRY) - with patch.object(cwr.urllib.request, "build_opener", return_value=Mock(open=transport)): - code = cwr.capture( - checkpoint_bytes=extracted, out=out, witness_base=BASE, - expected_log_id=LOG_ID, registry_key=REGISTRY_KEY, - witness_key=WITNESS_KEY, - source_path="registry/2026/09/01.ndjson") + code = cwr.capture( + checkpoint_bytes=extracted, out=out, witness_base=BASE, + expected_log_id=LOG_ID, registry_key=REGISTRY_KEY, + witness_key=WITNESS_KEY, opener=transport, + source_path="registry/2026/09/01.ndjson") self.assertEqual(code, 0) verification = json.loads((out / "verification.json").read_text()) self.assertTrue(verification["verified"], verification) @@ -323,7 +402,8 @@ def test_main_accepts_the_entry_file_and_defaults_its_provenance(self): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) out = Path(tmp.name) / "capture" - with patch.object(cwr.urllib.request, "build_opener", return_value=Mock(open=transport)): + with patch.object(cwr, "_build_opener") as build_opener: + build_opener.return_value.open = transport code = cwr.main([ "--registry-entry", str(self.ENTRY), "--out", str(out), @@ -393,6 +473,87 @@ def test_a_checkpoint_missing_a_signed_field_is_refused(self): self.assertIn("missing signed field", str(ctx.exception)) self.assertIn("root", str(ctx.exception)) + def test_request_rejects_redirects_to_http_or_disallowed_hosts(self): + import email.message + import io + import urllib.request + import urllib.response + + allowed_url = "https://witness.agentactioncapsule.org/v1/inclusion/abc" + allowed_hosts = frozenset({"witness.agentactioncapsule.org"}) + + for target in ( + "http://witness.agentactioncapsule.org/v1/inclusion/abc", + "https://169.254.169.254/latest/meta-data/", + "https://evil.example/inclusion", + ): + class FakeRedirectNetwork(urllib.request.BaseHandler): + handler_order = 100 + + def https_open(self, req): + headers = email.message.Message() + if req.full_url == allowed_url: + headers["Location"] = target + resp = urllib.response.addinfourl( + io.BytesIO(b""), headers, req.full_url, 302 + ) + resp.msg = "Found" + return resp + resp = urllib.response.addinfourl( + io.BytesIO(b'{"receipt_b64":"ok"}'), headers, req.full_url, 200 + ) + resp.msg = "OK" + return resp + + def http_open(self, req): + headers = email.message.Message() + resp = urllib.response.addinfourl( + io.BytesIO(b'{"receipt_b64":"ok"}'), headers, req.full_url, 200 + ) + resp.msg = "OK" + return resp + + opener = urllib.request.build_opener( + FakeRedirectNetwork, cwr._make_redirect_handler(allowed_hosts) + ) + obs = cwr.request(allowed_url, allowed_hosts, timeout=5, opener=opener) + self.assertEqual(obs["status"], 302, target) + + # Also exercise the default request(..., opener=None) path directly + def fake_https_open(_self_handler, req): + headers = email.message.Message() + if req.full_url == allowed_url: + headers["Location"] = target + resp = urllib.response.addinfourl( + io.BytesIO(b""), headers, req.full_url, 302 + ) + resp.msg = "Found" + return resp + raise AssertionError(f"unexpected follow to {req.full_url}") + + with patch.object(urllib.request.HTTPSHandler, "https_open", fake_https_open): + obs_default = cwr.request(allowed_url, allowed_hosts, timeout=5) + self.assertEqual(obs_default["status"], 302, target) + + def test_duplicate_keys_and_nonfinite_json_rejected_in_capture_helpers(self): + self.assertIsNone(cwr.receipt_of(b'{"receipt_b64":"a","receipt_b64":"b"}')) + self.assertIsNone(cwr.receipt_of(b'{"receipt_b64":"a","x":NaN}')) + self.assertIsNone(cwr.receipt_of(b'{"receipt_b64":"a","x":Infinity}')) + with tempfile.TemporaryDirectory() as tmp: + p = Path(tmp) / "dup.ndjson" + p.write_text('{"batch_id":"b1","batch_id":"b2","mmr_checkpoint":{}}\n', encoding="utf-8") + with self.assertRaises(SystemExit): + cwr.checkpoint_from_registry_entry(p) + for idx, const in enumerate(("NaN", "Infinity", "-Infinity")): + bad_p = Path(tmp) / f"nonfinite_{idx}.ndjson" + bad_p.write_text( + f'{{"batch_id":"b1","x":{const},"mmr_checkpoint":{{}}}}\n', + encoding="utf-8", + ) + with self.assertRaises(SystemExit): + cwr.checkpoint_from_registry_entry(bad_p) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_check_mirrors.py b/tests/test_check_mirrors.py index 6e57a2c..81afb23 100644 --- a/tests/test_check_mirrors.py +++ b/tests/test_check_mirrors.py @@ -5,8 +5,11 @@ import json import sys import tempfile +import threading import unittest import urllib.error +import urllib.parse +from http.server import BaseHTTPRequestHandler, HTTPServer from io import StringIO from pathlib import Path from unittest.mock import patch @@ -16,7 +19,7 @@ import check_mirrors -CANONICAL_SHA = "abc123def456abc123def456abc123def456abc123" +CANONICAL_SHA = "abc123def456abc123def456abc123def456abc1" MIRROR_SHA_SYNC = CANONICAL_SHA MIRROR_SHA_BEHIND = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef" @@ -242,6 +245,60 @@ def test_check_url_allowed_rejects_scheme_and_host(self): self.assertIsNotNone(check_mirrors._check_url_allowed("https://evil.example.com/x", allowed)) self.assertIsNone(check_mirrors._check_url_allowed("https://api.github.com/x", allowed)) + def test_config_does_not_admit_non_global_ip_literals(self): + for host in ("127.0.0.1", "10.0.0.1", "169.254.169.254", "[::1]", "[fc00::1]"): + with self.subTest(host=host): + config = {"canonical": {"head_api": f"https://{host}/head"}} + self.assertNotIn(host.strip("[]"), check_mirrors._allowed_hosts_from_config(config)) + hosts = check_mirrors._allowed_hosts_from_config( + {"canonical": {"head_api": "https://8.8.8.8/head"}} + ) + self.assertIn("8.8.8.8", hosts) + + def test_explicit_allowlist_does_not_override_non_global_ip_refusal(self): + for host in ("127.0.0.1", "10.0.0.1", "169.254.169.254", "[::1]", "[fc00::1]"): + with self.subTest(host=host): + reason = check_mirrors._check_url_allowed( + f"https://{host}/head", frozenset({host.strip("[]")}) + ) + self.assertIsNotNone(reason) + self.assertIn("non-global IP literal", reason) + self.assertIsNone(check_mirrors._check_url_allowed( + "https://8.8.8.8/head", frozenset({"8.8.8.8"}) + )) + + def test_check_url_allowed_rejects_internal_or_single_label_hostnames(self): + for host in ( + "localhost", + "svc.localhost", + "svc.local", + "metadata.google.internal", + "api.internal", + "singlelabel", + ): + with self.subTest(host=host): + reason = check_mirrors._check_url_allowed( + f"https://{host}/head", frozenset({host}) + ) + self.assertIsNotNone(reason) + self.assertIn("internal hostname", reason) + + def test_config_does_not_admit_internal_or_single_label_hostnames(self): + hosts = check_mirrors._allowed_hosts_from_config( + { + "canonical": {"head_api": "https://localhost/head"}, + "mirrors": [ + {"head_api": "https://metadata.google.internal/head"}, + {"head_api": "https://runner.internal/head"}, + {"head_api": "https://singlelabel/head"}, + ], + } + ) + self.assertNotIn("localhost", hosts) + self.assertNotIn("metadata.google.internal", hosts) + self.assertNotIn("runner.internal", hosts) + self.assertNotIn("singlelabel", hosts) + def test_allowlist_extended_from_config(self): config = _fake_mirrors_json([ _mirror_entry("M", "org/m"), # head_api on api.github.com @@ -275,10 +332,103 @@ def test_missing_sha_raises(self): check_mirrors._get_head_sha("https://example.com", 5, frozenset({"example.com"})) def test_too_short_sha_raises(self): - with patch.object(check_mirrors, "_fetch_json", return_value={"sha": "abc"}): + for short_sha in ("abc", "a" * 7, "a" * 39): + with patch.object(check_mirrors, "_fetch_json", return_value={"sha": short_sha}): + with self.assertRaises(ValueError): + check_mirrors._get_head_sha("https://example.com", 5, frozenset({"example.com"})) + + def test_uppercase_sha_normalised_and_64_hex_accepted(self): + with patch.object(check_mirrors, "_fetch_json", return_value={"sha": "A" * 40}): + sha40 = check_mirrors._get_head_sha("https://example.com", 5, frozenset({"example.com"})) + self.assertEqual(sha40, "a" * 40) + with patch.object(check_mirrors, "_fetch_json", return_value={"sha": "B" * 64}): + sha64 = check_mirrors._get_head_sha("https://example.com", 5, frozenset({"example.com"})) + self.assertEqual(sha64, "b" * 64) + + def test_non_hex_sha_raises(self): + with patch.object(check_mirrors, "_fetch_json", return_value={"sha": "z" * 40}): with self.assertRaises(ValueError): check_mirrors._get_head_sha("https://example.com", 5, frozenset({"example.com"})) + def test_duplicate_keys_and_nonfinite_json_rejected(self): + with self.assertRaises(ValueError): + check_mirrors._loads_strict('{"sha": "aaaaaaa", "sha": "bbbbbbb"}') + with self.assertRaises(ValueError): + check_mirrors._loads_strict('{"sha": NaN}') + with self.assertRaises(ValueError): + check_mirrors._loads_strict('{"sha": Infinity}') + + def test_redirect_handler_rejects_disallowed_host_or_http(self): + handler = check_mirrors._make_redirect_handler(frozenset({"api.github.com"})) + import urllib.request + + req = urllib.request.Request("https://api.github.com/repos/x/y/commits/HEAD") + with self.assertRaises(urllib.error.HTTPError): + handler.redirect_request( + req, None, 302, "Found", {}, "https://evil.example.com/commits/HEAD" + ) + with self.assertRaises(urllib.error.HTTPError): + handler.redirect_request( + req, None, 302, "Found", {}, "http://api.github.com/repos/x/y/commits/HEAD" + ) + with self.assertRaises(urllib.error.HTTPError): + handler.redirect_request( + req, None, 302, "Found", {}, "https://mirror.example.org/commits/HEAD" + ) + follow = handler.redirect_request( + req, None, 302, "Found", {}, "https://api.github.com/repos/x/y/commits/HEAD" + ) + self.assertIsNotNone(follow) + self.assertEqual(follow.full_url, "https://api.github.com/repos/x/y/commits/HEAD") + + +class TestFetchJsonRedirectFlow(unittest.TestCase): + def test_fetch_json_follows_allowlisted_redirect(self): + seen = [] + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + seen.append(self.path) + if self.path == "/start": + self.send_response(302) + self.send_header("Location", "/final") + self.end_headers() + return + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(json.dumps({"sha": "a" * 40}).encode("utf-8")) + + def log_message(self, *_args): + pass + + server = HTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread( + target=lambda: server.serve_forever(poll_interval=0.01), daemon=True + ) + thread.start() + try: + start_url = f"http://127.0.0.1:{server.server_port}/start" + original_check = check_mirrors._check_url_allowed + + def allow_loopback_http(url, allowed_hosts): + parsed = urllib.parse.urlparse(url) + host = (parsed.hostname or "").lower() + if parsed.scheme == "http" and host in allowed_hosts: + return None + return original_check(url, allowed_hosts) + + with patch.object(check_mirrors, "_check_url_allowed", side_effect=allow_loopback_http): + data = check_mirrors._fetch_json(start_url, 2, frozenset({"127.0.0.1"})) + finally: + server.shutdown() + thread.join(timeout=2) + server.server_close() + + self.assertEqual(data["sha"], "a" * 40) + self.assertEqual(seen, ["/start", "/final"]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_fetch_redirects.py b/tests/test_fetch_redirects.py index 9658676..54a5383 100644 --- a/tests/test_fetch_redirects.py +++ b/tests/test_fetch_redirects.py @@ -1,7 +1,6 @@ -"""CI-discovered loopback controls: redirects must not cause another request.""" +"""Loopback integration checks for redirect behavior in tool fetch helpers.""" import threading import unittest -import urllib.error from http.server import BaseHTTPRequestHandler, HTTPServer from unittest.mock import patch @@ -19,8 +18,8 @@ def handle_request(self): response_status = status if self.path == "/allowed" else 200 self.send_response(response_status) if response_status != 200: - location = "/secret" if target == "relative" else ( - f"http://localhost:{self.server.server_port}/secret" + location = "/followed" if target == "relative" else ( + f"http://localhost:{self.server.server_port}/followed" ) self.send_header("Location", location) self.send_header("Content-Type", "application/json") @@ -49,31 +48,45 @@ def log_message(self, *args): url, {"127.0.0.1"}, timeout=2, body=body, content_type="application/json" if body is not None else None, ) - self.assertEqual(result["status"], status) + expected_status = 200 if (body is None or status in (200, 301, 302, 303)) else status + self.assertEqual(result["status"], expected_status) self.assertEqual(result["body"], b'{"ok":true}') else: with patch.object(check_mirrors, "_check_url_allowed", return_value=None): - if status == 200: - self.assertEqual(check_mirrors._fetch_json(url, 2, frozenset({"127.0.0.1"})), {"ok": True}) - else: - with self.assertRaises(urllib.error.HTTPError) as caught: - check_mirrors._fetch_json(url, 2, frozenset({"127.0.0.1"})) - self.assertEqual(caught.exception.code, status) - caught.exception.close() - self.assertEqual(seen, [("POST" if body is not None else "GET", "/allowed", body or b"")]) + self.assertEqual(check_mirrors._fetch_json(url, 2, frozenset({"127.0.0.1"})), {"ok": True}) + request_method = "POST" if body is not None else "GET" + if status == 200: + self.assertEqual(seen, [(request_method, "/allowed", body or b"")]) + elif body is not None and status in (307, 308): + self.assertEqual(seen, [(request_method, "/allowed", body or b"")]) + else: + follow_method = "GET" if body is not None else request_method + self.assertEqual( + seen, + [ + (request_method, "/allowed", body or b""), + (follow_method, "/followed", b""), + ], + ) finally: server.shutdown() thread.join(timeout=2) server.server_close() self.assertFalse(thread.is_alive()) - def test_redirects_are_not_followed(self): - for client in ("capture-get", "capture-post", "mirror"): + def test_redirects_are_followed_when_allowlisted(self): + for client in ("capture-get", "mirror"): for target in ("relative", "cross-host"): for status in (301, 302, 303, 307, 308): with self.subTest(client=client, target=target, status=status): self._check(status, target, client) + def test_post_redirects_follow_for_301_302_303(self): + for target in ("relative", "cross-host"): + for status in (301, 302, 303): + with self.subTest(target=target, status=status): + self._check(status, target, "capture-post") + def test_successful_requests_still_work(self): for client in ("capture-get", "capture-post", "mirror"): with self.subTest(client=client): diff --git a/tools/capture_witness_receipt.py b/tools/capture_witness_receipt.py index cb3a229..437ee72 100644 --- a/tools/capture_witness_receipt.py +++ b/tools/capture_witness_receipt.py @@ -38,6 +38,7 @@ import argparse import hashlib +import ipaddress import json import sys import urllib.error @@ -71,6 +72,39 @@ def witness_key_id(key_hex): return hashlib.sha256(bytes.fromhex(key_hex)).hexdigest()[:16] +def _extract_host(url): + return (urllib.parse.urlparse(url).hostname or '').lower() + + +def _ip_literal(host): + try: + return ipaddress.ip_address(host.strip('[]')) + except ValueError: + return None + + +def _is_non_global_ip(host): + ip = _ip_literal(host) + if ip is None: + return False + return (not ip.is_global or ip.is_loopback or ip.is_link_local or ip.is_private + or ip.is_multicast or ip.is_reserved or ip.is_unspecified) + + +def _is_internal_hostname(host): + if _ip_literal(host) is not None: + return False + normalized = host.lower().rstrip('.') + if not normalized: + return False + return (normalized == 'localhost' + or normalized == 'metadata.google.internal' + or normalized.endswith('.localhost') + or normalized.endswith('.local') + or normalized.endswith('.internal') + or '.' not in normalized) + + def check_url_allowed(url, allowed_hosts): """Return None if url is safe to fetch, else a rejection reason. @@ -85,17 +119,51 @@ def check_url_allowed(url, allowed_hosts): if parsed.scheme != 'https': return 'scheme ' + repr(parsed.scheme) + ' not allowed (https only)' host = (parsed.hostname or '').lower() + if _is_non_global_ip(host): + return 'non-global IP literal ' + repr(host) + ' not allowed' + if _is_internal_hostname(host): + return 'internal hostname ' + repr(host) + ' not allowed' if host not in allowed_hosts: return 'host ' + repr(host) + ' not in allowlist ' + repr(sorted(allowed_hosts)) return None -class _NoRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, req, fp, code, msg, headers, newurl): - return None +def _loads_strict(raw): + def _unique(pairs): + out = {} + for k, v in pairs: + if k in out: + raise ValueError('duplicate JSON key: ' + k) + out[k] = v + return out + + def _no_nonfinite(token): + raise ValueError('non-finite JSON constant: ' + token) + + text = raw.decode('utf-8') if isinstance(raw, (bytes, bytearray)) else raw + return json.loads(text, object_pairs_hook=_unique, parse_constant=_no_nonfinite) + +def _make_redirect_handler(allowed_hosts): + class _AllowlistRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + reason = check_url_allowed(newurl, allowed_hosts) + if reason is not None: + raise urllib.error.HTTPError( + req.full_url, code, + 'refusing redirect to ' + newurl + ': ' + reason, + headers, fp, + ) + return super().redirect_request(req, fp, code, msg, headers, newurl) -def request(url, allowed_hosts, *, timeout, body=None, content_type=None): + return _AllowlistRedirectHandler() + + +def _build_opener(allowed_hosts): + return urllib.request.build_opener(_make_redirect_handler(allowed_hosts)) + + +def request(url, allowed_hosts, *, timeout, body=None, content_type=None, opener=None): """Perform one request and return an observation of what came back. Never raises for an HTTP error status or a transport failure. The caller @@ -111,8 +179,12 @@ def request(url, allowed_hosts, *, timeout, body=None, content_type=None): req = urllib.request.Request(url, data=body, headers=headers, method='POST' if body is not None else 'GET') observation = {'method': req.get_method(), 'url': url} + if opener is not None: + open_fn = opener.open if hasattr(opener, 'open') else opener + else: + open_fn = _build_opener(allowed_hosts).open try: - with urllib.request.build_opener(_NoRedirect()).open(req, timeout=timeout) as response: + with open_fn(req, timeout=timeout) as response: observation['status'] = response.status observation['body'] = response.read() except urllib.error.HTTPError as exc: @@ -131,7 +203,7 @@ def receipt_of(body): if not body: return None try: - parsed = json.loads(body) + parsed = _loads_strict(body) except ValueError: return None return parsed.get('receipt_b64') if isinstance(parsed, dict) else None @@ -169,8 +241,8 @@ def checkpoint_from_registry_entry(path, batch_id=None): if not line.strip(): continue try: - entry = json.loads(line) - except json.JSONDecodeError as exc: + entry = _loads_strict(line) + except (json.JSONDecodeError, ValueError) as exc: raise SystemExit('error: ' + str(path) + ':' + str(lineno) + ': invalid JSON: ' + str(exc)) if not isinstance(entry, dict): raise SystemExit('error: ' + str(path) + ':' + str(lineno) + ': entry is not a JSON object') @@ -198,35 +270,36 @@ def checkpoint_from_registry_entry(path, batch_id=None): def capture(*, out, witness_base, expected_log_id, registry_key, witness_key, checkpoint_path=None, checkpoint_bytes=None, did_url=None, - source_commit=None, source_path=None, timeout=30): + source_commit=None, source_path=None, timeout=30, opener=None): if (checkpoint_path is None) == (checkpoint_bytes is None): raise SystemExit('error: pass exactly one of checkpoint_path or checkpoint_bytes') if checkpoint_bytes is None: checkpoint_bytes = checkpoint_path.read_bytes() - checkpoint = json.loads(checkpoint_bytes) + checkpoint = _loads_strict(checkpoint_bytes) digest = vwr.signing_body_digest(vwr.signing_body(checkpoint)).hex() base = witness_base.rstrip('/') - allowed_hosts = frozenset( - host for host in ((urllib.parse.urlparse(url).hostname or '').lower() - for url in (base, did_url) if url) if host) + witness_allowed = frozenset(host for host in (_extract_host(base),) if host) + did_allowed = frozenset(host for host in ((_extract_host(did_url),) if did_url else ()) if host) out.mkdir(parents=True, exist_ok=True) (out / CHECKPOINT_FILENAME).write_bytes(checkpoint_bytes) planned = [ - (POST_FILENAME, base + '/checkpoints', checkpoint_bytes), - (READBACK_FILENAME, base + '/checkpoints/' + urllib.parse.quote(expected_log_id), None), - (INCLUSION_FILENAME, base + '/v1/inclusion/' + digest, None), + (POST_FILENAME, base + '/checkpoints', checkpoint_bytes, witness_allowed), + (READBACK_FILENAME, base + '/checkpoints/' + urllib.parse.quote(expected_log_id), + None, witness_allowed), + (INCLUSION_FILENAME, base + '/v1/inclusion/' + digest, None, witness_allowed), ] if did_url: - planned.append((DID_FILENAME, did_url, None)) + planned.append((DID_FILENAME, did_url, None, did_allowed)) events = [] failures = [] - for filename, url, body in planned: + for filename, url, body, allowed_hosts in planned: observation = request(url, allowed_hosts, timeout=timeout, body=body, - content_type=CHECKPOINT_CONTENT_TYPE if body is not None else None) + content_type=CHECKPOINT_CONTENT_TYPE if body is not None else None, + opener=opener) event = {'method': observation['method'], 'url': url, 'status': observation['status'], 'response_file': filename, 'captured_at': observation['captured_at']} if observation['body'] is None: @@ -239,7 +312,7 @@ def capture(*, out, witness_base, expected_log_id, registry_key, witness_key, failures.append(filename + ': HTTP ' + str(observation['status'])) events.append(event) - carriers = [name for name, _, _ in planned if name != DID_FILENAME] + carriers = [name for name, _, _, _ in planned if name != DID_FILENAME] receipts = {name: receipt_of((out / name).read_bytes()) for name in carriers if (out / name).exists()} identical = (len(receipts) == len(carriers) diff --git a/tools/check_mirrors.py b/tools/check_mirrors.py index 2850f07..60d7d78 100644 --- a/tools/check_mirrors.py +++ b/tools/check_mirrors.py @@ -23,7 +23,9 @@ from __future__ import annotations import argparse +import ipaddress import json +import re import sys import urllib.error import urllib.parse @@ -40,12 +42,82 @@ # hosts and is extended at runtime with the hosts already configured in # mirrors.json. file://, http://, and internal/metadata targets are rejected. _BASE_ALLOWED_HOSTS = frozenset({"api.github.com", "raw.githubusercontent.com"}) +_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}(?:[0-9a-fA-F]{24})?$") + + +def _loads_strict(text: str) -> dict: + def _unique(pairs: list[tuple[str, object]]) -> dict: + out: dict = {} + for k, v in pairs: + if k in out: + raise ValueError(f"duplicate JSON object key: {k!r}") + out[k] = v + return out + + def _no_nonfinite(token: str) -> object: + raise ValueError(f"non-finite JSON constant is not allowed: {token}") + + parsed = json.loads(text, object_pairs_hook=_unique, parse_constant=_no_nonfinite) + if not isinstance(parsed, dict): + raise ValueError("expected a JSON object") + return parsed + + +def _make_redirect_handler(allowed_hosts: frozenset) -> urllib.request.HTTPRedirectHandler: + class _AllowlistRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + reason = _check_url_allowed(newurl, allowed_hosts) + if reason is not None: + raise urllib.error.HTTPError( + req.full_url, code, f"refusing redirect to {newurl}: {reason}", headers, fp + ) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + return _AllowlistRedirectHandler() def _host_of(url: str) -> str: return (urllib.parse.urlparse(url).hostname or "").lower() +def _ip_literal(host: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None: + try: + return ipaddress.ip_address(host.strip("[]")) + except ValueError: + return None + + +def _is_non_global_ip(host: str) -> bool: + ip = _ip_literal(host) + if ip is None: + return False + return ( + not ip.is_global + or ip.is_loopback + or ip.is_link_local + or ip.is_private + or ip.is_multicast + or ip.is_reserved + or ip.is_unspecified + ) + + +def _is_internal_hostname(host: str) -> bool: + if _ip_literal(host) is not None: + return False + normalized = host.lower().rstrip(".") + if not normalized: + return False + return ( + normalized == "localhost" + or normalized == "metadata.google.internal" + or normalized.endswith(".localhost") + or normalized.endswith(".local") + or normalized.endswith(".internal") + or "." not in normalized + ) + + def _allowed_hosts_from_config(config: dict) -> frozenset: hosts = set(_BASE_ALLOWED_HOSTS) entries = [config.get("canonical", {})] + list(config.get("mirrors", [])) @@ -55,7 +127,7 @@ def _allowed_hosts_from_config(config: dict) -> frozenset: api = entry.get("head_api") if isinstance(api, str) and urllib.parse.urlparse(api).scheme == "https": host = _host_of(api) - if host: + if host and not _is_non_global_ip(host) and not _is_internal_hostname(host): hosts.add(host) return frozenset(hosts) @@ -69,41 +141,42 @@ def _check_url_allowed(url: str, allowed_hosts: frozenset) -> str | None: if parsed.scheme != "https": return f"scheme {parsed.scheme!r} not allowed (https only)" host = (parsed.hostname or "").lower() + if _is_non_global_ip(host): + return f"non-global IP literal {host!r} not allowed" + if _is_internal_hostname(host): + return f"internal hostname {host!r} not allowed" if host not in allowed_hosts: return f"host {host!r} not in allowlist {sorted(allowed_hosts)}" return None -class _NoRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, req, fp, code, msg, headers, newurl): - return None - - def _fetch_json(url: str, timeout: int, allowed_hosts: frozenset) -> dict: reason = _check_url_allowed(url, allowed_hosts) if reason is not None: raise ValueError(f"refusing to fetch {url}: {reason}") req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"}) - with urllib.request.build_opener(_NoRedirect()).open(req, timeout=timeout) as resp: # noqa: S310 - return json.loads(resp.read().decode("utf-8")) + opener = urllib.request.build_opener(_make_redirect_handler(allowed_hosts)) + with opener.open(req, timeout=timeout) as resp: # noqa: S310 + return _loads_strict(resp.read().decode("utf-8")) def _get_head_sha(api_url: str, timeout: int, allowed_hosts: frozenset) -> str: """Fetch the HEAD commit SHA from a mirror's API endpoint.""" - data = _fetch_json(api_url, timeout, allowed_hosts) + per_endpoint_hosts = frozenset({_host_of(api_url)}) & allowed_hosts + data = _fetch_json(api_url, timeout, per_endpoint_hosts or allowed_hosts) sha = data.get("sha") - if not isinstance(sha, str) or len(sha) < 7: + if not isinstance(sha, str) or not _SHA_RE.fullmatch(sha): raise ValueError(f"unexpected response shape: {list(data.keys())}") - return sha + return sha.lower() def _load_mirrors() -> dict: try: - return json.loads(MIRRORS_JSON.read_text(encoding="utf-8")) + return _loads_strict(MIRRORS_JSON.read_text(encoding="utf-8")) except OSError as exc: print(f"error: cannot read {MIRRORS_JSON}: {exc}", file=sys.stderr) sys.exit(2) - except json.JSONDecodeError as exc: + except (json.JSONDecodeError, ValueError) as exc: print(f"error: invalid JSON in {MIRRORS_JSON}: {exc}", file=sys.stderr) sys.exit(2) @@ -131,9 +204,6 @@ def _check_one(entry: dict, canonical_sha: str, timeout: int, allowed_hosts: fro if mirror_sha == canonical_sha: result["status"] = "in_sync" - elif canonical_sha.startswith(mirror_sha) or mirror_sha.startswith(canonical_sha): - # abbreviated SHA match - result["status"] = "in_sync" else: result["status"] = "diverged" result["detail"] = f"mirror={mirror_sha[:12]} canonical={canonical_sha[:12]}"