Skip to content
Merged
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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ All notable changes to `agent-readback`. Dates are UTC.

## Unreleased

### Fixed

- An incomplete read could be `verified`. A FHIR next link with a null or
empty URL, or a Stripe page with `has_more: true` and no refunds, ended the
read as if it were complete, so a duplicate booking or a double refund on an
unread page could pass. Both are now `unverified`.
- A timestamp with no UTC form (for example year 1 at `+01:00`) raised
`OverflowError`; it is now left as is and shows as a mismatch.
- A malformed FHIR or Stripe response (for example a list where an object is
expected, a string entry, or a non-string id or reference) made the verifier
raise `AttributeError` or `TypeError` out of `watch()`, breaking the agent's
call. Responses are now shape-checked where they are parsed and anything
malformed is `unverified`. A Stripe refund page that repeats now stops after
the second request instead of after `MAX_PAGES`.

### Documentation

- README reworked as a front page: quick start near the top, a results table,
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,5 @@ python -m pip install -e ".[security]" && python -m bandit -r agent_readback exa
- All HTTP goes through an injected `httpx.Client`; tests swap in `httpx.MockTransport`. Keep new verifiers and providers injectable the same way.
- New verifier: implement `snapshot`/`check` per `core.Verifier`, name actions `<system>.<resource>.<verb>`, export from `verifiers/__init__.py`, update the README verifier table.
- The verifier must use credentials the agent doesn't hold; a shared write path makes the check meaningless.
- The README's "What is tested and what is not" and "Security model" tables are kept honest. Update them (and the test count, currently 162) when coverage or guarantees change.
- The README's "What is tested and what is not" and "Security model" tables are kept honest. Update them (and the test count, currently 184) when coverage or guarantees change.
- Security changes need a test that demonstrates the attack failing (see `test_keyed_log_detects_a_chain_forged_without_the_key`), not just the happy path.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,7 @@ restricted key with `refunds: read`, a database role with `SELECT` only).
| Server-supplied paging link sends the verifier's token elsewhere | Each FHIR next link is resolved the way httpx will send it (so `//host/x` and similar forms count) and must stay on the client's scheme, host and port; anything else is `unverified` and is never requested |
| Evidence log overwritten by the dashboard | `readback dashboard` refuses an output path that is the log itself or any existing `.jsonl` |
| Hostile or broken server pages forever | FHIR and Stripe reads are page-capped; the result is `unverified`, not a hang |
| Malformed or incomplete server response | The FHIR and Stripe fields the verifiers read are shape-checked where they are parsed (objects, lists, string ids, references and next links); a wrong shape is `unverified`. A read that cannot be completed, such as a FHIR next link with no usable URL or a Stripe page that promises more but is empty, is `unverified`, never `verified`. A Stripe page that repeats stops after the second request; a timestamp with no UTC form shows as a mismatch |
| SQL injection via claim or config | Table and column names come from your code and are pattern-checked; the `placeholder` must be a DB-API paramstyle (`?`, `%s`, `:name`, `:1`, `$1`); values are always bound parameters |
| Verifier overloading the system of record | Opt-in `limit_reads(..., RateLimit(...))` caps every read; it only delays reads, and with `max_wait` an over-long wait is `unverified`, never `failed` (see [Rate limiting the verifier's reads](#rate-limiting-the-verifiers-reads)) |
| Unreadable system of record | `unverified`, never `verified` and never `failed` |
Expand Down Expand Up @@ -343,7 +344,7 @@ external security or compliance review has been done.

## What is tested and what is not

Version 0.3.0. All 162 offline tests pass with the optional test dependencies
Version 0.3.0 plus unreleased fixes. All 184 offline tests pass with the optional test dependencies
installed. A separate public HAPI FHIR R4 sandbox run verified 10 scripted
operations (6 bookings, 1 reschedule, 3 cancellations); this is a
compatibility smoke test, not production validation. A Stripe test-mode run
Expand Down
41 changes: 34 additions & 7 deletions agent_readback/verifiers/fhir.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,30 @@ def normalize_instant(value: Any) -> Any:
return value
if parsed.tzinfo is None:
return value # a time with no zone is ambiguous; leave it so it shows as a mismatch
return parsed.astimezone(timezone.utc).isoformat()
try:
return parsed.astimezone(timezone.utc).isoformat()
except OverflowError:
return value # e.g. year 1 at +01:00 has no UTC form; leave it so it shows as a mismatch


def _object(value: Any, what: str) -> dict[str, Any]:
# Server JSON is untrusted: a wrong shape is a read error (unverified), never a crash.
if not isinstance(value, dict):
raise ValueError(f"malformed FHIR response: {what} is not an object")
return value


def _array(value: Any, what: str) -> list[Any]:
if not isinstance(value, list):
raise ValueError(f"malformed FHIR response: {what} is not a list")
return value


def flatten_appointment(resource: dict[str, Any]) -> dict[str, Any]:
"""Reduce a FHIR Appointment to the flat fields a claim can assert on."""
resource = _object(resource, "Appointment")
if not isinstance(resource.get("id"), (str, type(None))):
raise ValueError("malformed FHIR response: Appointment.id is not a string")
flat: dict[str, Any] = {
"id": resource.get("id"),
"status": resource.get("status"),
Expand All @@ -47,8 +66,11 @@ def flatten_appointment(resource: dict[str, Any]) -> dict[str, Any]:
"patient": None,
"practitioner": None,
}
for participant in resource.get("participant", []):
reference = (participant.get("actor") or {}).get("reference", "")
for participant in _array(resource.get("participant", []), "Appointment.participant"):
actor = _object(_object(participant, "participant").get("actor") or {}, "participant.actor")
reference = actor.get("reference", "")
if not isinstance(reference, str):
raise ValueError("malformed FHIR response: actor.reference is not a string")
if reference.startswith("Patient/"):
flat["patient"] = reference
elif reference.startswith("Practitioner/"):
Expand All @@ -74,11 +96,16 @@ def _appointments(self, patient: str) -> dict[str, dict[str, Any]]:
# HAPI can reuse a pre-write search bundle for the same query.
response = self.client.get(url, params=params, headers={"Cache-Control": "no-cache"})
response.raise_for_status()
bundle = response.json()
for entry in bundle.get("entry", []):
flat = flatten_appointment(entry["resource"])
bundle = _object(response.json(), "search Bundle")
for entry in _array(bundle.get("entry", []), "Bundle.entry"):
flat = flatten_appointment(_object(entry, "Bundle.entry item")["resource"])
found[flat["id"] or f"<no-id>#{len(found)}"] = flat # keep id-less entries distinct
url = next((l["url"] for l in bundle.get("link", []) if l.get("relation") == "next"), None)
links = [_object(link, "Bundle.link item") for link in _array(bundle.get("link", []), "Bundle.link")]
nexts = [link for link in links if link.get("relation") == "next"]
url = nexts[0].get("url") if nexts else None
if nexts and (not isinstance(url, str) or not url):
# A next link we cannot follow means pages are unread: never treat that as complete.
raise ValueError("malformed FHIR response: next link has no usable url")
params = None
if not url:
break
Expand Down
21 changes: 18 additions & 3 deletions agent_readback/verifiers/stripe.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,30 @@ def __init__(self, client: httpx.Client) -> None:
def _refunds(self, payment_intent: str) -> dict[str, dict[str, Any]]:
found: dict[str, dict[str, Any]] = {}
params: dict[str, Any] = {"payment_intent": payment_intent, "limit": 100}
cursors: set[str] = set()
for _ in range(MAX_PAGES):
response = self.client.get("/v1/refunds", params=params)
response.raise_for_status()
# Server JSON is untrusted: a wrong shape is a read error (unverified), never a crash.
page = response.json()
for item in page.get("data", []):
if not isinstance(page, dict):
raise ValueError("malformed Stripe response: refund page is not an object")
items, has_more = page.get("data", []), page.get("has_more", False)
if not isinstance(items, list) or not isinstance(has_more, bool):
raise ValueError("malformed Stripe response: data is not a list or has_more is not a boolean")
for item in items:
if not isinstance(item, dict) or not isinstance(item.get("id"), str) or not item["id"]:
raise ValueError("malformed Stripe response: refund without a string id")
found[item["id"]] = {name: item.get(name) for name in FIELDS}
if not page.get("has_more") or not page.get("data"):
if not has_more:
return found
params["starting_after"] = page["data"][-1]["id"]
if not items: # more pages promised but no cursor to reach them: an incomplete read
raise ValueError("malformed Stripe response: has_more is true but the page is empty")
cursor = items[-1]["id"]
if cursor in cursors: # the server repeats a page: stop now, not after MAX_PAGES requests
raise ValueError("Stripe refund pagination did not advance")
cursors.add(cursor)
params["starting_after"] = cursor
raise ValueError(f"more than {MAX_PAGES} pages of refunds; refusing to continue")

def snapshot(self, claim: Claim) -> set[str] | None:
Expand Down
2 changes: 1 addition & 1 deletion docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,5 @@ infrastructure from the maintainer. Step 12 needs outside reviewers.
UNKEYED flagging and `--require-key`, dashboard overwrite guard, malformed
record handling, LF log endings, LangGraph example agent with Anthropic and
OpenAI models, `tzdata` on Windows.
- Verified locally (2026-11-21, 0.3.0): 162 tests pass on MCP 1.30 and on MCP 2.3, both with
- Verified locally (2026-11-22, 0.3.0 plus unreleased fixes): 184 tests pass on MCP 1.30 and on MCP 2.3, both with
LangGraph 1.2 (1 symlink test skips on Windows without symlink privileges).
60 changes: 60 additions & 0 deletions tests/test_fhir_verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,3 +263,63 @@ def handle(request):
with httpx.Client(transport=httpx.MockTransport(handle), base_url="https://fhir.test") as client:
result = FhirAppointmentVerifier(client).snapshot(create_claim())
assert result in (set(), None) # followed, or refused as unverified; never an exception


MALFORMED_BUNDLES = {
"bundle is a list": [],
"entry is a string": {"resourceType": "Bundle", "entry": "x"},
"entry item is a string": {"resourceType": "Bundle", "entry": ["x"]},
"resource is a string": {"resourceType": "Bundle", "entry": [{"resource": "x"}]},
"id is an object": {"resourceType": "Bundle", "entry": [{"resource": {"id": {"x": 1}}}]},
"participant is a string": {"resourceType": "Bundle", "entry": [{"resource": {"id": "a1", "participant": "x"}}]},
"actor reference is a number": {"resourceType": "Bundle", "entry": [{"resource": {"id": "a1", "participant": [{"actor": {"reference": 7}}]}}]},
"link is a string": {"resourceType": "Bundle", "entry": [], "link": "next"},
"link item is a string": {"resourceType": "Bundle", "entry": [], "link": ["next"]},
"next url is a number": {"resourceType": "Bundle", "entry": [], "link": [{"relation": "next", "url": 5}]},
}


@pytest.mark.parametrize("body", MALFORMED_BUNDLES.values(), ids=MALFORMED_BUNDLES.keys())
def test_malformed_fhir_search_is_unverified_not_a_crash(body):
transport = httpx.MockTransport(lambda request: httpx.Response(200, json=body))
with httpx.Client(transport=transport, base_url="https://fhir.test") as client:
verifier = FhirAppointmentVerifier(client)
assert verifier.snapshot(create_claim()) is None
assert verifier.check(create_claim(), set()).status is Status.UNVERIFIED


def test_malformed_fhir_read_by_id_is_unverified_not_a_crash(server, tools):
from agent_readback.verifiers.fhir import flatten_appointment

for bad in ([], "x", {"id": "a1", "participant": [42]}):
with pytest.raises(ValueError, match="malformed FHIR response"):
flatten_appointment(bad)


def _bundle_appointment(appointment_id, start=START):
return {"resource": {"resourceType": "Appointment", "id": appointment_id, "status": "booked", "start": start,
"end": END, "participant": [{"actor": {"reference": PATIENT}}, {"actor": {"reference": DOCTOR}}]}}


@pytest.mark.parametrize("next_link", [{"relation": "next", "url": None}, {"relation": "next", "url": ""}, {"relation": "next"}])
def test_next_link_without_a_usable_url_is_an_incomplete_read_not_verified(next_link):
# The duplicate booking would be on page 2; a next link we cannot follow must not end the search as complete.
pages = [{"resourceType": "Bundle", "entry": []},
{"resourceType": "Bundle", "entry": [_bundle_appointment("a1")], "link": [next_link]}]
transport = httpx.MockTransport(lambda request: httpx.Response(200, json=pages.pop(0) if len(pages) > 1 else pages[0]))
with httpx.Client(transport=transport, base_url="https://fhir.test") as client:
verifier = FhirAppointmentVerifier(client)
before = verifier.snapshot(create_claim())
assert before == set()
assert verifier.check(create_claim(), before).status is Status.UNVERIFIED


def test_timestamp_without_a_utc_form_is_a_mismatch_not_a_crash():
assert normalize_instant("0001-01-01T00:00:00+01:00") == "0001-01-01T00:00:00+01:00"
pages = [{"resourceType": "Bundle", "entry": []},
{"resourceType": "Bundle", "entry": [_bundle_appointment("a1", "0001-01-01T00:00:00+01:00")]}]
transport = httpx.MockTransport(lambda request: httpx.Response(200, json=pages.pop(0) if len(pages) > 1 else pages[0]))
with httpx.Client(transport=transport, base_url="https://fhir.test") as client:
verifier = FhirAppointmentVerifier(client)
verdict = verifier.check(create_claim(), verifier.snapshot(create_claim()))
assert verdict.status is Status.FAILED and [f.field for f in verdict.findings] == ["start"]
43 changes: 43 additions & 0 deletions tests/test_stripe_sql_alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,3 +397,46 @@ def sync_auth_flow(self, request):

transport = httpx.MockTransport(lambda request: httpx.Response(200, json={"data": [], "has_more": False}))
StripeRefundVerifier(httpx.Client(transport=transport, auth=CustomBasic("rk_live_x", "")))


MALFORMED_REFUND_PAGES = {
"page is a list": [],
"refund is a string": {"data": ["re_1"], "has_more": False},
"refund id is a number": {"data": [{"id": 7}], "has_more": False},
"has_more is a string": {"data": [], "has_more": "false"},
"data is an object": {"data": {"id": "re_1"}, "has_more": False},
}


@pytest.mark.parametrize("body", MALFORMED_REFUND_PAGES.values(), ids=MALFORMED_REFUND_PAGES.keys())
def test_malformed_stripe_page_is_unverified_not_a_crash(body):
transport = httpx.MockTransport(lambda request: httpx.Response(200, json=body))
with httpx.Client(transport=transport, base_url="https://stripe.test") as client:
verifier = StripeRefundVerifier(client)
assert verifier.snapshot(REFUND) is None
assert verifier.check(REFUND, set()).status is Status.UNVERIFIED


def test_stripe_snapshot_stops_when_pagination_repeats():
cursors = []

def handle(request):
cursors.append(request.url.params.get("starting_after"))
return httpx.Response(200, json={"data": [{"id": "re_1"}], "has_more": True})

with httpx.Client(transport=httpx.MockTransport(handle), base_url="https://stripe.test") as client:
assert StripeRefundVerifier(client).snapshot(REFUND) is None
assert cursors == [None, "re_1"] # two requests, not MAX_PAGES


def test_has_more_with_an_empty_page_is_an_incomplete_read_not_verified():
# A double refund could be on the page that was never read: that must not be verified.
refund = {"id": "re_1", "amount": REFUND.expected["amount"], "currency": REFUND.expected["currency"],
"status": "succeeded", "payment_intent": REFUND.expected["payment_intent"]}
pages = [{"data": [], "has_more": False}, {"data": [refund], "has_more": True}, {"data": [], "has_more": True}]
transport = httpx.MockTransport(lambda request: httpx.Response(200, json=pages.pop(0) if len(pages) > 1 else pages[0]))
with httpx.Client(transport=transport, base_url="https://stripe.test") as client:
verifier = StripeRefundVerifier(client)
before = verifier.snapshot(REFUND)
assert before == set()
assert verifier.check(REFUND, before).status is Status.UNVERIFIED
Loading