Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 180 additions & 19 deletions tests/test_capture_witness_receipt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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, [])

Expand All @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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)
Expand All @@ -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),
Expand Down Expand Up @@ -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()
Loading
Loading