From 8f975c14f160fa7638a79d37a560f63ecddc498e Mon Sep 17 00:00:00 2001 From: dhonitheja Date: Sun, 22 Nov 2026 14:38:47 -0600 Subject: [PATCH 1/2] Verifiers: malformed FHIR or Stripe responses are unverified, not a crash Both verifiers treated only HTTPError, KeyError and ValueError as read errors but trusted the JSON shape, so a list where an object was expected, a string entry, or a non-string id or reference raised AttributeError or TypeError out of watch() and broke the agent's call (7 of 8 malformed FHIR shapes and 2 Stripe shapes crashed). Responses are now shape-checked where they are parsed and a wrong shape raises ValueError, which every caller already reports as unverified. Ported from the unmerged stripe-test-mode-mcp branch for Stripe, which also stops a repeating refund page after the second request instead of after MAX_PAGES. 17 new tests; each fails on the previous code. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++++++ CLAUDE.md | 2 +- README.md | 3 ++- agent_readback/verifiers/fhir.py | 34 ++++++++++++++++++++++++------ agent_readback/verifiers/stripe.py | 19 ++++++++++++++--- docs/ROADMAP.md | 2 +- tests/test_fhir_verifier.py | 31 +++++++++++++++++++++++++++ tests/test_stripe_sql_alerts.py | 30 ++++++++++++++++++++++++++ 8 files changed, 118 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f507e2..7c98b42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to `agent-readback`. Dates are UTC. ## Unreleased +### Fixed + +- 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, diff --git a/CLAUDE.md b/CLAUDE.md index 6acb7dd..b397133 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 `..`, 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 179) 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. diff --git a/README.md b/README.md index 8acc00c..e8249b9 100644 --- a/README.md +++ b/README.md @@ -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 server response | FHIR and Stripe responses are shape-checked where they are parsed (objects, lists, string ids and references); anything else is `unverified`, never a crash. A Stripe page that repeats stops after the second request | | 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` | @@ -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 179 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 diff --git a/agent_readback/verifiers/fhir.py b/agent_readback/verifiers/fhir.py index 48ea9c4..bd4b188 100644 --- a/agent_readback/verifiers/fhir.py +++ b/agent_readback/verifiers/fhir.py @@ -37,8 +37,24 @@ def normalize_instant(value: Any) -> Any: return parsed.astimezone(timezone.utc).isoformat() +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"), @@ -47,8 +63,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/"): @@ -74,11 +93,14 @@ 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"#{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")] + url = next((link["url"] for link in links if link.get("relation") == "next"), None) + if url is not None and not isinstance(url, str): + raise ValueError("malformed FHIR response: next link url is not a string") params = None if not url: break diff --git a/agent_readback/verifiers/stripe.py b/agent_readback/verifiers/stripe.py index ed022a8..64e3f34 100644 --- a/agent_readback/verifiers/stripe.py +++ b/agent_readback/verifiers/stripe.py @@ -65,15 +65,28 @@ 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 or not items: return found - params["starting_after"] = page["data"][-1]["id"] + 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: diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 7a597b1..7cc842d 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -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): 179 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). diff --git a/tests/test_fhir_verifier.py b/tests/test_fhir_verifier.py index 3229efc..0388d47 100644 --- a/tests/test_fhir_verifier.py +++ b/tests/test_fhir_verifier.py @@ -263,3 +263,34 @@ 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) diff --git a/tests/test_stripe_sql_alerts.py b/tests/test_stripe_sql_alerts.py index ca731ac..77251f5 100644 --- a/tests/test_stripe_sql_alerts.py +++ b/tests/test_stripe_sql_alerts.py @@ -397,3 +397,33 @@ 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 From 108a74cb3c7afdd6fc73fc13b7ce1d675adccfde Mon Sep 17 00:00:00 2001 From: dhonitheja Date: Sun, 22 Nov 2026 14:50:56 -0600 Subject: [PATCH 2/2] Never verify an incomplete read; tolerate timestamps with no UTC form CodeRabbit findings on #10, each confirmed before fixing: - A FHIR next link with a null or empty url ended the search as complete, so a duplicate on an unread page could still be verified. A next link we cannot follow is now a read error (unverified). - A Stripe page with has_more true and no refunds did the same; now unverified. - normalize_instant raised OverflowError for instants with no UTC form (year 1 at +01:00); the value is now left as is and shows as a mismatch. README row now promises only the shapes the code checks. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++++ CLAUDE.md | 2 +- README.md | 4 ++-- agent_readback/verifiers/fhir.py | 13 +++++++++---- agent_readback/verifiers/stripe.py | 4 +++- docs/ROADMAP.md | 2 +- tests/test_fhir_verifier.py | 29 +++++++++++++++++++++++++++++ tests/test_stripe_sql_alerts.py | 13 +++++++++++++ 8 files changed, 64 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c98b42..d80890a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ All notable changes to `agent-readback`. Dates are UTC. ### 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 diff --git a/CLAUDE.md b/CLAUDE.md index b397133..5736025 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 `..`, 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 179) 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. diff --git a/README.md b/README.md index e8249b9..7dc94dc 100644 --- a/README.md +++ b/README.md @@ -307,7 +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 server response | FHIR and Stripe responses are shape-checked where they are parsed (objects, lists, string ids and references); anything else is `unverified`, never a crash. A Stripe page that repeats stops after the second request | +| 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` | @@ -344,7 +344,7 @@ external security or compliance review has been done. ## What is tested and what is not -Version 0.3.0 plus unreleased fixes. All 179 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 diff --git a/agent_readback/verifiers/fhir.py b/agent_readback/verifiers/fhir.py index bd4b188..be0872e 100644 --- a/agent_readback/verifiers/fhir.py +++ b/agent_readback/verifiers/fhir.py @@ -34,7 +34,10 @@ 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]: @@ -98,9 +101,11 @@ def _appointments(self, patient: str) -> dict[str, dict[str, Any]]: flat = flatten_appointment(_object(entry, "Bundle.entry item")["resource"]) found[flat["id"] or f"#{len(found)}"] = flat # keep id-less entries distinct links = [_object(link, "Bundle.link item") for link in _array(bundle.get("link", []), "Bundle.link")] - url = next((link["url"] for link in links if link.get("relation") == "next"), None) - if url is not None and not isinstance(url, str): - raise ValueError("malformed FHIR response: next link url is not a string") + 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 diff --git a/agent_readback/verifiers/stripe.py b/agent_readback/verifiers/stripe.py index 64e3f34..63eec4f 100644 --- a/agent_readback/verifiers/stripe.py +++ b/agent_readback/verifiers/stripe.py @@ -80,8 +80,10 @@ def _refunds(self, payment_intent: str) -> dict[str, dict[str, Any]]: 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 has_more or not items: + if not has_more: return found + 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") diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 7cc842d..bc9c4fb 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -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-22, 0.3.0 plus unreleased fixes): 179 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). diff --git a/tests/test_fhir_verifier.py b/tests/test_fhir_verifier.py index 0388d47..13dae08 100644 --- a/tests/test_fhir_verifier.py +++ b/tests/test_fhir_verifier.py @@ -294,3 +294,32 @@ def test_malformed_fhir_read_by_id_is_unverified_not_a_crash(server, tools): 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"] diff --git a/tests/test_stripe_sql_alerts.py b/tests/test_stripe_sql_alerts.py index 77251f5..afea2a3 100644 --- a/tests/test_stripe_sql_alerts.py +++ b/tests/test_stripe_sql_alerts.py @@ -427,3 +427,16 @@ def handle(request): 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