diff --git a/.gitignore b/.gitignore index e9a9428..e01a7d2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,5 @@ graphify-out/ .test-tmp*/ .test-python*/ .venv*/ +.claude-flow/ +.pytest-live-assessment*/ diff --git a/CHANGELOG.md b/CHANGELOG.md index d80890a..f5de10f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ All notable changes to `agent-readback`. Dates are UTC. -## Unreleased +## 0.3.1 — 2026-11-22 ### Fixed @@ -11,13 +11,28 @@ All notable changes to `agent-readback`. Dates are UTC. 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. + `OverflowError`; it is now compared as written, so it matches only an identical + string; the same instant written another way is a `wrong_value`. - 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`. +- A broken read could still be a false `failed`: + - A Stripe 200 response with no `data` list or no `has_more` (an error body, + a proxy page, `{}`) was read as "no refunds", so a real refund was + `failed`. Both fields are now required; otherwise the result is `unverified`. + - A FHIR 200 response that is not a Bundle (for example an + OperationOutcome) was read as an empty search. A search entry that is not + an Appointment, or a read by id that returns another resource type, was + counted as an appointment. These are now `unverified`. Entries with + `search.mode` `include` or `outcome` are skipped instead of counted. + - An Appointment with no id was keyed by its position in the read, so an + unchanged one could look new (a false `extra_effect`) or hide a new + duplicate. A missing or empty id is now `unverified`. + - A participant `actor` that was `[]`, `""` or another falsy non-object was + treated as absent, giving a `wrong_value` `failed`. It is now `unverified`. ### Documentation diff --git a/CLAUDE.md b/CLAUDE.md index 5736025..5d9d110 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## What this is -Readback (`agent-readback`, v0.3.0): checks an AI agent's "Done." claim against the system of record. Snapshot before the agent acts, re-read afterward through a read-only path, emit a deterministic verdict (`verified` / `failed` / `unverified`). Verdicts never come from an LLM. Only runtime dependency: `httpx`. +Readback (`agent-readback`, v0.3.1): checks an AI agent's "Done." claim against the system of record. Snapshot before the agent acts, re-read afterward through a read-only path, emit a deterministic verdict (`verified` / `failed` / `unverified`). Verdicts never come from an LLM. Only runtime dependency: `httpx`. ## Commands @@ -29,7 +29,7 @@ python -m pip install -e ".[security]" && python -m bandit -r agent_readback exa ## Architecture - `agent_readback/core.py` — the whole contract. `Claim` (action, agent_said, expected fields, context) → `Verifier` protocol (`snapshot(claim)` before, `check(claim, before)` after) → `Verdict` with `Finding`s of kind `missing` / `wrong_value` / `extra_effect` / `unreachable`. `watch()` context manager orchestrates: snapshot on enter with a `probe` claim, check in a `finally` on exit (runs even if the agent raises) with the final claim set via `w.claims(...)`, optional settle retries (only `FAILED` is retried, never `UNVERIFIED`), then appends to the log and fires `on_verdict` callbacks. -- `agent_readback/verifiers/` — FHIR Appointment (create/update/cancel), Stripe refund, SQL row. Shared pattern: snapshot captures prior state (existing IDs for FHIR/Stripe; row + row count for SQL), or `None` on read error; anything new that wasn't claimed becomes `extra_effect`; read errors yield `UNVERIFIED`, never `FAILED`; a `None` snapshot means `UNVERIFIED`. Field comparison goes through `compare_fields`. FHIR normalizes timestamps to UTC and deliberately leaves zoneless times unnormalized so they mismatch. FHIR and Stripe reads are page-capped (`MAX_PAGES`); overflow → `UNVERIFIED`. A matching `pending` Stripe refund is `UNVERIFIED` with a `PENDING` finding (a pending refund with a wrong field is `FAILED`). `core.recheck(verifier, verdict_or_dict, log)` re-judges only `UNVERIFIED` verdicts via the verifier's optional `recheck(claim, observed)` and tags `context["recheck_of"]`; Stripe judges only the refunds seen at the first check. +- `agent_readback/verifiers/` — FHIR Appointment (create/update/cancel), Stripe refund, SQL row. Shared pattern: snapshot captures prior state (existing IDs for FHIR/Stripe; row + row count for SQL), or `None` on read error; anything new that wasn't claimed becomes `extra_effect`; read errors yield `UNVERIFIED`, never `FAILED`; a `None` snapshot means `UNVERIFIED`. Field comparison goes through `compare_fields`. FHIR normalizes timestamps to UTC; zoneless times and instants with no UTC form are left unnormalized and compared as written (only identical text matches). FHIR and Stripe reads are page-capped (`MAX_PAGES`); overflow → `UNVERIFIED`. A matching `pending` Stripe refund is `UNVERIFIED` with a `PENDING` finding (a pending refund with a wrong field is `FAILED`). `core.recheck(verifier, verdict_or_dict, log)` re-judges only `UNVERIFIED` verdicts via the verifier's optional `recheck(claim, observed)` and tags `context["recheck_of"]`; Stripe judges only the refunds seen at the first check. - `agent_readback/evidence.py` — append-only JSONL log; each record carries `seq` and hashes the previous (`GENESIS` = 64 zeros). With a key (`key=` or `READBACK_LOG_KEY`) hashes are HMAC-SHA256; `_digest(prev, seq, body, key)` is the single hashing function. File opened `0600` + `O_APPEND`. Optional `anchor=` callable gets `(count, head)` after each append (`FileAnchor` writes it atomically to a separate file; a failing anchor warns and sets `anchor_error`, never raises); `verify-log --anchor FILE` / `--head HASH` uses `check_anchor` to catch truncation. Redacts by default: no observed values, agent text replaced by a keyed digest, expected/finding values replaced unless the field is in `keep_fields` (`"*"` keeps all). Preserve this default when changing the log format. README "Security model" table must stay in sync with these guarantees. - `agent_readback/adapters.py` — `watched(fn, verifier, to_claim, log, said=...)` wraps a sync/async callable in `watch()`; `to_claim(*args, **kwargs)` → probe or `None` (skip). Used for MCP (`session.call_tool = watched(...)`, `said=mcp_text`) and LangGraph nodes. Imports neither framework; tests use them via `importorskip`. - `agent_readback/ratelimit.py` — opt-in read limiting. `RateLimit(per_second, burst)` is a thread-safe token bucket (GCRA; slot reserved under the lock, sleep outside it; clock and sleep injectable for tests). `limit_reads(target, limit)` adds an httpx request hook to a sync `httpx.Client` or wraps a SQL `connect` callable; it refuses an `AsyncClient` and a target it already limited (marked with `_readback_rate_limit`). Keyword-only `max_wait`: a wait longer than that raises `RateLimitTimeout` (subclass of `httpx.TimeoutException`) without taking a slot, which every verifier reports as `unverified`. Otherwise it only ever delays a read, so verdict semantics are unchanged. @@ -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 184) 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 199, of which 1 skips on Windows without symlink privileges) 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 7dc94dc..2343de3 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ flowchart LR Install (Python 3.10+; the only runtime dependency is `httpx`): ```bash -pip install "agent-readback @ git+https://github.com/dhonitheja/agent-readback@v0.3.0" +pip install "agent-readback @ git+https://github.com/dhonitheja/agent-readback@v0.3.1" ``` Wrap the call your agent makes. Readback snapshots before it, reads back after @@ -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 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 | +| 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 FHIR search must be a `Bundle` of Appointments that each have an id (`include` and `outcome` entries are skipped), and a Stripe page must carry `data` and `has_more`; anything else is `unverified`. A timestamp with no UTC form is compared as written | | 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,8 +344,8 @@ external security or compliance review has been done. ## What is tested and what is not -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 +Version 0.3.1. The suite has 199 offline tests; with the optional test dependencies +installed, 198 pass on Windows and the symlink test is skipped there without symlink privileges; elsewhere it runs too. 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 produced the expected verdict for all four refund scenarios, using a separate diff --git a/agent_readback/__init__.py b/agent_readback/__init__.py index bafeaf8..61f36fd 100644 --- a/agent_readback/__init__.py +++ b/agent_readback/__init__.py @@ -6,7 +6,7 @@ from .evidence import EvidenceLog, FileAnchor from .ratelimit import RateLimit, RateLimitTimeout, limit_reads -__version__ = "0.3.0" +__version__ = "0.3.1" __all__ = [ "Claim", "EvidenceLog", diff --git a/agent_readback/verifiers/fhir.py b/agent_readback/verifiers/fhir.py index be0872e..e45eef7 100644 --- a/agent_readback/verifiers/fhir.py +++ b/agent_readback/verifiers/fhir.py @@ -33,11 +33,11 @@ def normalize_instant(value: Any) -> Any: except ValueError: 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 value # a time with no zone is ambiguous; compared as written: it matches only identical text 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 + return value # e.g. year 1 at +01:00 has no UTC form; compared as written: it matches only identical text def _object(value: Any, what: str) -> dict[str, Any]: @@ -56,8 +56,11 @@ def _array(value: Any, what: str) -> list[Any]: 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") + if resource.get("resourceType") != "Appointment": # e.g. an OperationOutcome sent with HTTP 200 + raise ValueError("malformed FHIR response: resource is not an Appointment") + if not isinstance(resource.get("id"), str) or not resource["id"].strip(): + # A stored resource always has an id; keying by position would let an old entry look new. + raise ValueError("malformed FHIR response: Appointment.id is missing or not a string") flat: dict[str, Any] = { "id": resource.get("id"), "status": resource.get("status"), @@ -67,7 +70,8 @@ def flatten_appointment(resource: dict[str, Any]) -> dict[str, Any]: "practitioner": None, } for participant in _array(resource.get("participant", []), "Appointment.participant"): - actor = _object(_object(participant, "participant").get("actor") or {}, "participant.actor") + actor = _object(participant, "participant").get("actor") + actor = _object({} if actor is None else actor, "participant.actor") # [] or "" is malformed, not absent reference = actor.get("reference", "") if not isinstance(reference, str): raise ValueError("malformed FHIR response: actor.reference is not a string") @@ -97,9 +101,14 @@ def _appointments(self, patient: str) -> dict[str, dict[str, Any]]: response = self.client.get(url, params=params, headers={"Cache-Control": "no-cache"}) response.raise_for_status() bundle = _object(response.json(), "search Bundle") + if bundle.get("resourceType") != "Bundle": # e.g. an OperationOutcome sent with HTTP 200 + raise ValueError("malformed FHIR response: search result is not a 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 + entry = _object(entry, "Bundle.entry item") + if _object(entry.get("search", {}), "Bundle.entry.search").get("mode") in ("include", "outcome"): + continue # _include'd resources and server warnings are not search matches + flat = flatten_appointment(entry["resource"]) + found[flat["id"]] = flat 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 diff --git a/agent_readback/verifiers/stripe.py b/agent_readback/verifiers/stripe.py index 63eec4f..def02fd 100644 --- a/agent_readback/verifiers/stripe.py +++ b/agent_readback/verifiers/stripe.py @@ -73,7 +73,8 @@ def _refunds(self, payment_intent: str) -> dict[str, dict[str, Any]]: page = response.json() 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) + # No default for data or has_more: an error body or {} must not read as "no refunds" (a false FAILED). + items, has_more = page.get("data"), page.get("has_more") 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: diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index bc9c4fb..2cef467 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -50,3 +50,5 @@ infrastructure from the maintainer. Step 12 needs outside reviewers. OpenAI models, `tzdata` on Windows. - 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). +- Verified locally (2026-11-22, 0.3.1): 198 tests pass, 1 symlink test skips, on Windows with MCP 1.30 and LangGraph 1.2. + The 0.3.0 line above predates the 0.3.1 fixes; MCP 2.3 has not been re-run on 0.3.1 locally (CI covers both). diff --git a/examples/healthcare/mock_booking.py b/examples/healthcare/mock_booking.py new file mode 100644 index 0000000..1452942 --- /dev/null +++ b/examples/healthcare/mock_booking.py @@ -0,0 +1,41 @@ +"""Run one synthetic booking for a local agent and report the readback verdict.""" + +import argparse + +from agent_readback import Claim, Status, watch +from agent_readback.verifiers import FhirAppointmentVerifier + +from .mock_fhir import FAULTS, MockFhirServer +from .tasks import VISIT, seed_people, slot, utc +from .tools import make_tools + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--scenario", choices=(*FAULTS, "unavailable"), default="ok") + args = parser.parse_args() + server = MockFhirServer() + with server.client() as writer, server.client() as reader: + patients, practitioners = seed_people(writer, patients=1, practitioners=1) + start = slot(0) + booking = { + "patient": patients[0], "practitioner": practitioners[0], + "start": utc(start), "end": utc(start + VISIT), + } + claim = Claim("fhir.appointment.create", "", {**booking, "status": "booked"}) + server.fault = "ok" if args.scenario == "unavailable" else args.scenario + with watch(FhirAppointmentVerifier(reader), claim) as check: + make_tools(writer)["book_appointment"](**booking) + server.down = args.scenario == "unavailable" + if check.verdict is None: # not assert: python -O strips it + raise SystemExit("unverified: no verdict was produced. Review required.") + messages = { + Status.VERIFIED: f"Synthetic appointment booked for {booking['start']}.", + Status.FAILED: "The appointment record differs from the request. Review required.", + Status.UNVERIFIED: "The appointment could not be verified. Review required.", + } + print(f"{check.verdict.status.value}: {messages[check.verdict.status]}") + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml index 42c7da8..136fe61 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "agent-readback" -version = "0.3.0" +version = "0.3.1" description = "Readback: check what an AI agent says it did against the system of record." readme = "README.md" requires-python = ">=3.10" diff --git a/tests/test_fhir_verifier.py b/tests/test_fhir_verifier.py index 13dae08..9bb7e0c 100644 --- a/tests/test_fhir_verifier.py +++ b/tests/test_fhir_verifier.py @@ -36,7 +36,7 @@ def handle(request): def test_incomplete_pagination_is_unverified(): def handle(request): return httpx.Response(200, json={ - "entry": [], + "resourceType": "Bundle", "entry": [], "link": [{"relation": "next", "url": "Appointment?page=next"}], }) @@ -180,10 +180,14 @@ def test_agent_exception_still_produces_a_verdict_and_a_log_record(server, tools assert len(log.records()) == 1 -def test_resources_without_an_id_are_not_collapsed(): +def test_appointment_without_an_id_is_a_read_error(): + # Keying id-less entries by position let an unchanged one look new at check time. from agent_readback.verifiers.fhir import flatten_appointment - assert flatten_appointment({"status": "booked"})["id"] is None + for bad in ({"resourceType": "Appointment", "status": "booked"}, {"resourceType": "Appointment", "id": ""}, + {"resourceType": "Appointment", "id": " "}): + with pytest.raises(ValueError, match="malformed FHIR response"): + flatten_appointment(bad) def test_foreign_next_link_never_receives_the_read_only_token(): @@ -192,7 +196,7 @@ def test_foreign_next_link_never_receives_the_read_only_token(): def handle(request): hosts.append((request.url.host, request.headers.get("Authorization"))) return httpx.Response(200, json={ - "entry": [], + "resourceType": "Bundle", "entry": [], "link": [{"relation": "next", "url": "https://attacker.test/steal?page=2"}], }) @@ -210,9 +214,9 @@ def test_absolute_next_link_on_the_same_server_is_followed(): def handle(request): pages.append(str(request.url)) if "page=2" in str(request.url): - return httpx.Response(200, json={"entry": []}) + return httpx.Response(200, json={"resourceType": "Bundle", "entry": []}) return httpx.Response(200, json={ - "entry": [], + "resourceType": "Bundle", "entry": [], "link": [{"relation": "next", "url": "https://fhir.test/Appointment?page=2"}], }) @@ -227,7 +231,7 @@ def test_odd_next_links_are_judged_by_where_httpx_sends_them(link): def handle(request): hosts.append(str(request.url)) - return httpx.Response(200, json={"entry": [], "link": [{"relation": "next", "url": link}]}) + return httpx.Response(200, json={"resourceType": "Bundle", "entry": [], "link": [{"relation": "next", "url": link}]}) with httpx.Client(transport=httpx.MockTransport(handle), base_url="https://fhir.test") as client: verifier = FhirAppointmentVerifier(client) @@ -245,8 +249,8 @@ def test_root_relative_next_link_is_not_appended_to_the_base_path(): def handle(request): paths.append(request.url.path) if request.url.params.get("page") == "2": - return httpx.Response(200, json={"entry": []}) - return httpx.Response(200, json={"entry": [], "link": [{"relation": "next", "url": "/r4/Appointment?page=2"}]}) + return httpx.Response(200, json={"resourceType": "Bundle", "entry": []}) + return httpx.Response(200, json={"resourceType": "Bundle", "entry": [], "link": [{"relation": "next", "url": "/r4/Appointment?page=2"}]}) with httpx.Client(transport=httpx.MockTransport(handle), base_url="https://fhir.test/r4/") as client: assert FhirAppointmentVerifier(client).snapshot(create_claim()) == set() @@ -257,8 +261,8 @@ def handle(request): def test_odd_next_links_never_crash_the_snapshot(link): def handle(request): if request.url.params.get("page") == "2": - return httpx.Response(200, json={"entry": []}) - return httpx.Response(200, json={"entry": [], "link": [{"relation": "next", "url": link}]}) + return httpx.Response(200, json={"resourceType": "Bundle", "entry": []}) + return httpx.Response(200, json={"resourceType": "Bundle", "entry": [], "link": [{"relation": "next", "url": link}]}) with httpx.Client(transport=httpx.MockTransport(handle), base_url="https://fhir.test") as client: result = FhirAppointmentVerifier(client).snapshot(create_claim()) @@ -270,12 +274,19 @@ def handle(request): "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}}]}}]}, + "id is an object": {"resourceType": "Bundle", "entry": [{"resource": {"resourceType": "Appointment", "id": {"x": 1}}}]}, + "participant is a string": {"resourceType": "Bundle", "entry": [{"resource": {"resourceType": "Appointment", "id": "a1", "participant": "x"}}]}, + "actor reference is a number": {"resourceType": "Bundle", "entry": [{"resource": {"resourceType": "Appointment", "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}]}, + "OperationOutcome with 200": {"resourceType": "OperationOutcome", "issue": [{"severity": "error"}]}, + "bundle without resourceType": {"entry": []}, + "matched entry is not an Appointment": {"resourceType": "Bundle", "entry": [{"resource": {"resourceType": "Patient", "id": "p1"}}]}, + "appointment without an id": {"resourceType": "Bundle", "entry": [{"resource": {"resourceType": "Appointment"}}]}, + "actor is a list": {"resourceType": "Bundle", "entry": [{"resource": {"resourceType": "Appointment", "id": "a1", "participant": [{"actor": []}]}}]}, + "actor is an empty string": {"resourceType": "Bundle", "entry": [{"resource": {"resourceType": "Appointment", "id": "a1", "participant": [{"actor": ""}]}}]}, + "entry search is a string": {"resourceType": "Bundle", "entry": [{"search": "match", "resource": {"resourceType": "Appointment", "id": "a1"}}]}, } @@ -314,12 +325,34 @@ def test_next_link_without_a_usable_url_is_an_incomplete_read_not_verified(next_ 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" +def test_outcome_and_include_entries_are_not_counted_as_appointments(): + # A server warning added only to the check-time search must not become a false extra_effect. + warning = {"search": {"mode": "outcome"}, "resource": {"resourceType": "OperationOutcome", "issue": []}} + included = {"search": {"mode": "include"}, "resource": {"resourceType": "Practitioner", "id": "d1"}} + booked = {**_bundle_appointment("a1"), "search": {"mode": "match"}} pages = [{"resourceType": "Bundle", "entry": []}, - {"resourceType": "Bundle", "entry": [_bundle_appointment("a1", "0001-01-01T00:00:00+01:00")]}] + {"resourceType": "Bundle", "entry": [warning, booked, included]}] 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"] + assert verdict.status is Status.VERIFIED and [item["id"] for item in verdict.observed["created"]] == ["a1"] + + +@pytest.mark.parametrize("claimed, status", [ + ("0001-01-01T00:00:00+01:00", Status.VERIFIED), # identical text matches + ("0001-01-01T01:00:00+02:00", Status.FAILED), # same instant written another way does not + (START, Status.FAILED), # a different instant does not +]) +def test_timestamp_without_a_utc_form_is_compared_as_written_not_a_crash(claimed, status): + stored = "0001-01-01T00:00:00+01:00" # year 1 at +01:00 has no UTC form + assert normalize_instant(stored) == stored + pages = [{"resourceType": "Bundle", "entry": []}, + {"resourceType": "Bundle", "entry": [_bundle_appointment("a1", stored)]}] + 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) + claim = create_claim(start=claimed) + verdict = verifier.check(claim, verifier.snapshot(claim)) + assert verdict.status is status + assert [f.field for f in verdict.findings] == ([] if status is Status.VERIFIED else ["start"]) diff --git a/tests/test_stripe_sql_alerts.py b/tests/test_stripe_sql_alerts.py index afea2a3..9f6407f 100644 --- a/tests/test_stripe_sql_alerts.py +++ b/tests/test_stripe_sql_alerts.py @@ -405,9 +405,22 @@ def sync_auth_flow(self, request): "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}, + "error body with 200": {"error": {"type": "api_error", "message": "x"}}, + "empty object": {}, + "has_more missing": {"data": []}, } +def test_error_shaped_stripe_page_after_a_real_refund_is_unverified_not_failed(): + # The refund exists, but the check-time read is broken: that must never read as "no refund". + pages = [{"data": [], "has_more": False}, {"error": {"type": "api_error"}}] + 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) + verdict = verifier.check(REFUND, verifier.snapshot(REFUND)) + assert verdict.status is Status.UNVERIFIED and kinds(verdict) == [FindingKind.UNREACHABLE] + + @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))