From 05e8bdefe5f77166b83b7fb62df400adbffd5cfb Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 23:19:03 -0500 Subject: [PATCH 1/2] fix(tx): count read-only POSTs as reads, from protocol or sandbox evidence (#2389) Reads sent as POST used up the tap's single mutation, so the real save got 403, and with a relaxed budget the extra mutations made a correct save REFUTED (wire_evidence_incomplete, wire_target_mismatch, wire_collateral_mutation). Reproduced on a live Medplum through the merged engine: a batch read, a GraphQL query and a PUT save gave [200, 403, 403] and REFUTED; relaxed, [200, 200, 200] and REFUTED. Three general classes, none naming an app: - A GraphQL query on an operation-style route (/$graphql) is classified like one on /graphql. Mutations stay mutations. - A batch Bundle (batch or transaction) whose every entry is a GET or HEAD is a read. Any other entry, a resource body, or a missing method makes it a mutation. - Any other POST is a read only when it matches a ReadRoute declared in WirePolicy.read_routes: method, exact path, and every top-level body field that was constant across the observed samples, so a write on the same RPC route with a different operation field never matches. probe_read_routes learns those routes. It replays each POST route of a trace on a loopback sandbox, after a caller-supplied reset to the pre-trace state, and accepts a route only when the store was idle, every replay returned 2xx and a caller-supplied digest of the whole store did not change. Without the reset, replaying a recorded save writes the value the store already holds and looks like a read; a test pins that. Credential-like body fields are never stored in a route. Live on Medplum (every table in the app's database hashed): batch and GraphQL reads are reads, POST /Patient/_search is learned as a read, the PUT save is not, a wrapped save after three POST reads goes through with a second write still blocked, and the engine returns UNCERTAIN with only unqualified_observation_only. Signed-off-by: abrichr --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/openadapt_flow/tx/__init__.py | 10 + packages/flow/openadapt_flow/tx/read_probe.py | 307 +++++++++++++++ packages/flow/openadapt_flow/tx/wire_tap.py | 141 ++++++- packages/flow/tests/test_tx_post_reads.py | 348 ++++++++++++++++++ .../flow/tests/test_tx_post_reads_live.py | 288 +++++++++++++++ 7 files changed, 1091 insertions(+), 7 deletions(-) create mode 100644 packages/flow/openadapt_flow/tx/read_probe.py create mode 100644 packages/flow/tests/test_tx_post_reads.py create mode 100644 packages/flow/tests/test_tx_post_reads_live.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 3214679ba6..c364673c99 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -179,7 +179,7 @@ improvising or retrying when something is off. | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Undo refuses to overwrite a change made after the write. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers; no third-party application) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Undo refuses to overwrite a change made after the write. The wire tap counts a GraphQL query (on `/graphql` or `/$graphql`) and a batch of `GET`s as reads. Another `POST` counts as a read only when it matches a read route declared as data; `probe_read_routes` learns those by replaying a trace on a sandbox reset to its pre-trace state and requiring that a whole-store digest not change. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers; no third-party application) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](packages/flow/docs/RECONCILE.md), [results](packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | diff --git a/llms-full.txt b/llms-full.txt index 336d9b6236..b8867234ac 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -613,7 +613,7 @@ improvising or retrying when something is off. | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Undo refuses to overwrite a change made after the write. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers; no third-party application) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Undo refuses to overwrite a change made after the write. The wire tap counts a GraphQL query (on `/graphql` or `/$graphql`) and a batch of `GET`s as reads. Another `POST` counts as a read only when it matches a read route declared as data; `probe_read_routes` learns those by replaying a trace on a sandbox reset to its pre-trace state and requiring that a whole-store digest not change. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers; no third-party application) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECONCILE.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | diff --git a/packages/flow/openadapt_flow/tx/__init__.py b/packages/flow/openadapt_flow/tx/__init__.py index 9d02c3317d..7a5556bb92 100644 --- a/packages/flow/openadapt_flow/tx/__init__.py +++ b/packages/flow/openadapt_flow/tx/__init__.py @@ -25,6 +25,11 @@ load_network_capture_as_har, network_capture_entries_to_har, ) +from openadapt_flow.tx.read_probe import ( + ReadRouteProbe, + ReadRouteReport, + probe_read_routes, +) from openadapt_flow.tx.receipt import ( TxReceiptPayload, audit_legacy_tx_receipt, @@ -61,6 +66,7 @@ salted_sha256, ) from openadapt_flow.tx.wire_tap import ( + ReadRoute, SessionWireTap, WirePolicy, dump_har, @@ -117,6 +123,10 @@ "load_or_create_signing_key", "network_capture_entries_to_har", "probe_put_semantics", + "probe_read_routes", + "ReadRoute", + "ReadRouteProbe", + "ReadRouteReport", "salted_sha256", "strict_equal", "strip_readonly_volatile", diff --git a/packages/flow/openadapt_flow/tx/read_probe.py b/packages/flow/openadapt_flow/tx/read_probe.py new file mode 100644 index 0000000000..82fd359617 --- /dev/null +++ b/packages/flow/openadapt_flow/tx/read_probe.py @@ -0,0 +1,307 @@ +"""Learn which ``POST`` routes only read, by replaying them on a sandbox. + +Many apps read with ``POST``: chart fragments, search forms, query APIs. The +wire tap treats every ``POST`` it cannot classify as a mutation, so those reads +use up the write budget and the real save is blocked (OpenAdapt #2389). + +Guessing from names would be fail-open: one RPC endpoint can carry both reads +and writes. This module takes evidence instead. For each ``POST`` route in a +recorded trace it replays every observed request against a sandbox copy of +the app, and reads a caller-supplied digest of the sandbox's whole store +before and after. Before every replay the caller's ``store_reset`` puts the +sandbox back in its state from before the trace. Without that, replaying a +recorded save would write the value the store already holds and look like a +read. A route is learned as a read only when + +- the store was idle (two digests with no request in between agree), +- every replay returned 2xx, and +- no replay changed the digest. + +What it cannot see: a write route whose every recorded sample wrote values +the pre-trace store already held. Such a request changed nothing in the +trace either. The engine's read-back of the target record still judges any +write that reaches it. + +The learned ``ReadRoute`` keys on the method, the exact path and every +top-level body field whose value was the same in all samples, so a write on +the same route with a different operation field never matches it. Fields +that look like credentials or anti-forgery tokens are never stored. + +The report is data for ``WirePolicy.read_routes``. Nothing here runs against +anything but a loopback sandbox unless the caller opts in. +""" + +from __future__ import annotations + +import base64 +import json +import re +import urllib.error +import urllib.parse +import urllib.request +from typing import Any, Callable, Iterable, Mapping, Optional + +from pydantic import BaseModel, ConfigDict + +from openadapt_flow.tx.induce import _assert_sandbox_url_allowed +from openadapt_flow.tx.wire_tap import ( + ReadRoute, + _top_level_body_fields, + is_mutation_request, +) + +_CREDENTIAL_KEY_RE = re.compile( + r"(pass|secret|token|csrf|xsrf|nonce|session|auth|api[_-]?key|cookie|signature)", + re.IGNORECASE, +) + +#: Request headers replayed from the trace. Anything that could carry a +#: credential comes from ``headers`` instead, supplied by the caller. +_REPLAYED_HEADERS = frozenset({"content-type", "accept", "x-requested-with"}) + + +class ReadRouteProbe(BaseModel): + """What the probe saw for one route.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + method: str + path: str + samples: int + read_only: bool + reason: str + body_equals: tuple[tuple[str, str], ...] = () + + +class ReadRouteReport(BaseModel): + """Learned read routes plus the evidence for every route probed.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + store_idle: bool + routes: tuple[ReadRouteProbe, ...] + + @property + def read_routes(self) -> tuple[ReadRoute, ...]: + if not self.store_idle: + return () + return tuple( + ReadRoute( + method=r.method, path=re.escape(r.path), body_equals=r.body_equals + ) + for r in self.routes + if r.read_only + ) + + +class _Sample: + __slots__ = ("method", "path", "query", "body", "headers") + + def __init__( + self, + method: str, + path: str, + query: str, + body: bytes, + headers: list[tuple[str, str]], + ) -> None: + self.method = method + self.path = path + self.query = query + self.body = body + self.headers = headers + + +def _har_body(request: Mapping[str, Any]) -> bytes: + post = request.get("postData") + if not isinstance(post, Mapping): + return b"" + text = str(post.get("text") or "") + if post.get("encoding") == "base64": + try: + return base64.b64decode(text) + except ValueError: + return b"" + return text.encode("utf-8") + + +def _post_samples(har: Mapping[str, Any]) -> dict[tuple[str, str], list[_Sample]]: + log = har.get("log") + entries = log.get("entries") if isinstance(log, Mapping) else None + groups: dict[tuple[str, str], list[_Sample]] = {} + for entry in entries if isinstance(entries, list) else []: + if not isinstance(entry, Mapping): + continue + req = entry.get("request") + resp = entry.get("response") + if not isinstance(req, Mapping) or not isinstance(resp, Mapping): + continue + method = str(req.get("method", "")).upper() + if method != "POST": + continue + status = int(resp.get("status") or 0) + if not 200 <= status < 300: + continue + parts = urllib.parse.urlsplit(str(req.get("url", ""))) + headers = [ + (str(h.get("name", "")), str(h.get("value", ""))) + for h in req.get("headers") or [] + if isinstance(h, Mapping) + ] + body = _har_body(req) + is_mut, is_gql_mut = is_mutation_request(method, req["url"], body, headers) + if not is_mut or is_gql_mut: + continue # already a read, or a declared GraphQL mutation + path = parts.path or "/" + groups.setdefault((method, path), []).append( + _Sample(method, path, parts.query, body, headers) + ) + return groups + + +def _constant_fields(samples: list[_Sample]) -> Optional[tuple[tuple[str, str], ...]]: + common: Optional[dict[str, str]] = None + for sample in samples: + fields = _top_level_body_fields(sample.body, sample.headers) + if fields is None: + return None + if common is None: + common = dict(fields) + else: + common = {k: v for k, v in common.items() if fields.get(k) == v} + return tuple( + sorted( + (k, v) + for k, v in (common or {}).items() + if not _CREDENTIAL_KEY_RE.search(k) + ) + ) + + +def _replay( + base_url: str, + sample: _Sample, + headers: Mapping[str, str], + timeout: float, +) -> int: + url = base_url.rstrip("/") + sample.path + if sample.query: + url += "?" + sample.query + req_headers = { + k: v for k, v in sample.headers if k.lower() in _REPLAYED_HEADERS and v + } + req_headers.update(headers) + request = urllib.request.Request( + url, data=sample.body or None, headers=req_headers, method=sample.method + ) + opener = urllib.request.build_opener(_NoRedirect) + try: + with opener.open(request, timeout=timeout) as resp: + resp.read() + return int(resp.status) + except urllib.error.HTTPError as err: + return int(err.code) + except urllib.error.URLError: + return 0 + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args: Any, **kwargs: Any) -> None: + return None + + +def probe_read_routes( + har: Mapping[str, Any], + *, + sandbox_base_url: str, + store_digest: Callable[[], str], + store_reset: Callable[[], None], + headers: Optional[Mapping[str, str]] = None, + allow_remote_sandbox: bool = False, + timeout: float = 15.0, + routes: Optional[Iterable[tuple[str, str]]] = None, +) -> ReadRouteReport: + """Replay a trace's ``POST`` routes on a sandbox; learn the read-only ones. + + ``store_digest`` must hash the sandbox's whole persistent store (every + table, or the data directory), not one record: a read route must change + nothing anywhere. ``store_reset`` must restore the sandbox to its state + from before the trace was recorded; it runs before every replay. ``routes`` limits the probe to some ``(method, path)`` + pairs from the trace. + """ + _assert_sandbox_url_allowed( + sandbox_base_url, allow_remote_sandbox=allow_remote_sandbox + ) + groups = _post_samples(har) + if routes is not None: + wanted = {(m.upper(), p) for m, p in routes} + groups = {k: v for k, v in groups.items() if k in wanted} + auth = dict(headers or {}) + + store_reset() + first = store_digest() + idle = store_digest() == first + probes: list[ReadRouteProbe] = [] + for (method, path), samples in sorted(groups.items()): + if not idle: + probes.append( + ReadRouteProbe( + method=method, + path=path, + samples=len(samples), + read_only=False, + reason="store not idle: digests differ with no request", + ) + ) + continue + body_equals = _constant_fields(samples) + if body_equals is None: + probes.append( + ReadRouteProbe( + method=method, + path=path, + samples=len(samples), + read_only=False, + reason="body is neither a JSON object nor a form", + ) + ) + continue + reason = "every replay returned 2xx and left the store unchanged" + read_only = True + for sample in samples: + store_reset() + before = store_digest() + status = _replay(sandbox_base_url, sample, auth, timeout) + after = store_digest() + if not 200 <= status < 300: + read_only, reason = False, f"replay returned {status}" + break + if after != before: + read_only, reason = False, "replay changed the store" + break + probes.append( + ReadRouteProbe( + method=method, + path=path, + samples=len(samples), + read_only=read_only, + reason=reason, + body_equals=body_equals if read_only else (), + ) + ) + return ReadRouteReport(store_idle=idle, routes=tuple(probes)) + + +def dump_read_routes(report: ReadRouteReport) -> str: + """Serialize learned routes as JSON data for a policy file.""" + return json.dumps( + [route.model_dump() for route in report.read_routes], indent=2, sort_keys=True + ) + + +__all__ = [ + "ReadRouteProbe", + "ReadRouteReport", + "dump_read_routes", + "probe_read_routes", +] diff --git a/packages/flow/openadapt_flow/tx/wire_tap.py b/packages/flow/openadapt_flow/tx/wire_tap.py index bbea837b8b..56405b0593 100644 --- a/packages/flow/openadapt_flow/tx/wire_tap.py +++ b/packages/flow/openadapt_flow/tx/wire_tap.py @@ -71,6 +71,23 @@ _LOCAL_BROWSER_SCHEMES = ("about:", "blob:", "data:", "javascript:") +class ReadRoute(BaseModel): + """A ``POST`` route proven to read only, declared as data. + + A request counts as a read only when its method and path match and every + ``body_equals`` key holds exactly that top-level value in a JSON or form + body. The constant body fields are what distinguish a read from a write on + a route that carries both (one RPC endpoint, many methods). An entry is + meant to come from ``probe_read_routes`` on a sandbox, never from a guess. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + method: str = "POST" + path: str + body_equals: tuple[tuple[str, str], ...] = () + + class WirePolicy(BaseModel): """Declarative inline gating and extraction policy for ``SessionWireTap``.""" @@ -79,6 +96,7 @@ class WirePolicy(BaseModel): allowed_origins: tuple[str, ...] = () max_mutations: Optional[int] = 1 allowed_write_routes: tuple[tuple[str, str], ...] = () + read_routes: tuple[ReadRoute, ...] = () id_fields: tuple[str, ...] = ("id", "uuid", "pid") version_fields: tuple[str, ...] = ("version", "etag", "meta.versionId") secrets: tuple[str, ...] = () @@ -355,6 +373,48 @@ def _classify_single_graphql_doc( return (True, False) +def _is_graphql_path(path_or_url: str) -> bool: + """True when the last path segment names a GraphQL endpoint. + + Servers spell it ``/graphql`` or, for an operation-style route, + ``/$graphql``. + """ + clean_path = (urlsplit(path_or_url).path or "/").rstrip("/").lower() + last = clean_path.rsplit("/", 1)[-1] + return last.lstrip("$") == "graphql" + + +_READ_BATCH_METHODS = frozenset({"GET", "HEAD"}) + + +def _is_read_only_batch(parsed: Any) -> bool: + """True for a batch envelope whose every entry is a ``GET`` or ``HEAD``. + + This is the standard ``Bundle`` of type ``batch`` or ``transaction``: the + server runs each entry's request, so a bundle of reads changes nothing. + One entry with another method, or one without a method, makes it a write. + """ + if not isinstance(parsed, dict) or parsed.get("resourceType") != "Bundle": + return False + if parsed.get("type") not in ("batch", "transaction"): + return False + entries = parsed.get("entry") + if not isinstance(entries, list) or not entries: + return False + for entry in entries: + if not isinstance(entry, dict) or set(entry) - {"request", "fullUrl"}: + return False + request = entry.get("request") + if not isinstance(request, dict): + return False + method = request.get("method") + if not isinstance(method, str) or method.upper() not in _READ_BATCH_METHODS: + return False + if not isinstance(request.get("url"), str): + return False + return True + + def classify_graphql_post( path_or_url: str, request_body: bytes, @@ -365,8 +425,7 @@ def classify_graphql_post( A ``POST`` is treated as a state mutation unless it is provably a GraphQL ``query``-only request. GraphQL ``mutation`` operations return ``(True, True)``. """ - clean_path = (urlsplit(path_or_url).path or "/").rstrip("/").lower() - is_graphql_endpoint = clean_path.endswith("/graphql") + is_graphql_endpoint = _is_graphql_path(path_or_url) ctype = _get_header(request_headers, "content-type").lower() decoded = _decompress_for_inspection(request_body, request_headers) @@ -386,6 +445,8 @@ def classify_graphql_post( return classified if classified is not None else (True, False) parsed = _parse_json_body(request_body, request_headers) + if _is_read_only_batch(parsed): + return (False, False) if isinstance(parsed, dict) and isinstance(parsed.get("query"), str): op_name = parsed.get("operationName") classified = _classify_single_graphql_doc( @@ -437,7 +498,7 @@ def is_mutation_request( parts = urlsplit(path_or_url) query = parse_qsl(parts.query, keep_blank_values=True) documents = [value for name, value in query if name == "query"] - if parts.path.rstrip("/").lower().endswith("/graphql") or documents: + if _is_graphql_path(path_or_url) or documents: if len(documents) != 1: return (True, False) operation_names = [ @@ -448,11 +509,11 @@ def is_mutation_request( classified = _classify_single_graphql_doc( documents[0], operation_name=operation_names[0] if operation_names else None, - is_graphql_endpoint=parts.path.rstrip("/").lower().endswith("/graphql"), + is_graphql_endpoint=_is_graphql_path(path_or_url), ) if classified is not None: return classified - if parts.path.rstrip("/").lower().endswith("/graphql"): + if _is_graphql_path(path_or_url): return (True, False) return (False, False) if upper == "POST": @@ -494,6 +555,63 @@ def matches_write_route( return raw_pattern == clean_path +def _top_level_body_fields( + request_body: bytes, + request_headers: Optional[Mapping[str, str] | Iterable[tuple[str, str]]], +) -> Optional[dict[str, str]]: + """Top-level scalar fields of a JSON object or form body, as strings.""" + parsed = _parse_json_body(request_body, request_headers) + if isinstance(parsed, dict): + fields: dict[str, str] = {} + for key, val in parsed.items(): + if isinstance(val, bool): + fields[str(key)] = "true" if val else "false" + elif isinstance(val, (str, int, float)): + fields[str(key)] = str(val) + return fields + decoded = _decompress_for_inspection(request_body, request_headers) + ctype = _get_header(request_headers, "content-type").lower() + if decoded is not None and ctype.startswith("application/x-www-form-urlencoded"): + try: + text = decoded.decode("utf-8") + except UnicodeDecodeError: + return None + pairs = parse_qsl(text, keep_blank_values=True) + names = [k for k, _ in pairs] + if len(names) != len(set(names)): + return None + return {k: v for k, v in pairs} + if not decoded: + return {} + return None + + +def matches_read_route( + routes: Iterable["ReadRoute"], + method: str, + path: str, + request_body: bytes = b"", + request_headers: Optional[Mapping[str, str] | Iterable[tuple[str, str]]] = None, +) -> bool: + """True when a request matches a declared read-only route exactly.""" + routes = tuple(routes) + if not routes: + return False + fields: Optional[dict[str, str]] = None + fields_parsed = False + for route in routes: + if not matches_write_route(method, path, route.method, route.path): + continue + if not fields_parsed: + fields = _top_level_body_fields(request_body, request_headers) + fields_parsed = True + if fields is None: + continue + if all(fields.get(k) == v for k, v in route.body_equals): + return True + return False + + def extract_entity_id( method: str, path: str, @@ -1256,6 +1374,19 @@ def _begin_request( request_body, request_headers, ) + if ( + is_mut + and not is_gql_mut + and target_origin in self._allowed_origins + and matches_read_route( + self._policy.read_routes, + upper_method, + path, + request_body, + request_headers, + ) + ): + is_mut = False started_utc = _utc_now_iso() req_sha = hashlib.sha256(request_body).hexdigest() masked_url = _mask_if_needed(full_url, self._policy.secrets) diff --git a/packages/flow/tests/test_tx_post_reads.py b/packages/flow/tests/test_tx_post_reads.py new file mode 100644 index 0000000000..9b3704bc30 --- /dev/null +++ b/packages/flow/tests/test_tx_post_reads.py @@ -0,0 +1,348 @@ +"""Read-only ``POST`` requests no longer use up the write budget (#2389). + +Three general classes, none tied to an app: + +1. A GraphQL query sent to an operation-style route (``/$graphql``) is a + read, like one sent to ``/graphql``. +2. A batch envelope (``Bundle`` of type ``batch`` or ``transaction``) whose + every entry is a ``GET`` or ``HEAD`` is a read. +3. Any other ``POST`` route counts as a read only when it matches a + ``ReadRoute`` declared as data, which ``probe_read_routes`` learns by + replaying the route on a sandbox and checking that the whole store did not + change. + +The controls below use a local SQLite-backed server so the store digest is +exact. ``test_tx_post_reads_live.py`` runs the same checks on a real app. +""" + +from __future__ import annotations + +import hashlib +import http.client +import json +import sqlite3 +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any, Iterator +from urllib.parse import urlsplit + +import pytest + +from openadapt_flow.tx.read_probe import probe_read_routes +from openadapt_flow.tx.wire_tap import ( + ReadRoute, + SessionWireTap, + WirePolicy, + is_mutation_request, + matches_read_route, +) + +JSON = [("Content-Type", "application/json")] + + +def _post(path: str, body: Any) -> tuple[bool, bool]: + return is_mutation_request("POST", path, json.dumps(body).encode(), JSON) + + +# --------------------------------------------------------------------------- +# Static classes +# --------------------------------------------------------------------------- + + +def test_graphql_query_on_operation_route_is_a_read() -> None: + assert _post("/fhir/R4/$graphql", {"query": "{ PatientList { id } }"}) == ( + False, + False, + ) + assert _post("/api/graphql", {"query": "query Q { a }"}) == (False, False) + + +def test_graphql_mutation_on_operation_route_is_a_mutation() -> None: + assert _post( + "/fhir/R4/$graphql", {"query": "mutation { PatientCreate(res: {}) { id } }"} + ) == (True, True) + + +def test_graphql_name_elsewhere_in_path_does_not_make_a_read() -> None: + assert _post("/graphql/upload", {"query": "{ a }"}) == (True, False) + assert _post("/notgraphql", {"query": "{ a }"}) == (True, False) + + +@pytest.mark.parametrize("kind", ["batch", "transaction"]) +def test_batch_of_reads_is_a_read(kind: str) -> None: + bundle = { + "resourceType": "Bundle", + "type": kind, + "entry": [ + {"request": {"method": "GET", "url": "Patient?name=a"}}, + {"request": {"method": "HEAD", "url": "Patient/1"}}, + ], + } + assert _post("/fhir/R4", bundle) == (False, False) + + +@pytest.mark.parametrize( + "entries", + [ + [ + {"request": {"method": "GET", "url": "Patient"}}, + {"request": {"method": "PUT", "url": "Patient/1"}}, + ], + [ + { + "request": {"method": "GET", "url": "Patient"}, + "resource": {"resourceType": "Patient"}, + } + ], + [{"request": {"url": "Patient"}}], + [{"request": {"method": "GET"}}], + [], + ], +) +def test_batch_with_any_write_or_odd_entry_is_a_mutation(entries: list) -> None: + bundle = {"resourceType": "Bundle", "type": "batch", "entry": entries} + assert _post("/fhir/R4", bundle) == (True, False) + + +def test_other_bundle_types_are_mutations() -> None: + bundle = { + "resourceType": "Bundle", + "type": "collection", + "entry": [{"request": {"method": "GET", "url": "Patient"}}], + } + assert _post("/fhir/R4", bundle) == (True, False) + + +# --------------------------------------------------------------------------- +# Declared read routes +# --------------------------------------------------------------------------- + + +def test_read_route_requires_every_declared_body_field() -> None: + route = ReadRoute(path=r"/rpc", body_equals=(("method", "model.read"),)) + read = json.dumps({"method": "model.read", "params": [1]}).encode() + write = json.dumps({"method": "model.write", "params": [1]}).encode() + assert matches_read_route((route,), "POST", "/rpc", read, JSON) + assert not matches_read_route((route,), "POST", "/rpc", write, JSON) + assert not matches_read_route((route,), "POST", "/rpc/x", read, JSON) + assert not matches_read_route((route,), "PUT", "/rpc", read, JSON) + assert not matches_read_route((route,), "POST", "/rpc", b"not json", JSON) + + +def test_read_route_matches_form_bodies_and_refuses_repeated_names() -> None: + form = [("Content-Type", "application/x-www-form-urlencoded")] + route = ReadRoute(path=r"/fragment\.php", body_equals=(("action", "list"),)) + assert matches_read_route( + (route,), "POST", "/fragment.php", b"action=list&x=1", form + ) + assert not matches_read_route( + (route,), "POST", "/fragment.php", b"action=list&action=save", form + ) + + +# --------------------------------------------------------------------------- +# A local app with an exact store digest +# --------------------------------------------------------------------------- + + +class _App: + """One RPC route that reads or writes by body, one search route, one save.""" + + def __init__(self, db: Path) -> None: + self.db = db + conn = sqlite3.connect(db) + conn.execute("create table rec (id integer primary key, note text)") + conn.execute("insert into rec (id, note) values (1, 'a'), (2, 'b')") + conn.commit() + conn.close() + app = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args: Any) -> None: + pass + + def do_GET(self) -> None: + rid = self.path.rsplit("/", 1)[-1] + with sqlite3.connect(app.db) as conn: + row = conn.execute( + "select id, note from rec where id=?", (rid,) + ).fetchone() + self._json(200, {"id": row[0], "note": row[1]} if row else {}) + + def do_POST(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + body = json.loads(self.rfile.read(length) or b"{}") + with sqlite3.connect(app.db) as conn: + if self.path == "/search": + rows = conn.execute("select id from rec").fetchall() + self._json(200, {"ids": [r[0] for r in rows]}) + elif self.path == "/rpc" and body.get("method") == "rec.read": + self._json( + 200, + { + "n": conn.execute( + "select count(*) from rec" + ).fetchone()[0] + }, + ) + elif self.path == "/rpc" and body.get("method") == "rec.write": + conn.execute( + "update rec set note=? where id=1", (body["note"],) + ) + self._json(200, {"ok": True}) + elif self.path == "/rec/1": + conn.execute( + "update rec set note=? where id=1", (body["note"],) + ) + self._json(200, {"id": 1, "note": body["note"]}) + else: + self._json(404, {}) + + def _json(self, status: int, payload: Any) -> None: + raw = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.base = f"http://127.0.0.1:{self.server.server_port}" + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + + def reset(self) -> None: + """Restore the state from before any demonstration.""" + with sqlite3.connect(self.db) as conn: + conn.execute("delete from rec") + conn.execute("insert into rec (id, note) values (1, 'a'), (2, 'b')") + + def digest(self) -> str: + with sqlite3.connect(self.db) as conn: + rows = conn.execute("select id, note from rec order by id").fetchall() + return hashlib.sha256(repr(rows).encode()).hexdigest() + + def close(self) -> None: + self.server.shutdown() + self.server.server_close() + self.thread.join(timeout=5) + + +@pytest.fixture() +def app(tmp_path: Path) -> Iterator[_App]: + a = _App(tmp_path / "store.db") + try: + yield a + finally: + a.close() + + +def _call(base: str, method: str, path: str, body: Any = None) -> int: + parts = urlsplit(base) + conn = http.client.HTTPConnection(parts.hostname, parts.port, timeout=10) + raw = json.dumps(body).encode() if body is not None else None + conn.request(method, path, body=raw, headers={"Content-Type": "application/json"}) + status = conn.getresponse().status + conn.close() + return status + + +def _demo_har(app: _App) -> dict: + with SessionWireTap(app.base, WirePolicy(max_mutations=None)) as tap: + _call(tap.base_url, "POST", "/search", {"q": "a", "page": 1}) + _call(tap.base_url, "POST", "/search", {"q": "b", "page": 1}) + _call(tap.base_url, "POST", "/rpc", {"method": "rec.read", "id": 1}) + _call(tap.base_url, "POST", "/rpc", {"method": "rec.read", "id": 2}) + _call(tap.base_url, "POST", "/rec/1", {"note": "demo"}) + return tap.export_har() + + +def test_probe_learns_reads_and_refuses_the_save(app: _App) -> None: + report = probe_read_routes( + _demo_har(app), + sandbox_base_url=app.base, + store_digest=app.digest, + store_reset=app.reset, + ) + by_path = {r.path: r for r in report.routes} + assert report.store_idle + assert by_path["/search"].read_only and by_path["/search"].body_equals == ( + ("page", "1"), + ) + assert by_path["/rpc"].read_only + assert by_path["/rpc"].body_equals == (("method", "rec.read"),) + assert not by_path["/rec/1"].read_only + assert by_path["/rec/1"].reason == "replay changed the store" + + +def test_without_a_reset_a_replayed_save_would_look_like_a_read(app: _App) -> None: + """Why ``store_reset`` is required: the demo's own write already landed.""" + report = probe_read_routes( + _demo_har(app), + sandbox_base_url=app.base, + store_digest=app.digest, + store_reset=lambda: None, + ) + by_path = {r.path: r for r in report.routes} + assert by_path["/rec/1"].read_only # the fail-open the reset prevents + + +def test_learned_routes_let_the_one_save_through_and_still_gate_rpc_writes( + app: _App, +) -> None: + report = probe_read_routes( + _demo_har(app), + sandbox_base_url=app.base, + store_digest=app.digest, + store_reset=app.reset, + ) + policy = WirePolicy(max_mutations=1, read_routes=report.read_routes) + with SessionWireTap(app.base, policy) as tap: + assert _call(tap.base_url, "POST", "/search", {"q": "z", "page": 1}) == 200 + assert ( + _call(tap.base_url, "POST", "/rpc", {"method": "rec.read", "id": 1}) == 200 + ) + assert _call(tap.base_url, "POST", "/rec/1", {"note": "saved"}) == 200 + # A write on the RPC route is still a mutation, so the budget stops it. + assert ( + _call(tap.base_url, "POST", "/rpc", {"method": "rec.write", "note": "x"}) + == 403 + ) + summary = tap.summary() + assert summary.mutations_allowed == 1 and summary.mutations_blocked == 1 + assert summary.read_requests == 2 + + +def test_probe_refuses_everything_when_the_store_is_not_idle(app: _App) -> None: + ticks = iter(range(1000)) + report = probe_read_routes( + _demo_har(app), + sandbox_base_url=app.base, + store_digest=lambda: str(next(ticks)), + store_reset=app.reset, + ) + assert not report.store_idle and report.read_routes == () + + +def test_probe_refuses_a_non_loopback_sandbox(app: _App) -> None: + from openadapt_flow.tx.induce import SandboxSafetyError + + with pytest.raises(SandboxSafetyError): + probe_read_routes( + _demo_har(app), + sandbox_base_url="http://192.0.2.10", + store_digest=app.digest, + store_reset=app.reset, + ) + + +def test_learned_routes_never_store_credential_fields(app: _App) -> None: + with SessionWireTap(app.base, WirePolicy(max_mutations=None)) as tap: + for _ in range(2): + _call(tap.base_url, "POST", "/search", {"csrf_token": "t0k", "page": 1}) + har = tap.export_har() + report = probe_read_routes( + har, sandbox_base_url=app.base, store_digest=app.digest, store_reset=app.reset + ) + assert report.read_routes[0].body_equals == (("page", "1"),) diff --git a/packages/flow/tests/test_tx_post_reads_live.py b/packages/flow/tests/test_tx_post_reads_live.py new file mode 100644 index 0000000000..9e618920f1 --- /dev/null +++ b/packages/flow/tests/test_tx_post_reads_live.py @@ -0,0 +1,288 @@ +"""Read-only ``POST``s on a real app (#2389), lab only. + +Runs against a local Medplum started with ``benchmark/fhir_medplum``'s +fixture when ``OAFLOW_TX_LIVE_MEDPLUM_STATE`` names the fixture's state +directory (``OAFLOW_TX_LIVE_MEDPLUM_PORT`` and ``_PROJECT`` override the port +and compose project). It is skipped otherwise. Synthetic records only. + +The benchmark found that FHIR batch reads (``POST /fhir/R4``) and GraphQL +queries (``POST /fhir/R4/$graphql``) used up the tap's single mutation, so the +real save got 403. FHIR search by ``POST`` (``/Patient/_search``) is the same +class with no protocol marker, so it is learned on the sandbox instead. The +store digest hashes every table in the app's database. +""" + +from __future__ import annotations + +import json +import os +import secrets +import urllib.request +from pathlib import Path +from typing import Any, Optional + +import pytest + +STATE = os.environ.get("OAFLOW_TX_LIVE_MEDPLUM_STATE", "").strip() +PORT = int(os.environ.get("OAFLOW_TX_LIVE_MEDPLUM_PORT", "9744")) +PROJECT = os.environ.get("OAFLOW_TX_LIVE_MEDPLUM_PROJECT", "lens-medplum") + +pytestmark = pytest.mark.skipif(not STATE, reason="set OAFLOW_TX_LIVE_MEDPLUM_STATE") + +DIGEST_SQL = ( + "select md5(string_agg(md5(query_to_xml(format('select * from %I.%I order by 1'," + " schemaname, tablename), true, false, '')::text), '' order by tablename))" + " from pg_tables where schemaname='public'" +) + + +def _req( + base: str, + method: str, + path: str, + token: str, + body: Optional[bytes] = None, + ctype: str = "application/fhir+json", +) -> tuple[int, Any]: + request = urllib.request.Request( + base + path, + data=body, + method=method, + headers={"Authorization": "Bearer " + token, "Content-Type": ctype}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as resp: + raw = resp.read() + status = resp.status + except urllib.error.HTTPError as err: + raw, status = err.read(), err.code + try: + return status, json.loads(raw or b"null") + except ValueError: + return status, None + + +@pytest.fixture(scope="module") +def live() -> dict[str, Any]: + from benchmark.fhir_medplum.fixture import MedplumFixture + + fx = MedplumFixture( + state_dir=Path(STATE), server_port=PORT, app_port=PORT + 1, project=PROJECT + ) + token = fx.client_token("lens") + family = "Lensprobe" + secrets.token_hex(3) + patient = { + "resourceType": "Patient", + "name": [{"family": family, "given": ["Casey"]}], + "birthDate": "1980-02-03", + "telecom": [{"system": "email", "value": f"{family.lower()}@example.test"}], + } + pid = fx.create_patient(patient, token=token) + base = fx.base_url.replace("localhost", "127.0.0.1") + _, original = _req(base, "GET", f"/fhir/R4/Patient/{pid}", token) + return { + "fx": fx, + "token": token, + "pid": pid, + "family": family, + "base": base, + "original": original, + } + + +def _reads(live: dict[str, Any]) -> list[tuple[str, str, bytes, str]]: + pid, family = live["pid"], live["family"] + batch = { + "resourceType": "Bundle", + "type": "batch", + "entry": [ + {"request": {"method": "GET", "url": f"Patient/{pid}"}}, + {"request": {"method": "GET", "url": f"Patient?family={family}"}}, + ], + } + gql = {"query": f'{{ PatientList(family: "{family}") {{ id name {{ family }} }} }}'} + return [ + ("POST", "/fhir/R4", json.dumps(batch).encode(), "application/fhir+json"), + ("POST", "/fhir/R4/$graphql", json.dumps(gql).encode(), "application/json"), + ( + "POST", + "/fhir/R4/Patient/_search", + f"family={family}&_count=5".encode(), + "application/x-www-form-urlencoded", + ), + ] + + +def _save_body(live: dict[str, Any], email: str) -> bytes: + body = {k: v for k, v in live["original"].items() if k != "meta"} + body["telecom"] = [{"system": "email", "value": email}] + return json.dumps(body).encode() + + +def _restore(live: dict[str, Any]) -> None: + body = {k: v for k, v in live["original"].items() if k != "meta"} + status, _ = _req( + live["base"], + "PUT", + f"/fhir/R4/Patient/{live['pid']}", + live["token"], + json.dumps(body).encode(), + ) + assert status == 200 + + +def _through_tap(tap: Any, live: dict[str, Any], calls: list) -> list[int]: + return [ + _req(tap.base_url, m, p, live["token"], body, ctype)[0] + for m, p, body, ctype in calls + ] + + +def test_live_batch_and_graphql_reads_are_classified_as_reads(live) -> None: + from openadapt_flow.tx.wire_tap import SessionWireTap, WirePolicy + + with SessionWireTap(live["base"], WirePolicy(max_mutations=1)) as tap: + statuses = _through_tap(tap, live, _reads(live)[:2]) + summary = tap.summary() + assert statuses == [200, 200] + assert summary.read_requests == 2 and summary.mutations_allowed == 0 + + +def test_live_probe_learns_post_search_and_refuses_the_save(live) -> None: + from openadapt_flow.tx.read_probe import probe_read_routes + from openadapt_flow.tx.wire_tap import SessionWireTap, WirePolicy + + pid = live["pid"] + with SessionWireTap( + live["base"], WirePolicy(max_mutations=None, secrets=(live["token"],)) + ) as tap: + calls = _reads(live) + [ + ( + "PUT", + f"/fhir/R4/Patient/{pid}", + _save_body(live, "demo@example.test"), + "application/fhir+json", + ), + # A second save, by POST to the type's _search sibling, would be a + # different route; the save here is the PUT above. + ] + _through_tap(tap, live, calls) + har = tap.export_har() + _restore(live) + + fx = live["fx"] + report = probe_read_routes( + har, + sandbox_base_url=live["base"], + store_digest=lambda: fx.psql(DIGEST_SQL).strip(), + store_reset=lambda: _restore(live), + headers={"Authorization": "Bearer " + live["token"]}, + ) + by_path = {r.path: r for r in report.routes} + assert report.store_idle + # Only the unmarked POST read is probed; batch and GraphQL reads were + # already reads, and the PUT is not a POST. + assert set(by_path) == {"/fhir/R4/Patient/_search"} + search = by_path["/fhir/R4/Patient/_search"] + assert search.read_only, search.reason + live["read_routes"] = report.read_routes + + +def test_live_save_goes_through_after_post_reads(live) -> None: + from openadapt_flow.tx.wire_tap import SessionWireTap, WirePolicy + + if "read_routes" not in live: + pytest.skip("needs the probe test's learned routes") + pid = live["pid"] + policy = WirePolicy(max_mutations=1, read_routes=live["read_routes"]) + with SessionWireTap(live["base"], policy) as tap: + calls = _reads(live) + [ + ( + "PUT", + f"/fhir/R4/Patient/{pid}", + _save_body(live, "saved@example.test"), + "application/fhir+json", + ), + ( + "PUT", + f"/fhir/R4/Patient/{pid}", + _save_body(live, "second@example.test"), + "application/fhir+json", + ), + ] + statuses = _through_tap(tap, live, calls) + summary = tap.summary() + # Three reads, the one save, and a second write still blocked. + assert statuses == [200, 200, 200, 200, 403] + assert summary.read_requests == 3 + assert summary.mutations_allowed == 1 and summary.mutations_blocked == 1 + _, stored = _req(live["base"], "GET", f"/fhir/R4/Patient/{pid}", live["token"]) + assert stored["telecom"] == [{"system": "email", "value": "saved@example.test"}] + _restore(live) + + +def test_live_learned_route_does_not_cover_a_post_write(live) -> None: + """A POST create on another path is never covered by the learned read.""" + from openadapt_flow.tx.wire_tap import matches_read_route + + if "read_routes" not in live: + pytest.skip("needs the probe test's learned routes") + body = json.dumps({"resourceType": "Patient"}).encode() + assert not matches_read_route( + live["read_routes"], + "POST", + "/fhir/R4/Patient", + body, + [("Content-Type", "application/fhir+json")], + ) + + +def test_live_wrapped_save_is_not_refuted_by_post_reads(live, tmp_path) -> None: + """The benchmark's second symptom: correct saves came back REFUTED.""" + from openadapt_flow.tx.lens import TransactionalCommitEngine + from openadapt_flow.tx.types import EndpointTemplate, EntityLensSpec, TxTask + from openadapt_flow.tx.wire_tap import SessionWireTap, WirePolicy + + if "read_routes" not in live: + pytest.skip("needs the probe test's learned routes") + pid = live["pid"] + item = "/fhir/R4/Patient/{id}" + lens = EntityLensSpec( + entity_name="patient", + base_url=live["base"], + write_mode="replace", + get_one=EndpointTemplate(method="GET", path_template=item), + write_endpoint=EndpointTemplate(method="PUT", path_template=item), + ) + task_id = "live-" + secrets.token_hex(4) + policy = WirePolicy(max_mutations=1, read_routes=live["read_routes"]) + with SessionWireTap(live["base"], policy, session_id=task_id) as tap: + engine = TransactionalCommitEngine( + lens, + tmp_path / "engine", + wire_tap=tap, + headers={"Authorization": "Bearer " + live["token"]}, + allow_unqualified_prototype=True, + ) + body = {k: v for k, v in live["original"].items() if k != "meta"} + body["birthDate"] = "1981-04-05" + calls = _reads(live) + [ + ( + "PUT", + f"/fhir/R4/Patient/{pid}", + json.dumps(body).encode(), + "application/fhir+json", + ) + ] + result = engine.wrap_action( + TxTask( + task_id=task_id, + operation="update", + entity_id=pid, + intended_delta={"birthDate": "1981-04-05"}, + ), + lambda: _through_tap(tap, live, calls), + ) + _restore(live) + assert result.outcome == "UNCERTAIN", result.reasons + assert set(result.reasons) == {"unqualified_observation_only"} From cc1567a474bcead4a7b72c01930ad2e90386efc2 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:02:17 -0500 Subject: [PATCH 2/2] fix(tx): a read route needs a body discriminator Review finding: with an empty body_equals, all(()) matched any body on the route's path, so a write sent to a path that also served reads would be counted as a read and skip the mutation budget. _constant_fields returns () when every field varies or is a credential, which a form that both searches and saves produces. ReadRoute now rejects an empty body_equals, matches_read_route skips any such entry, and probe_read_routes refuses a route whose samples share no constant field. A test pins that a write on such a path still uses the budget. Signed-off-by: abrichr --- packages/flow/openadapt_flow/tx/read_probe.py | 12 +++++++++ packages/flow/openadapt_flow/tx/wire_tap.py | 17 ++++++++++--- packages/flow/tests/test_tx_post_reads.py | 25 +++++++++++++++++++ 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/packages/flow/openadapt_flow/tx/read_probe.py b/packages/flow/openadapt_flow/tx/read_probe.py index 82fd359617..d2b59d752e 100644 --- a/packages/flow/openadapt_flow/tx/read_probe.py +++ b/packages/flow/openadapt_flow/tx/read_probe.py @@ -266,6 +266,18 @@ def probe_read_routes( ) ) continue + if not body_equals: + probes.append( + ReadRouteProbe( + method=method, + path=path, + samples=len(samples), + read_only=False, + reason="no body field was constant across the samples, so " + "nothing tells a read on this path from a write", + ) + ) + continue reason = "every replay returned 2xx and left the store unchanged" read_only = True for sample in samples: diff --git a/packages/flow/openadapt_flow/tx/wire_tap.py b/packages/flow/openadapt_flow/tx/wire_tap.py index 56405b0593..7925a4c805 100644 --- a/packages/flow/openadapt_flow/tx/wire_tap.py +++ b/packages/flow/openadapt_flow/tx/wire_tap.py @@ -25,7 +25,7 @@ from typing import Any, Callable, Iterable, Mapping, NamedTuple, Optional, cast from urllib.parse import parse_qsl, unquote, urlsplit -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, field_validator from openadapt_flow.secret_redaction import MASK, credential_header, mask_header from openadapt_flow.tx.receipt import write_private_record @@ -85,7 +85,18 @@ class ReadRoute(BaseModel): method: str = "POST" path: str - body_equals: tuple[tuple[str, str], ...] = () + body_equals: tuple[tuple[str, str], ...] + + @field_validator("body_equals") + @classmethod + def _needs_a_discriminator( + cls, value: tuple[tuple[str, str], ...] + ) -> tuple[tuple[str, str], ...]: + # With no body field to match, a read route would also match a write + # sent to the same path (a form that both searches and saves). + if not value: + raise ValueError("a read route needs at least one body_equals field") + return value class WirePolicy(BaseModel): @@ -605,7 +616,7 @@ def matches_read_route( if not fields_parsed: fields = _top_level_body_fields(request_body, request_headers) fields_parsed = True - if fields is None: + if fields is None or not route.body_equals: continue if all(fields.get(k) == v for k, v in route.body_equals): return True diff --git a/packages/flow/tests/test_tx_post_reads.py b/packages/flow/tests/test_tx_post_reads.py index 9b3704bc30..fd7961189e 100644 --- a/packages/flow/tests/test_tx_post_reads.py +++ b/packages/flow/tests/test_tx_post_reads.py @@ -346,3 +346,28 @@ def test_learned_routes_never_store_credential_fields(app: _App) -> None: har, sandbox_base_url=app.base, store_digest=app.digest, store_reset=app.reset ) assert report.read_routes[0].body_equals == (("page", "1"),) + + +def test_read_route_without_a_body_discriminator_is_rejected() -> None: + from pydantic import ValidationError + + with pytest.raises(ValidationError): + ReadRoute(path=r"/search", body_equals=()) + + +def test_probe_refuses_a_route_whose_bodies_share_no_field(app: _App) -> None: + """A form path that both searches and saves: nothing is constant.""" + with SessionWireTap(app.base, WirePolicy(max_mutations=None)) as tap: + _call(tap.base_url, "POST", "/search", {"q": "a"}) + _call(tap.base_url, "POST", "/search", {"term": "b"}) + har = tap.export_har() + report = probe_read_routes( + har, sandbox_base_url=app.base, store_digest=app.digest, store_reset=app.reset + ) + (route,) = report.routes + assert not route.read_only and "nothing tells a read" in route.reason + assert report.read_routes == () + # With nothing learned, a write on that path is still a mutation. + with SessionWireTap(app.base, WirePolicy(max_mutations=1)) as tap: + assert _call(tap.base_url, "POST", "/search", {"q": "c"}) == 200 + assert _call(tap.base_url, "POST", "/rec/1", {"note": "x"}) == 403