diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index a43eb01f9c..1ba0b72c50 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -1140,6 +1140,13 @@ this computer's device key and, in organization mode, the organization's key files at rest, not a running session: anyone who can run commands as the signed-in person can read them, as Flow does. +A network capture keeps only declared fields by default. What reads a +capture (undo proposals, record checks, API steps, readiness import) works +from the kept fields or refuses, naming the withheld field. It never treats +a withheld body as empty. API steps and record checks from the app's reads +need `--capture-network-bodies raw` +([`NETWORK_CAPTURE.md`](NETWORK_CAPTURE.md#bodies-minimized-by-default)). + See [`SANITIZED_ARTIFACTS.md`](SANITIZED_ARTIFACTS.md) for the review and exact-hash workflow, [`PRIVACY.md`](PRIVACY.md) for the field-level data map, and [`ENTERPRISE_ARCHITECTURE.md`](ENTERPRISE_ARCHITECTURE.md) for component diff --git a/packages/flow/docs/NETWORK_CAPTURE.md b/packages/flow/docs/NETWORK_CAPTURE.md index 0965543d6a..f50c5c9871 100644 --- a/packages/flow/docs/NETWORK_CAPTURE.md +++ b/packages/flow/docs/NETWORK_CAPTURE.md @@ -96,9 +96,32 @@ headers (`Location`, `Referer`, `Content-Location`, `Refresh`). A HAR that is marked minimized but has a body with other text or form `params` is refused when loaded (`load_har`, `from_har`). -Readers find no body in a minimized file and propose nothing from it: no -API step, no undo proposal, no record check from the app's reads. Record -with `--capture-network-bodies raw` for those and for debugging. Raw is +Readers rebuild what they need from the kept fields, or refuse and say +why; none reads a withheld body as an empty one +(`openadapt_flow/capture_bodies.py`): + +- **Undo proposal** finds the save by its kept record fields and reads the + new record's id from the kept response fields (declare it with + `--identifier`). A selector field the capture withheld, a later write it + withheld, or a withheld id refuses the network undo. +- **Record check** (`scaffold-verifier`) matches on the save's kept sent + values and notes the withheld ones. A write it can't read is listed as + not covered, with that reason. It does not build a check from the app's + reads, since a minimized response keeps only declared fields (a page, + nothing). Read discovery (`--probe-reads`) refuses when the capture + withheld any field of a write, since a withheld value would count as + not sent. +- **`--prove`** sends the save's body, so it refuses unless every field was + kept. +- **Reference import** (`readiness import`) compares only fields that were + kept, and refuses when a task field was withheld. +- **API steps** are not proposed: they send every field of the save again, + and a form save also needs the form page. +- **Lens induction from a capture** (`tx.network_bridge`) raises an error. + +An opaque or cut body is refused as unreadable. Record with +`--capture-network-bodies raw` for API steps, record checks from reads and +debugging, or declare the fields a reader needs. Raw is refused unless the recording is encrypted (set `OPENADAPT_RECORDING_KEY` or `OPENADAPT_BUNDLE_KEY`, or use `OPENADAPT_FLOW_AT_REST=strict`; never with `--no-encrypt`) or `OPENADAPT_FLOW_PLAINTEXT_AT_REST` explicitly allows diff --git a/packages/flow/openadapt_flow/capture_bodies.py b/packages/flow/openadapt_flow/capture_bodies.py new file mode 100644 index 0000000000..e5bf4906e7 --- /dev/null +++ b/packages/flow/openadapt_flow/capture_bodies.py @@ -0,0 +1,311 @@ +"""Read the request and response bodies of a network capture line. + +Since captures keep only declared fields (:mod:`openadapt_flow.capture_privacy`), +a ``network.jsonl`` line usually has no ``body``, ``form`` or +``response_text``. It has ``body_minimized``, ``form_minimized`` or +``response_minimized`` instead: the declared (kept) fields with their values, +and every other field as a keyed hash (withheld). A reader that looks only at +``body`` or ``form`` sees nothing in such a capture and must not treat that +as "the request sent nothing". + +:func:`request_body` and :func:`response_body` give a reader one view of +either kind of line: + +- a raw line (``body``, ``form`` or ``response_text``) is returned as it is; +- a minimized form is rebuilt as its kept ``[name, value]`` pairs, and a + minimized JSON body as a JSON document of its kept fields + (:func:`openadapt_flow.capture_privacy.restore_kept_json`). Withheld values + are absent, never guessed; +- an opaque or cut minimized body kept nothing to read and raises + :class:`BodyUnreadable`; +- a field the reader needs that the capture withheld raises + :class:`FieldsWithheld`, naming the field and the recording flags that keep + it. Session tokens and secrets (:func:`is_withheld_name`) are withheld like + any other field: a reader that needs one is refused. + +A rebuilt JSON body is the kept fields only. Empty objects and lists, and the +order of keys, are not kept, so a rebuilt body is fit for finding and matching +a request, not for sending it again as the recorded request (an API step). +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from typing import Any, Iterable, Literal, Mapping, Optional, Union + +#: ``need=ALL``: every field of the body must have been kept. +ALL = "all" + +#: How to keep a field's value in the next recording. +RECORD_HINT = ( + "record with each field declared (--param or --identifier), or with " + "--capture-network-bodies raw on a sealed recording" +) + +#: Request types whose UTF-8 body a raw capture keeps as text. +_TEXT_REQUEST = re.compile(r"^text/|json|xml|javascript|graphql", re.I) + + +class CaptureBodyRefused(ValueError): + """A body the reader can't read from the capture. ``code`` is closed.""" + + code = "body_refused" + + def __init__(self, why: str, fields: Iterable[str] = ()) -> None: + super().__init__(why) + self.why = why + self.fields = tuple(fields) + + +class BodyUnreadable(CaptureBodyRefused): + """The capture kept nothing of the body to read (opaque or cut).""" + + code = "body_unreadable" + + +class FieldsWithheld(CaptureBodyRefused): + """The capture withheld a field the reader needs.""" + + code = "fields_withheld" + + +@dataclass(frozen=True) +class CapturedBody: + """One side of a capture line as a reader sees it. + + ``kind`` is ``"form"``, ``"json"`` (a minimized JSON body, rebuilt), + ``"text"`` (a raw body: the reader parses it) or None (no body). + ``form`` holds ``[name, value]`` pairs; ``text`` the body text + (for a minimized JSON body, the rebuilt kept fields). ``withheld`` and + ``secrets`` are the full paths the capture withheld; both are empty for a + raw body. + """ + + kind: Optional[Literal["form", "json", "text"]] + text: Optional[str] = None + form: Optional[list[list[Any]]] = None + minimized: bool = False + kept: tuple[str, ...] = () + withheld: tuple[str, ...] = () + secrets: tuple[str, ...] = field(default=()) + + @property + def withheld_all(self) -> tuple[str, ...]: + """Every withheld path, secrets included.""" + return self.withheld + self.secrets + + +def is_withheld_name(name: str) -> bool: + """A session token or password-like field: never kept. + + The same names as ``agent_guard.shadow_hold.is_withheld_name``, read from + the capture's own patterns so core readers don't import the agent guard. + """ + from openadapt_flow.network_capture import SECRET_NAME, TOKEN_NAME + + leaf = name.rsplit(".", 1)[-1] + return bool(TOKEN_NAME.search(leaf) or SECRET_NAME.search(leaf)) + + +def _leaf(path: str) -> str: + """The last named segment of a dotted path (list indices dropped).""" + named = [p for p in str(path).split(".") if p and not p.isdigit()] + return named[-1] if named else str(path) + + +def withheld_leaves(body: CapturedBody) -> frozenset[str]: + """The leaf names of every withheld path (secrets included).""" + return frozenset(_leaf(p) for p in body.withheld_all) + + +def request_body( + line: Mapping[str, Any], + *, + need: Union[None, str, Iterable[str]] = None, + what: str = "request", +) -> CapturedBody: + """The request body of ``line``, rebuilt from a minimized capture. + + ``need`` is checked only for a minimized body: :data:`ALL` (every field + but session tokens and secrets), or the full paths (case-exact) the + reader needs. ``what`` names the request in a refusal ("the save"). + """ + if "form" in line or "body" in line: + form = line.get("form") + if isinstance(form, list): + return CapturedBody(kind="form", form=[list(p) for p in form]) + body = line.get("body") + text = body if isinstance(body, str) else None + return CapturedBody(kind="text" if text is not None else None, text=text) + form_minimized = line.get("form_minimized") + if isinstance(form_minimized, Mapping): + return _rebuild(form_minimized, need, what, form=True) + if "body_minimized" not in line: + return CapturedBody(kind=None) + minimized = line.get("body_minimized") + if minimized is None: + return CapturedBody(kind=None, minimized=True) # an empty body + if not isinstance(minimized, Mapping): + raise BodyUnreadable(f"the capture did not keep {_the(what)}'s body") + return _rebuild(minimized, need, what, form=minimized.get("format") == "form") + + +def response_body( + line: Mapping[str, Any], + *, + need: Union[None, str, Iterable[str]] = None, + what: str = "response", +) -> CapturedBody: + """The response body of ``line``, rebuilt from a minimized capture. + + As :func:`request_body`. A minimized HTML or text response is always + opaque, so it raises :class:`BodyUnreadable`. + """ + if "response_text" in line: + text = line.get("response_text") + return CapturedBody( + kind="text" if isinstance(text, str) else None, + text=text if isinstance(text, str) else None, + ) + minimized = line.get("response_minimized") + if minimized is None: + return CapturedBody(kind=None, minimized="response_minimized" in line) + if not isinstance(minimized, Mapping): + raise BodyUnreadable(f"the capture did not keep {_the(what)}'s body") + return _rebuild(minimized, need, what, form=minimized.get("format") == "form") + + +def request_hidden(line: Mapping[str, Any], *, raw_capture: bool = False) -> bool: + """Whether the capture minimized away a request body a raw capture keeps. + + A raw capture keeps a readable body as ``body`` or ``form``. It also + writes an opaque ``body_minimized``, for a body that isn't UTF-8 or a + multipart body with a file (``body_omitted``); a raw capture has no more + of that one, so it is not hidden. A minimized form or JSON body always + is. An opaque body is hidden when a raw capture would have kept it as + text: a textual or unlabelled type, not a form (a readable form is always + ``form_minimized``). ``raw_capture``: the capture header says raw, so + nothing is hidden. + """ + if raw_capture or "form" in line or "body" in line: + return False + if isinstance(line.get("form_minimized"), Mapping): + return True + minimized = line.get("body_minimized") + if not isinstance(minimized, Mapping): + return False + if minimized.get("format") != "opaque": + return True + if line.get("body_omitted"): + return False + ctype = _ctype(minimized.get("content_type") or line.get("request_type")) + if ctype.startswith("multipart/") or ctype == "application/x-www-form-urlencoded": + return False + return ctype == "" or bool(_TEXT_REQUEST.search(ctype)) + + +def response_hidden(line: Mapping[str, Any], *, raw_capture: bool = False) -> bool: + """Whether the capture minimized away a response a raw capture keeps as + text: a minimized JSON or form response, or an opaque one of a type a raw + capture writes as text (``network_capture._TEXT_MIME``: HTML, JSON, plain + text). Any other response (binary, ``text/xml``) is opaque in a raw + capture too, so it is not hidden.""" + from openadapt_flow.network_capture import _TEXT_MIME + + if raw_capture or "response_text" in line: + return False + minimized = line.get("response_minimized") + if not isinstance(minimized, Mapping): + return False + if minimized.get("format") != "opaque": + return True + ctype = _ctype(minimized.get("content_type") or line.get("response_type")) + return bool(_TEXT_MIME.search(ctype)) + + +def _ctype(value: Any) -> str: + return str(value or "").split(";")[0].strip().lower() + + +def _the(what: str) -> str: + return what if what.startswith("the ") else f"the {what}" + + +def _rebuild( + minimized: Mapping[str, Any], + need: Union[None, str, Iterable[str]], + what: str, + *, + form: bool, +) -> CapturedBody: + from openadapt_flow.capture_privacy import restore_kept_json + + if ( + minimized.get("format") == "opaque" + or minimized.get("truncated") + or ("kept" not in minimized and "withheld" not in minimized) + ): + raise BodyUnreadable(f"the capture did not keep {_the(what)}'s body") + kept = [ + [str(item[0]), item[1]] + for item in minimized.get("kept") or [] + if isinstance(item, list) and len(item) == 2 + ] + withheld_paths = [ + str(item[0]) + for item in minimized.get("withheld") or [] + if isinstance(item, list) and item + ] + secrets = tuple(w for w in withheld_paths if is_withheld_name(w)) + withheld = tuple(w for w in withheld_paths if not is_withheld_name(w)) + kept_paths = tuple(path for path, _ in kept) + if need is not None: + if isinstance(need, str): + if need != ALL: + raise ValueError(f"need must be ALL or field paths, not {need!r}") + missing = sorted(set(withheld)) + else: + present = set(kept_paths) + missing = sorted({str(n) for n in need if str(n) not in present}) + if missing or not kept: + names = ", ".join(missing) or "every field" + raise FieldsWithheld( + f"the capture withheld {_the(what)}'s {names}; {RECORD_HINT}", + missing, + ) + if form: + return CapturedBody( + kind="form", + form=kept, + minimized=True, + kept=kept_paths, + withheld=withheld, + secrets=secrets, + ) + text: Optional[str] = None + if kept: + restored = restore_kept_json(minimized) + if not restored: + # Kept paths that collide: rebuild nothing rather than guess. + raise BodyUnreadable(f"the capture did not keep {_the(what)}'s body") + text = restored.decode("utf-8") + return CapturedBody( + kind="json", + text=text, + minimized=True, + kept=kept_paths, + withheld=withheld, + secrets=secrets, + ) + + +def json_document(body: CapturedBody) -> Any: + """``body.text`` parsed as JSON, or None (no text, or not JSON).""" + if body.text is None or not body.text.strip(): + return None + try: + return json.loads(body.text) + except ValueError: + return None diff --git a/packages/flow/openadapt_flow/compiler/api_proposal.py b/packages/flow/openadapt_flow/compiler/api_proposal.py index 8db07df67d..4342e98d01 100644 --- a/packages/flow/openadapt_flow/compiler/api_proposal.py +++ b/packages/flow/openadapt_flow/compiler/api_proposal.py @@ -29,6 +29,9 @@ request, a save done over a websocket, a desktop app); - the form page was not captured (start the recording before opening the form); +- the capture kept only declared fields of the save's request (the default, + ``--capture-network-bodies minimized``): the API step would send again + fields it can't see, so it needs ``--capture-network-bodies raw``; - the save sends a secret field, or a field the compiler can't explain; - the save is not the program's last step (steps after it would expect the page the save left); @@ -59,6 +62,7 @@ from openadapt_flow import network_capture as nc from openadapt_flow import sealed_set as _sealed from openadapt_flow.bundle_validation import derive_authored_workflow +from openadapt_flow.capture_bodies import request_hidden, response_hidden from openadapt_flow.ir import ( ActionKind, ApiAdmission, @@ -81,6 +85,13 @@ web_form_effects, ) +#: Why a save from a capture that kept only declared fields gets no API step. +MINIMIZED_SAVE = ( + "the capture kept only the declared fields of the save's request ({what}); " + "an API step sends again every field the save sent, and a form save also " + "needs the form page, so record with --capture-network-bodies raw" +) + class ApiProposalError(ValueError): """The API step can't be admitted (or the proposal input is malformed).""" @@ -588,6 +599,7 @@ def propose_api_step( lines = nc.load(recording) if not lines: return workflow, None, ["the recording has no network capture"] + raw_capture = nc.bodies_mode(recording) == "raw" if workflow.program is not None: return ( workflow, @@ -630,6 +642,21 @@ def propose_api_step( def carried(line: dict[str, Any]) -> int: return sum(1 for _, v in line.get("form") or [] if v in by_value) + # An API step sends again every field the save sent, and a form save + # also needs the form page: a capture that kept only declared fields + # holds neither, so it proposes nothing rather than guess. + hidden = [ + ln + for ln in lines + if ln["method"] in ("POST", "PUT", "PATCH") + and t_prev < float(ln["t"]) <= t_end + and not ln.get("failed") + and request_hidden(ln, raw_capture=raw_capture) + ] + if hidden: + what = f"{hidden[0]['method']} {_path(hidden[0]['url'])}" + return workflow, None, [MINIMIZED_SAVE.format(what=what)] + posts = [ ln for ln in lines @@ -649,7 +676,15 @@ def carried(line: dict[str, Any]) -> int: ] if json_saves: return _propose_json( - workflow, steps, save, events, lines, params, by_value, json_saves + workflow, + steps, + save, + events, + lines, + params, + by_value, + json_saves, + raw_capture=raw_capture, ) return workflow, None, ["no form request was sent by the save step"] # The save is the last request that carries the most recorded values: a @@ -1145,6 +1180,8 @@ def _propose_json( params: dict[str, str], by_value: dict[str, list[str]], candidates: list[dict[str, Any]], + *, + raw_capture: bool = False, ) -> tuple[Workflow, Optional[Step], list[str]]: """A save the page's script sent as JSON (a GraphQL mutation included). @@ -1297,6 +1334,13 @@ def carried(line: dict[str, Any]) -> int: if lo < float(ln["t"]) <= hi and (ln["method"] == "GET" or _graphql_read(ln)) ] + if texts and any(response_hidden(ln, raw_capture=raw_capture) for ln in reads): + # Whether the server answered the check can't be told. + return refuse( + f"{step.id} checks text on screen, and the capture kept only " + "declared fields of the responses read during it; record with " + "--capture-network-bodies raw" + ) if any(t in (ln.get("response_text") or "") for t in texts for ln in reads): # The server answered the check (a duplicate search, a lookup): # the API step would skip it, so the save stays on the GUI. diff --git a/packages/flow/openadapt_flow/read_discovery.py b/packages/flow/openadapt_flow/read_discovery.py index f84f5ac15d..68c89906cc 100644 --- a/packages/flow/openadapt_flow/read_discovery.py +++ b/packages/flow/openadapt_flow/read_discovery.py @@ -208,6 +208,19 @@ def candidates_for( return list(dict.fromkeys(out)) +def _unseen_write( + writes: Sequence[Mapping[str, Any]], search: rcs.ReadSearch +) -> Optional[str]: + """Why the capture doesn't show everything a write sent (its body is + unreadable, or fields of it were withheld), for the first such write.""" + + for line in writes: + why = rcs._write_unseen(line, raw_capture=search.raw_capture) + if why: + return why + return None + + def _sent_params(line: Mapping[str, Any], params: Mapping[str, str]) -> dict[str, str]: """Parameter name -> value, for each parameter value the write sent.""" @@ -266,6 +279,12 @@ def unavailable(reason: str) -> None: if not writes: unavailable("the capture holds no accepted create or update request") return None + unseen = _unseen_write(writes, search) + if unseen: + # A read is promoted when it holds the values the write sent; a value + # the capture withheld would count as "not sent". + unavailable(unseen) + return None if probe_base is not None and not is_local_origin(probe_base): unavailable( f"the probe base {urlsplit(probe_base).hostname} is not the local " @@ -485,9 +504,20 @@ def none(reason: str) -> None: if not is_local_origin(base): none(f"{urlsplit(base).hostname} is not the local machine") return None + unseen = _unseen_write(writes, search) + if unseen: + # The values a write sent are what a covering read must hold; a + # value the capture withheld would count as "not sent" here. + none(unseen) + return None sent = _sent_params(writes[0], params) if writes else {} for line in writes[1:]: sent.update(_sent_params(line, params)) + if not sent: + # With no written value, any read holds them all and proves nothing + # (discover() skips such a write for the same reason). + none("the write sent no recorded parameter value") + return None budget = [MAX_COVER_PROBES] diff --git a/packages/flow/openadapt_flow/readiness/reference.py b/packages/flow/openadapt_flow/readiness/reference.py index 4fe7bbd926..ccd2ce5b39 100644 --- a/packages/flow/openadapt_flow/readiness/reference.py +++ b/packages/flow/openadapt_flow/readiness/reference.py @@ -269,26 +269,7 @@ def _from_network( return None rows = network_capture.load(recording) line = _save_line(rows, raw, app_origin) - body = line.get("body") - form_pairs = line.get("form") - secrets_withheld = 0 - body_minimized = line.get("body_minimized") - form_minimized = line.get("form_minimized") - if body is None and form_pairs is None: - # A minimized capture (the default since captures keep only declared - # fields): rebuild the save from what it kept, or refuse. - from openadapt_flow.capture_privacy import restore_kept_json - - if isinstance(form_minimized, Mapping): - form_pairs, secrets_withheld = _kept_fields(form_minimized, raw) - elif isinstance(body_minimized, Mapping): - _kept, secrets_withheld = _kept_fields(body_minimized, raw) - restored = restore_kept_json(body_minimized) - if not restored: - raise ReferenceRefused( - "save_unreadable", "the capture did not keep the save's body" - ) - body = restored.decode("utf-8") + body, form_pairs, secrets_withheld = _save_body(line, raw) fields, withheld = parse_body_fields( method=str(line.get("method")), url=str(line.get("url")), @@ -356,10 +337,10 @@ def stamp(t: Optional[float]) -> Optional[str]: } -def _kept_fields( - minimized: Mapping[str, Any], raw: Mapping[str, Any] -) -> tuple[list[list[Any]], int]: - """The kept ``[path, value]`` pairs of a minimized save, checked for use. +def _save_body( + line: Mapping[str, Any], raw: Mapping[str, Any] +) -> tuple[Optional[str], Optional[list[list[Any]]], int]: + """``(body, form_pairs, secrets_withheld)`` of the save, checked for use. Since captures keep only declared fields by default, a save recorded without declaring its fields has every value withheld (hashed). The @@ -371,43 +352,28 @@ def _kept_fields( that keeps it, instead of comparing part of the save. Session tokens and secrets are never compared, so their being withheld is expected; they are counted, as for a raw body. An opaque or truncated body kept nothing to - read and refuses as unreadable. + read and refuses as unreadable (:mod:`openadapt_flow.capture_bodies`). """ - from openadapt_flow.agent_guard.shadow_hold import is_withheld_name + from openadapt_flow.capture_bodies import ( + ALL, + BodyUnreadable, + CaptureBodyRefused, + request_body, + ) - if minimized.get("format") == "opaque" or ( - "kept" not in minimized and "withheld" not in minimized - ): - raise ReferenceRefused( - "save_unreadable", "the capture did not keep the save's body" - ) - kept = [ - [str(item[0]), item[1]] - for item in minimized.get("kept") or [] - if isinstance(item, list) and len(item) == 2 - ] - kept_paths = {path for path, _ in kept} - withheld_paths = [ - str(item[0]) - for item in minimized.get("withheld") or [] - if isinstance(item, list) and item - ] - secrets = [w for w in withheld_paths if is_withheld_name(w)] - withheld = [w for w in withheld_paths if not is_withheld_name(w)] wanted = raw.get("fields") - if isinstance(wanted, list) and wanted: - missing = sorted(str(name) for name in wanted if str(name) not in kept_paths) - else: - missing = sorted(set(withheld)) - if missing or not kept: - names = ", ".join(missing) or "every field" - raise ReferenceRefused( - "save_fields_withheld", - f"the capture withheld the save's {names}; record with each field " - "declared (--param or --identifier), or with " - "--capture-network-bodies raw on a sealed recording", - ) - return kept, len(secrets) + need = [str(n) for n in wanted] if isinstance(wanted, list) and wanted else ALL + try: + seen = request_body(line, need=need, what="save") + except BodyUnreadable as exc: + raise ReferenceRefused("save_unreadable", exc.why) from exc + except CaptureBodyRefused as exc: + raise ReferenceRefused("save_fields_withheld", exc.why) from exc + if seen.kind == "json": + return seen.text, None, len(seen.secrets) + if seen.kind == "form": + return None, seen.form, len(seen.secrets) + return seen.text, None, 0 def network_capture_path(url: str) -> str: diff --git a/packages/flow/openadapt_flow/record_check_proof.py b/packages/flow/openadapt_flow/record_check_proof.py index 83240a808f..d7d23fc7d6 100644 --- a/packages/flow/openadapt_flow/record_check_proof.py +++ b/packages/flow/openadapt_flow/record_check_proof.py @@ -157,15 +157,50 @@ def body_template( params: Mapping[str, str], default: Mapping[str, str], ) -> dict[str, str]: - """The save's JSON body with recorded values replaced by ``{param}``.""" + """The save's JSON body with recorded values replaced by ``{param}``. + + The fixture's default body stands in only when no write sent a JSON + object. A minimized capture's body is rebuilt from its kept fields, and + every one of them, session tokens and secrets included, must have been + kept: the proof sends this body, so a withheld field would be a field the + save sent and the proof doesn't. A write whose body the capture withheld, + or kept nothing of, refuses the proof instead of proving a default body. + + A rebuilt body loses key order and empty objects or lists. That is + acceptable here, unlike for an API step: this template is already a flat + rendering of the save (top-level keys, every value as text), and it is + sent only to the caller's local proof fixture, never to the recorded app. + """ import json + from openadapt_flow.capture_bodies import ( + RECORD_HINT, + CaptureBodyRefused, + request_body, + request_hidden, + ) + lookup = {value: name for name, value in params.items()} for line in write_requests: - body = line.get("body") + what = f"{line.get('method')} {urlsplit(str(line.get('url') or '')).path}" + try: + seen = request_body(line, what=what) + except CaptureBodyRefused as exc: + if not request_hidden(line): + continue # a binary body: no raw capture holds more of it + raise ProofUnavailable( + f"the proof sends the save's body, and {exc.why}" + ) from exc + if seen.kind == "form": + continue # a form post, as in a raw capture: not a JSON body + if seen.withheld_all: + raise ProofUnavailable( + f"the proof sends the save's body, and the capture withheld the " + f"{what}'s {', '.join(seen.withheld_all)}; {RECORD_HINT}" + ) try: - parsed = json.loads(body) if isinstance(body, str) else None + parsed = json.loads(seen.text) if seen.text is not None else None except ValueError: parsed = None if isinstance(parsed, dict) and parsed: diff --git a/packages/flow/openadapt_flow/record_check_synthesis.py b/packages/flow/openadapt_flow/record_check_synthesis.py index 10dbdd0c06..737abe16fd 100644 --- a/packages/flow/openadapt_flow/record_check_synthesis.py +++ b/packages/flow/openadapt_flow/record_check_synthesis.py @@ -53,6 +53,7 @@ from urllib.parse import parse_qsl, quote, urlsplit from openadapt_flow import sealed_set as _sealed +from openadapt_flow.capture_bodies import response_hidden from openadapt_flow.runtime.effects._common import judge_records from openadapt_flow.runtime.effects.effect import ( Effect, @@ -245,6 +246,8 @@ class ReadSearch: uncovered: list[str] = field(default_factory=list) #: Reads that would not work as generated. Any entry keeps it a draft. problems: list[str] = field(default_factory=list) + #: The capture header says raw bodies: no write or read is minimized. + raw_capture: bool = False #: True when every table the save could touch is read (a database path), #: or a person declared the read complete (``--complete-read``). closed_world: bool = False @@ -533,13 +536,24 @@ def _templated(url: str, lookup: Mapping[str, str]) -> _Templated: def _write_values( line: Mapping[str, Any], *, excluded_values: Iterable[str] = () ) -> dict[str, str]: - """Field -> value the write sent (form or JSON body).""" + """Field -> value the write sent (form or JSON body). + + A minimized capture's body gives its kept fields only + (:mod:`openadapt_flow.capture_bodies`); :func:`_write_unseen` says what + it withheld. Callers must not read a missing field as "not sent". + """ + + from openadapt_flow.capture_bodies import CaptureBodyRefused, request_body values: dict[str, str] = {} - for pair in line.get("form") or []: + try: + seen = request_body(line) + except CaptureBodyRefused: + seen = None + for pair in (seen.form if seen is not None else None) or []: if isinstance(pair, (list, tuple)) and len(pair) == 2: values[str(pair[0])] = str(pair[1]) - body = line.get("body") + body = seen.text if seen is not None else None if isinstance(body, str) and body.strip(): try: parsed = json.loads(body) @@ -553,6 +567,56 @@ def _write_values( return values +def _write_unreadable( + line: Mapping[str, Any], *, raw_capture: bool = False +) -> Optional[str]: + """Why the capture kept nothing of this write's body to read, or None. + + None for a raw capture, and for a binary body no raw capture reads + either. + """ + + from openadapt_flow.capture_bodies import ( + CaptureBodyRefused, + request_body, + request_hidden, + ) + + if not request_hidden(line, raw_capture=raw_capture): + return None + try: + request_body(line, what=f"{line.get('method')} request") + except CaptureBodyRefused as exc: + return f"{exc.why}; record with --capture-network-bodies raw" + return None + + +def _write_unseen( + line: Mapping[str, Any], *, raw_capture: bool = False +) -> Optional[str]: + """Why the capture doesn't show everything this write sent, or None: + its body is unreadable (:func:`_write_unreadable`) or fields of it were + withheld.""" + + from openadapt_flow.capture_bodies import ( + RECORD_HINT, + request_body, + request_hidden, + ) + + unreadable = _write_unreadable(line, raw_capture=raw_capture) + if unreadable or not request_hidden(line, raw_capture=raw_capture): + return unreadable + what = f"{line.get('method')} request" + seen = request_body(line, what=what) + if seen.withheld_all: + return ( + f"the capture withheld the {what}'s " + f"{', '.join(seen.withheld_all)}; {RECORD_HINT}" + ) + return None + + def _save_event_times(recording_dir: Path) -> tuple[Optional[float], Optional[float]]: """``(save, previous)``: the last write-shaped step's ``t`` and the ``t`` of the event before it.""" @@ -1080,6 +1144,9 @@ def reads_from_network( network = load_network(recording_dir) if not network: return + from openadapt_flow.network_capture import bodies_mode + + search.raw_capture = bodies_mode(recording_dir) == "raw" lookup, _ = param_lookup(params) first, last, writes = save_window(recording_dir, network) search.save_t = last @@ -1095,6 +1162,19 @@ def reads_from_network( if str(line.get("method") or "").upper() == "GET" and _ok(line) ] after_gets = [line for line in gets if last is None or _t(line) > last] + hidden = [ + line + for line in after_gets + if response_hidden(line, raw_capture=search.raw_capture) + ] + if hidden: + # A record check compares whole records; a minimized response holds + # only declared fields (or, for a page, nothing), so it is not read. + search.notes.append( + f"{len(hidden)} read(s) after the save have responses the capture " + "kept only declared fields of; a record check from the capture " + "reads whole records, so record with --capture-network-bodies raw" + ) candidates: list[tuple[tuple[Any, ...], Surface]] = [] rejected: list[str] = [] seen_urls: set[str] = set() @@ -1150,11 +1230,14 @@ def reads_from_network( for line in writes: sent = set(_write_values(line, excluded_values=params.values()).values()) if not sent & read_back: + # A withheld value may be the one read back, or not: say which + # the capture can't show instead of "no read returns it". tpl = _templated(str(line.get("url") or ""), lookup) - search.uncovered.append( - f"{line.get('method')} {tpl.safe}: no read returns what this " - "request sent" + why = ( + _write_unseen(line, raw_capture=search.raw_capture) + or "no read returns what this request sent" ) + search.uncovered.append(f"{line.get('method')} {tpl.safe}: {why}") # -- database read path -------------------------------------------------------- @@ -1381,6 +1464,11 @@ def _apply_sent_constants(search: ReadSearch, params: Mapping[str, str]) -> None _write_values(line, excluded_values=params.values()) for line in search.write_requests ] + for line in search.write_requests: + why = _write_unseen(line, raw_capture=search.raw_capture) + if why: + # Fewer sent constants to tell the saved record apart: say so. + search.notes.append(f"the check can't match on every sent value: {why}") for surface in search.surfaces: if not surface.is_target: continue diff --git a/packages/flow/openadapt_flow/tx/network_bridge.py b/packages/flow/openadapt_flow/tx/network_bridge.py index 8bc7c0342f..768e04fbb4 100644 --- a/packages/flow/openadapt_flow/tx/network_bridge.py +++ b/packages/flow/openadapt_flow/tx/network_bridge.py @@ -18,8 +18,17 @@ def network_capture_entries_to_har( entries: Sequence[Mapping[str, Any]], + *, + raw_capture: bool = False, ) -> dict[str, Any]: - """Convert ``openadapt.network-capture/1`` exchange dicts into a HAR 1.2 document.""" + """Convert ``openadapt.network-capture/1`` exchange dicts into a HAR 1.2 document. + + A capture that kept only declared fields of a body (the default, + ``--capture-network-bodies minimized``) raises ``ValueError``: lens + induction reads whole bodies, and a body it can't see is not an empty one. + """ + from openadapt_flow.capture_bodies import request_hidden, response_hidden + har_entries: list[dict[str, Any]] = [] for item in entries: if item.get("failed"): @@ -28,6 +37,16 @@ def network_capture_entries_to_har( url = str(item.get("url") or "") if not url: continue + for side, hidden in ( + ("request", request_hidden(item, raw_capture=raw_capture)), + ("response", response_hidden(item, raw_capture=raw_capture)), + ): + if hidden: + raise ValueError( + f"the capture kept only declared fields of the {side} body " + f"of {method} {urlsplit(url).path}; a HAR for lens induction " + "needs whole bodies: record with --capture-network-bodies raw" + ) parsed = urlsplit(url) query_list = [ {"name": k, "value": v} @@ -138,4 +157,6 @@ def load_network_capture_as_har(path: Union[str, Path]) -> dict[str, Any]: ) exchanges = [json.loads(line) for line in lines[1:]] - return network_capture_entries_to_har(exchanges) + # A header without ``bodies`` predates minimization: raw. + raw = str(header.get("bodies") or "raw") == "raw" + return network_capture_entries_to_har(exchanges, raw_capture=raw) diff --git a/packages/flow/openadapt_flow/undo_proposal.py b/packages/flow/openadapt_flow/undo_proposal.py index 1b630df2b2..5ac19569bf 100644 --- a/packages/flow/openadapt_flow/undo_proposal.py +++ b/packages/flow/openadapt_flow/undo_proposal.py @@ -64,6 +64,7 @@ steps_from_demonstration, undo_workflow, ) +from openadapt_flow.capture_bodies import request_hidden, response_hidden from openadapt_flow.ir import ( ActionKind, ApiBinding, @@ -373,24 +374,39 @@ def _selector_values(effect: Effect, params: Mapping[str, Any]) -> dict[str, str return out -def _request_items(line: dict[str, Any]) -> tuple[Optional[str], dict[str, set[str]]]: - """``(kind, items)``: ``json``, ``form`` or None, and the request's - ``key -> values`` (body, form and query).""" +def _request_items( + line: dict[str, Any], +) -> tuple[Optional[str], dict[str, set[str]], frozenset[str]]: + """``(kind, items, withheld)``: ``json``, ``form`` or None; the request's + ``key -> values`` (body, form and query); and the leaf names of the body + fields the capture withheld. + + A minimized capture's body is rebuilt from its kept fields + (:mod:`openadapt_flow.capture_bodies`); one it kept nothing of raises + :class:`~openadapt_flow.capture_bodies.CaptureBodyRefused`. + """ + from openadapt_flow.capture_bodies import json_document, request_body + from openadapt_flow.capture_bodies import withheld_leaves as leaves + items: dict[str, set[str]] = {} for key, value in up.parse_qsl(up.urlsplit(line.get("url", "")).query): items.setdefault(key, set()).add(value) - if "form" in line: - for pair in line["form"]: + seen = request_body(line, what=f"{line.get('method')} request") + withheld = leaves(seen) + if seen.form is not None: + for pair in seen.form: if len(pair) == 2: items.setdefault(str(pair[0]), set()).add(str(pair[1])) - return "form", items - body = line.get("body") - if isinstance(body, str): + return "form", items, withheld + if seen.kind == "json": + # Minimized: the kept fields, rebuilt (none kept is still JSON). + return "json", _flat_items(json_document(seen) or {}, items), withheld + if seen.text is not None: try: - return "json", _flat_items(json.loads(body), items) + return "json", _flat_items(json.loads(seen.text), items), withheld except json.JSONDecodeError: - return None, items - return None, items + return None, items, withheld + return None, items, withheld def _explains(items: dict[str, set[str]], wanted: dict[str, str]) -> bool: @@ -407,36 +423,82 @@ def _explains(items: dict[str, set[str]], wanted: dict[str, str]) -> bool: def _save_request( lines: Sequence[dict[str, Any]], wanted: dict[str, str] -) -> Optional[int]: +) -> tuple[Optional[int], list[tuple[int, str]]]: """Index of the last successful write whose request carries the save's - record selector values.""" + record selector values, and the later writes whose body the capture + withheld (``(index, why)``): any of those could be the save instead, so + the caller refuses rather than pick an earlier request.""" + from openadapt_flow.capture_bodies import ( + RECORD_HINT, + CaptureBodyRefused, + is_withheld_name, + ) + found = None + unseen: list[tuple[int, str]] = [] for index, line in enumerate(lines): if str(line.get("method", "")).upper() not in _WRITE_METHODS: continue status = line.get("status") if not isinstance(status, int) or not 200 <= status < 300: continue - _kind, items = _request_items(line) + try: + _kind, items, withheld = _request_items(line) + except CaptureBodyRefused as exc: + # A binary body a raw capture can't read either carries no + # selector value; one the capture minimized away might. + if request_hidden(line): + unseen.append((index, exc.why)) + continue + hidden = sorted(key for key in wanted if key in withheld) + if hidden: + # A selector field withheld: whether this request names the + # save's record can't be told from the capture. + unseen.append( + ( + index, + f"the capture withheld the {line.get('method')} request's " + f"{', '.join(hidden)}; {RECORD_HINT}", + ) + ) + continue if _explains(items, wanted): found = index - return found + continue + # A form names its fields its own way (``form_lname`` for + # ``lname``), so the match falls back to the values; a withheld value + # (not a session token or secret) may be one of the selector's. + values = sorted(w for w in withheld if not is_withheld_name(w)) + if values and wanted and not any(key in items for key in wanted): + unseen.append( + ( + index, + f"the capture withheld the {line.get('method')} request's " + f"{', '.join(values)}, which may hold the save's record " + f"values; {RECORD_HINT}", + ) + ) + return found, [u for u in unseen if found is None or u[0] > found] def _response_id(line: dict[str, Any], id_field: str) -> Optional[str]: - text = line.get("response_text") - if isinstance(text, str): - try: - body = json.loads(text) - except json.JSONDecodeError: - body = None - if isinstance(body, dict): - for key in (id_field, "id"): - if body.get(key) not in (None, ""): - return str(body[key]) - data = body.get("data") - if isinstance(data, dict) and data.get(id_field) not in (None, ""): - return str(data[id_field]) + from openadapt_flow.capture_bodies import ( + CaptureBodyRefused, + json_document, + response_body, + ) + + try: + body = json_document(response_body(line)) + except CaptureBodyRefused: + body = None + if isinstance(body, dict): + for key in (id_field, "id"): + if body.get(key) not in (None, ""): + return str(body[key]) + data = body.get("data") + if isinstance(data, dict) and data.get(id_field) not in (None, ""): + return str(data[id_field]) location = line.get("location") if isinstance(location, str) and location.rstrip("/"): return location.rstrip("/").rsplit("/", 1)[-1] @@ -494,7 +556,14 @@ def network_candidates( if not lines: return [], "the recording has no network capture (record --capture-network)" wanted = _selector_values(effect, params) - index = _save_request(lines, wanted) + index, unseen = _save_request(lines, wanted) + if unseen: + # Fail closed: a write the capture withheld may be the save. + at, why = unseen[-1] + return [], ( + f"the save's request can't be told from {lines[at].get('method')} " + f"{_path(str(lines[at].get('url', '')))}: {why}" + ) if index is None: return [], ( "no captured request carries the save's record values, so the " @@ -502,7 +571,7 @@ def network_candidates( ) save = lines[index] method = str(save.get("method", "")).upper() - kind, _items = _request_items(save) + kind, _items, _withheld = _request_items(save) path = _path(str(save.get("url", ""))) if "graphql" in path.lower(): return [], ( @@ -518,6 +587,14 @@ def network_candidates( inverse, extra = _inverse_effect(step, effect) if method == "POST" and effect.kind is EffectKind.RECORD_WRITTEN: record_id = _response_id(save, effect.identity_field or "id") + if record_id is None and response_hidden(save): + from openadapt_flow.capture_bodies import RECORD_HINT + + return [], ( + f"the capture withheld the save's response ({method} {path}), " + f"so its record id ({effect.identity_field or 'id'}) can't be " + f"read; {RECORD_HINT}" + ) if record_id is None: return [], ( f"the save's response ({method} {path}) carried no record id, " @@ -747,7 +824,7 @@ def find_candidates( notes.append(note) if sources.network_lines: wanted = _selector_values(effect, params) - at = _save_request(sources.network_lines, wanted) + at, _unseen = _save_request(sources.network_lines, wanted) labels = app_ui_controls(sources.network_lines, at if at is not None else -1) if labels: named = ", ".join(repr(label) for label in labels) diff --git a/packages/flow/tests/test_capture_readers_minimized.py b/packages/flow/tests/test_capture_readers_minimized.py new file mode 100644 index 0000000000..f0377a10f7 --- /dev/null +++ b/packages/flow/tests/test_capture_readers_minimized.py @@ -0,0 +1,617 @@ +"""Readers of a network capture see what a minimized capture kept, or refuse. + +Since captures keep only declared fields (#2480), a save is written as +``body_minimized``/``form_minimized`` with no ``body``/``form``, and a +response as ``response_minimized``. Each reader here either rebuilds what it +needs from the kept fields or refuses, saying a field was withheld or the +body is unreadable; none reads a body it can't see as an empty one (#2789). + +Every capture is made by the real minimizer (``minimize_line``), the way the +recorder writes it. For each reader: a kept field is used, a withheld field +is refused, an opaque (cut) body is refused, and a raw capture still works. +Synthetic values only. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from openadapt_flow.capture_bodies import ( + ALL, + BodyUnreadable, + FieldsWithheld, + request_body, + request_hidden, + response_hidden, +) +from openadapt_flow.capture_privacy import BodyMinimizer, minimize_line + +NOTE = "Synthetic note: cough, 3 days" + + +def _minimized(line: dict[str, Any], keep: list[str]) -> dict[str, Any]: + """``line`` as the default (minimized) capture writes it.""" + return minimize_line(line, BodyMinimizer(keep_fields=keep)) + + +def _save_line(**extra: Any) -> dict[str, Any]: + line: dict[str, Any] = { + "t": 2.1, + "method": "POST", + "url": "http://127.0.0.1:1/api/encounter", + "request_type": "application/json", + "body": json.dumps({"patient_id": "p1", "type": "Triage", "note": NOTE}), + "status": 200, + "response_type": "application/json", + "response_text": json.dumps({"ok": True, "id": 7}), + } + line.update(extra) + return line + + +# -- the shared helper --------------------------------------------------------- + + +def test_helper_rebuilds_kept_json_and_names_what_was_withheld() -> None: + line = _minimized(_save_line(), ["patient_id", "type"]) + seen = request_body(line) + assert seen.kind == "json" and seen.minimized + assert json.loads(seen.text or "") == {"patient_id": "p1", "type": "Triage"} + assert seen.withheld == ("note",) + with pytest.raises(FieldsWithheld, match="note") as exc: + request_body(line, need=ALL, what="save") + assert exc.value.fields == ("note",) + assert "--capture-network-bodies raw" in exc.value.why + # Named fields are full paths, compared case-exact. + assert request_body(line, need=["type"]).kept == ("patient_id", "type") + with pytest.raises(FieldsWithheld, match="Type"): + request_body(line, need=["Type"]) + + +def test_helper_rebuilds_a_minimized_form_as_pairs() -> None: + line = _save_line(request_type="application/x-www-form-urlencoded") + del line["body"] + line["form"] = [["patient_id", "p1"], ["note", NOTE], ["csrf_token", "s" * 12]] + seen = request_body(_minimized(line, ["patient_id", "note"])) + assert seen.kind == "form" and seen.form == [["patient_id", "p1"], ["note", NOTE]] + # A session token is withheld like any field, and kept apart. + assert seen.withheld == () and seen.secrets == ("csrf_token",) + with pytest.raises(FieldsWithheld, match="csrf_token"): + request_body(_minimized(line, ["patient_id", "note"]), need=["csrf_token"]) + + +def test_helper_refuses_an_opaque_body_and_passes_a_raw_one() -> None: + cut = _minimized(_save_line(request_truncated=True), ["patient_id"]) + assert cut["body_minimized"]["format"] == "opaque" + with pytest.raises(BodyUnreadable, match="did not keep the save's body"): + request_body(cut, what="save") + assert request_hidden(cut) + raw = _save_line() + assert request_body(raw, need=ALL).text == raw["body"] + assert not request_hidden(raw) and not response_hidden(raw) + + +def test_a_binary_body_a_raw_capture_also_cannot_read_is_not_hidden() -> None: + # A raw capture writes an opaque descriptor for a binary upload too. + line = { + "method": "POST", + "url": "http://x/upload", + "request_type": "application/octet-stream", + "body_minimized": BodyMinimizer().opaque( + b"\x00\x01", "application/octet-stream" + ), + } + assert not request_hidden(line) + with pytest.raises(BodyUnreadable): + request_body(line) + + +def test_a_minimized_html_response_is_hidden() -> None: + page = _minimized( + { + "method": "GET", + "url": "http://x/chart", + "status": 200, + "response_type": "text/html", + "response_text": "
Saved
", + }, + [], + ) + assert page["response_minimized"]["format"] == "opaque" + assert response_hidden(page) + + +# -- undo_proposal -------------------------------------------------------------- + + +def _undo_step(): + from openadapt_flow.ir import ActionKind, Step + from openadapt_flow.runtime.effects import Effect, EffectKind + + return Step( + id="save_triage", + intent="save triage encounter", + action=ActionKind.KEY, + key="Enter", + risk="irreversible", + effects=[ + Effect( + kind=EffectKind.RECORD_WRITTEN, + match={"patient_id": "p1", "type": "Triage"}, + expected_count=1, + count_new_only=True, + risk="irreversible", + timeout_s=1.0, + ) + ], + ) + + +def _undo(lines: list[dict[str, Any]]): + from openadapt_flow.undo_proposal import network_candidates + + step = _undo_step() + return network_candidates(step, step.effects[0], lines, {}) + + +def test_undo_uses_the_kept_selector_fields_and_the_kept_id() -> None: + line = _minimized(_save_line(), ["patient_id", "type", "id"]) + assert "body" not in line and "response_text" not in line + [candidate], note = _undo([line]) + assert note == "" + assert candidate.undo.steps[0].api_binding.method == "DELETE" + assert "returned a record id" in candidate.basis + + +def test_undo_refuses_when_a_selector_field_was_withheld() -> None: + line = _minimized(_save_line(), ["patient_id", "id"]) + candidates, note = _undo([line]) + assert candidates == [] + assert "withheld the POST request's type" in note + assert "--capture-network-bodies raw" in note + + +def test_undo_refuses_when_a_later_write_was_withheld() -> None: + # The kept save is found, but a later write the capture withheld might + # be the save instead: refuse rather than pick the earlier one. + later = _save_line(t=3.0, url="http://127.0.0.1:1/api/encounter/2") + lines = [ + _minimized(_save_line(), ["patient_id", "type", "id"]), + _minimized(later, ["note"]), + ] + candidates, note = _undo(lines) + assert candidates == [] and "withheld" in note + + +def test_undo_says_the_response_id_was_withheld() -> None: + line = _minimized(_save_line(), ["patient_id", "type"]) + candidates, note = _undo([line]) + assert candidates == [] + assert "withheld the save's response" in note and "--identifier" in note + + +def test_undo_refuses_an_opaque_save_body() -> None: + line = _minimized(_save_line(request_truncated=True), ["patient_id", "type"]) + candidates, note = _undo([line]) + assert candidates == [] + assert "did not keep the POST request's body" in note + + +def test_undo_from_a_raw_capture_is_unchanged() -> None: + [candidate], note = _undo([_save_line()]) + assert note == "" and candidate.undo.steps[0].api_binding.method == "DELETE" + + +# -- record_check_proof.body_template ------------------------------------------ + + +PROOF_PARAMS = {"patient_id": "p1", "note": NOTE} +DEFAULT_BODY = {"default": "body"} + + +def _template(lines: list[dict[str, Any]]) -> dict[str, str]: + from openadapt_flow.record_check_proof import body_template + + return body_template(lines, PROOF_PARAMS, DEFAULT_BODY) + + +def test_proof_template_from_a_fully_kept_save_matches_the_raw_one() -> None: + expected = {"patient_id": "{patient_id}", "type": "Triage", "note": "{note}"} + assert _template([_save_line()]) == expected + kept = _minimized(_save_line(), ["patient_id", "type", "note"]) + assert _template([kept]) == expected + + +def test_proof_template_refuses_a_withheld_field_instead_of_the_default() -> None: + from openadapt_flow.record_check_proof import ProofUnavailable + + line = _minimized(_save_line(), ["patient_id", "note"]) + with pytest.raises( + ProofUnavailable, match="withheld the POST /api/encounter's type" + ): + _template([line]) + # A session token the save sent is withheld too: the proof can't send it. + with_token = _save_line( + body=json.dumps({"patient_id": "p1", "note": NOTE, "csrf_token": "t" * 12}) + ) + with pytest.raises(ProofUnavailable, match="csrf_token"): + _template([_minimized(with_token, ["patient_id", "note"])]) + + +def test_proof_template_refuses_an_opaque_body() -> None: + from openadapt_flow.record_check_proof import ProofUnavailable + + line = _minimized(_save_line(request_truncated=True), ["patient_id"]) + with pytest.raises(ProofUnavailable, match="did not keep"): + _template([line]) + + +def test_proof_template_of_a_form_save_uses_the_default_as_before() -> None: + form = _save_line(request_type="application/x-www-form-urlencoded") + del form["body"] + form["form"] = [["patient_id", "p1"], ["note", NOTE]] + assert _template([form]) == DEFAULT_BODY + assert _template([_minimized(form, ["patient_id"])]) == DEFAULT_BODY + + +# -- record_check_synthesis ------------------------------------------------------ + + +def test_write_values_read_the_kept_fields_and_say_what_is_withheld() -> None: + from openadapt_flow.record_check_synthesis import _write_unseen, _write_values + + raw = _save_line() + assert _write_values(raw) == {"patient_id": "p1", "type": "Triage", "note": NOTE} + assert _write_unseen(raw) is None + kept = _minimized(raw, ["patient_id", "type", "note"]) + assert _write_values(kept) == _write_values(raw) + assert _write_unseen(kept) is None + part = _minimized(raw, ["patient_id", "note"]) + assert _write_values(part) == {"patient_id": "p1", "note": NOTE} + assert "withheld the POST request's type" in (_write_unseen(part) or "") + cut = _minimized(_save_line(request_truncated=True), ["patient_id"]) + assert _write_values(cut) == {} + assert "did not keep the POST request's body" in (_write_unseen(cut) or "") + + +@pytest.fixture +def e2e_service(tmp_path): + from benchmark.effect_e2e.record_service import serve + + handle = serve(tmp_path / "record.db") + yield handle + handle.stop() + + +def _rewrite(rec: Path, change, *, bodies: str = "minimized") -> Path: + """Apply ``change`` to each capture line; the header says ``bodies`` as + the recorder's does.""" + path = rec / "network.jsonl" + header, *lines = [json.loads(x) for x in path.read_text().splitlines()] + header["bodies"] = bodies + path.write_text( + "".join(json.dumps(x) + "\n" for x in [header, *map(change, lines)]) + ) + return rec + + +def _minimize_writes(keep: list[str], **extra: Any): + """Minimize each write's request the real way, leaving the responses + raw, so the reads are found and the write's body is what is tested.""" + + def change(line: dict[str, Any]) -> dict[str, Any]: + if line["method"] == "GET": + return line + out = _minimized({**line, **extra}, keep) + out["response_text"] = line["response_text"] + out.pop("response_minimized", None) + return out + + return change + + +def test_synthesis_matches_on_a_kept_sent_constant(tmp_path, e2e_service) -> None: + from openadapt_flow.record_check_synthesis import synthesize + from tests._record_check_fixtures import effect_e2e_recording + + rec = effect_e2e_recording(tmp_path / "rec", e2e_service.base_url) + raw = synthesize(rec) + assert raw.effects[0].match["type"].literal == "Triage" + _rewrite(rec, _minimize_writes(["patient_id", "type", "note"])) + kept = synthesize(rec) + # The kept constant tells the saved record apart, as in the raw capture. + assert kept.effects[0].match["type"].literal == "Triage" + assert not any("can't match on every sent value" in n for n in kept.search.notes) + + +def test_synthesis_says_a_withheld_sent_value_is_not_matched( + tmp_path, e2e_service +) -> None: + from openadapt_flow.record_check_synthesis import synthesize + from tests._record_check_fixtures import effect_e2e_recording + + rec = effect_e2e_recording(tmp_path / "rec", e2e_service.base_url) + _rewrite(rec, _minimize_writes(["patient_id", "note"])) + proposal = synthesize(rec) + assert "type" not in proposal.effects[0].match + assert any( + "can't match on every sent value" in n and "type" in n + for n in proposal.search.notes + ) + + +def test_synthesis_lists_an_opaque_write_as_uncovered_with_its_reason( + tmp_path, e2e_service +) -> None: + from openadapt_flow.record_check_synthesis import synthesize + from tests._record_check_fixtures import effect_e2e_recording + + rec = effect_e2e_recording(tmp_path / "rec", e2e_service.base_url) + _rewrite(rec, _minimize_writes(["patient_id"], request_truncated=True)) + proposal = synthesize(rec) + assert any( + "did not keep the POST request's body" in u for u in proposal.search.uncovered + ) + assert not any("no read returns" in u for u in proposal.search.uncovered) + + +def test_synthesis_from_a_fully_minimized_capture_says_it_needs_raw( + tmp_path, e2e_service +) -> None: + from openadapt_flow.record_check_synthesis import synthesize + from tests._record_check_fixtures import effect_e2e_recording + + rec = effect_e2e_recording(tmp_path / "rec", e2e_service.base_url) + _rewrite(rec, lambda line: _minimized(line, ["patient_id", "type", "note"])) + proposal = synthesize(rec) + # The reads' records are withheld: no record check is built from them. + assert not any(s.is_target for s in proposal.search.surfaces) + assert any("--capture-network-bodies raw" in n for n in proposal.search.notes) + + +# -- compiler/api_proposal ------------------------------------------------------ + + +def _json_recording(tmp_path: Path, change, *, bodies: str = "minimized") -> Path: + from tests.test_api_step_json import BODY, _recording + + return _rewrite(_recording(tmp_path, BODY), change, bodies=bodies) + + +@pytest.mark.parametrize( + "keep", + [ + # Even every field kept: the API step would send a body rebuilt + # without its key order or empty values, so it is not proposed. + ["firstName", "lastName", "age", "assignedUserId", "teams"], + ["firstName", "lastName", "age"], + ], +) +def test_api_step_is_not_proposed_from_a_minimized_json_save(tmp_path, keep) -> None: + from openadapt_flow.compiler.api_proposal import propose_api_step + from tests.test_api_step_json import _workflow + + rec = _json_recording(tmp_path, lambda line: _minimized(line, keep)) + wf, step, reasons = propose_api_step(_workflow(), rec) + assert step is None + assert "kept only the declared fields of the save's request" in reasons[0] + assert "--capture-network-bodies raw" in reasons[0] + + +def test_api_step_is_not_proposed_from_an_opaque_save(tmp_path) -> None: + from openadapt_flow.compiler.api_proposal import propose_api_step + from tests.test_api_step_json import _workflow + + rec = _json_recording( + tmp_path, + lambda line: _minimized({**line, "request_truncated": True}, ["firstName"]), + ) + _wf, step, reasons = propose_api_step(_workflow(), rec) + assert step is None and "--capture-network-bodies raw" in reasons[0] + + +def test_api_step_is_not_proposed_from_a_minimized_form_save(tmp_path) -> None: + from openadapt_flow.compiler.api_proposal import propose_api_step + from tests.test_api_tier_web_form import _recording, _workflow + + rec = _rewrite( + _recording(tmp_path), + lambda line: _minimized(line, ["form_lname", "form_state", "form_note"]), + ) + _wf, step, reasons = propose_api_step(_workflow(), rec) + assert step is None + assert "POST /app/save.php" in reasons[0] and "form page" in reasons[0] + + +def test_api_step_from_a_raw_json_save_is_still_proposed(tmp_path) -> None: + from openadapt_flow.compiler.api_proposal import propose_api_step + from tests.test_api_step_json import _workflow + + rec = _json_recording(tmp_path, lambda line: line, bodies="raw") + _wf, step, reasons = propose_api_step(_workflow(), rec) + assert step is not None, reasons + + +# -- tx/network_bridge --------------------------------------------------------- + + +def test_network_bridge_refuses_a_minimized_body_and_converts_a_raw_one() -> None: + from openadapt_flow.tx.network_bridge import network_capture_entries_to_har + + har = network_capture_entries_to_har([_save_line()]) + [entry] = har["log"]["entries"] + assert json.loads(entry["request"]["postData"]["text"])["type"] == "Triage" + for keep in (["patient_id", "type", "note", "ok", "id"], ["patient_id"]): + with pytest.raises(ValueError, match="--capture-network-bodies raw"): + network_capture_entries_to_har([_minimized(_save_line(), keep)]) + cut = _minimized(_save_line(request_truncated=True), ["patient_id"]) + with pytest.raises(ValueError, match="request body"): + network_capture_entries_to_har([cut]) + + +# -- raw captures also write opaque bodies: those are not "hidden" ------------- + + +def _raw_opaque_shapes() -> list[dict[str, Any]]: + """Lines a raw capture writes with an opaque descriptor, as + ``network_capture`` does: a multipart body with a file, a binary body + and response over the size cap, and a response type it keeps as bytes.""" + m = BodyMinimizer() + base = {"t": 3.0, "method": "POST", "url": "http://127.0.0.1:1/upload"} + return [ + { + **base, + "request_type": "multipart/form-data", + "body_omitted": "multipart", + "body_minimized": m.opaque(b"--b\r\nfile", "multipart/form-data"), + "status": 200, + }, + { + **base, + "request_type": "application/octet-stream", + "request_truncated": True, + "body_minimized": m.opaque( + b"\x00" * 8, "application/octet-stream", truncated=True + ), + "status": 200, + "response_type": "application/pdf", + "response_truncated": True, + "response_minimized": m.opaque(b"%PDF", "application/pdf", truncated=True), + }, + { + **base, + "method": "GET", + "url": "http://127.0.0.1:1/feed.xml", + "status": 200, + "response_type": "text/xml", + "response_minimized": m.opaque(b"", "text/xml"), + }, + ] + + +@pytest.mark.parametrize("shape", range(3)) +def test_raw_capture_opaque_shapes_are_not_hidden(shape: int) -> None: + from openadapt_flow.record_check_synthesis import _write_unseen + from openadapt_flow.tx.network_bridge import network_capture_entries_to_har + + line = _raw_opaque_shapes()[shape] + assert not request_hidden(line) and not response_hidden(line) + assert _write_unseen(line) is None + network_capture_entries_to_har([line]) # does not raise, as on main + + +@pytest.mark.parametrize("shape", range(3)) +def test_raw_capture_opaque_shapes_leave_undo_and_proof_as_on_main(shape) -> None: + other = _raw_opaque_shapes()[shape] + [candidate], note = _undo([_save_line(), other]) + assert note == "" and candidate.undo.steps[0].api_binding.method == "DELETE" + assert _template([other, _save_line()]) == { + "patient_id": "{patient_id}", + "type": "Triage", + "note": "{note}", + } + + +@pytest.mark.parametrize("shape", range(2)) +def test_raw_capture_opaque_write_is_not_called_minimized_by_api_step( + tmp_path, shape +) -> None: + from openadapt_flow.compiler.api_proposal import propose_api_step + from tests.test_api_step_json import BODY, _recording, _workflow + + rec = _recording(tmp_path, BODY) + path = rec / "network.jsonl" + extra = {**_raw_opaque_shapes()[shape], "t": 7.3} + path.write_text(path.read_text() + json.dumps(extra) + "\n") + _wf, step, reasons = propose_api_step(_workflow(), rec) + # As on main: the extra write refuses the JSON step, for that reason. + assert step is None and "also sent POST /upload" in reasons[0] + + +def test_undo_refuses_a_later_write_whose_withheld_values_may_match() -> None: + # A form names its fields its own way: the match falls back to values, + # and a later form whose value fields were withheld might be the save. + later = { + "t": 3.0, + "method": "POST", + "url": "http://127.0.0.1:1/encounter.php", + "request_type": "application/x-www-form-urlencoded", + "form": [["form_pid", "p1"], ["form_type", "Triage"]], + "status": 200, + } + lines = [ + _minimized(_save_line(), ["patient_id", "type", "id"]), + _minimized(later, ["form_pid"]), + ] + candidates, note = _undo(lines) + assert candidates == [] and "form_type" in note and "record values" in note + + +def test_read_cover_refuses_a_write_it_kept_nothing_of() -> None: + from types import SimpleNamespace + + from openadapt_flow import record_check_synthesis as rcs + from openadapt_flow.read_discovery import cover + + cut = _minimized(_save_line(request_truncated=True), ["patient_id"]) + search = rcs.ReadSearch(write_requests=[cut], read_discovery={}) + # Only the promoted read's config is read before the refusal. + promoted: Any = SimpleNamespace( + config={"records_path": "/api/encounter", "base_url": "http://127.0.0.1:1"} + ) + + def no_probe(url: str) -> Any: + raise AssertionError(f"probed {url}") + + assert ( + cover({"patient_id": "p1"}, search, promoted, captured=[], get=no_probe) is None + ) + assert search.read_discovery is not None + assert "did not keep" in search.read_discovery["covering_read"]["reason"] + + +# -- read discovery: a withheld sent value is not "not sent" --------------------- + + +def _partly_kept_search() -> Any: + from openadapt_flow import record_check_synthesis as rcs + + # The save sent patient_id and type; the capture kept only patient_id. + line = _minimized(_save_line(), ["patient_id"]) + return rcs.ReadSearch(write_requests=[line], read_discovery={}) + + +def _no_probe(url: str) -> Any: + raise AssertionError(f"probed {url}") + + +def test_read_cover_refuses_a_write_whose_sent_fields_were_withheld() -> None: + from types import SimpleNamespace + + from openadapt_flow.read_discovery import cover + + search = _partly_kept_search() + promoted: Any = SimpleNamespace( + config={"records_path": "/api/encounter", "base_url": "http://127.0.0.1:1"} + ) + params = {"patient_id": "p1", "type": "Triage"} + assert cover(params, search, promoted, captured=[], get=_no_probe) is None + assert search.read_discovery is not None + reason = search.read_discovery["covering_read"]["reason"] + assert "withheld the POST request's" in reason and "type" in reason + + +def test_read_discover_refuses_a_write_whose_sent_fields_were_withheld() -> None: + from openadapt_flow.read_discovery import discover + + search = _partly_kept_search() + params = {"patient_id": "p1", "type": "Triage"} + assert discover(params, search, get=_no_probe) is None + assert search.read_discovery is not None + assert search.read_discovery["status"] == "unavailable" + assert "type" in search.read_discovery["reason"] + assert search.read_discovery["probes"] == [] diff --git a/packages/flow/tests/test_read_discovery_cover.py b/packages/flow/tests/test_read_discovery_cover.py index 4b4695b1c6..2fbbd6cf04 100644 --- a/packages/flow/tests/test_read_discovery_cover.py +++ b/packages/flow/tests/test_read_discovery_cover.py @@ -522,6 +522,44 @@ def test_cover_never_probes_a_remote_base(make_app): assert "not the local machine" in search.read_discovery["covering_read"]["reason"] +def test_cover_refuses_when_no_write_sent_a_recorded_value(make_app): + # A raw capture whose write sent none of the recorded values: "the read + # holds every written value" would hold for any read, so nothing covers. + from openadapt_flow import record_check_synthesis as rcs + + app = make_app(root="merged") + sent: list[str] = [] + search = rcs.ReadSearch() + search.read_discovery = {"probes": []} + search.write_requests = [ + { + "method": "POST", + "url": app.url + "/api/transfer", + "request_type": "application/json", + "body": json.dumps({"account": "acct-0001", "memo": "earlier memo"}), + "status": 200, + } + ] + promoted = rcs.Surface( + name="api_transfers", + config={"base_url": app.url, "records_path": "/api/transfers"}, + after=[], + before=[], + before_recorded=False, + source="probe", + ) + assert ( + read_discovery.cover( + PARAMS, search, promoted, captured=[], get=lambda url: sent.append(url) + ) + is None + ) + assert sent == [] + covering = search.read_discovery["covering_read"] + assert covering["status"] == "not found" + assert covering["reason"] == "the write sent no recorded parameter value" + + def test_sibling_paths_come_from_the_apps_own_gets(): origin = "http://127.0.0.1:9" captured = [