From d9cd722be7b1feedf3b121eb1f455e04ee99b4cf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:21:38 -0500 Subject: [PATCH 1/9] feat(flow): keep only declared fields of captured bodies on disk network.jsonl and saved wire-tap HARs now keep declared field values and a per-capture keyed hash of everything else. Raw bodies are an explicit opt-in that is refused unless sealed at rest. --- CAPABILITIES.md | 1 + llms-full.txt | 1 + packages/flow/CHANGELOG.md | 11 + .../benchmark/api_generalization/harness.py | 2 +- .../benchmark/openemr_api_tier/feature_e2e.py | 6 +- packages/flow/benchmark/undo_proposal/run.py | 5 +- .../flow/benchmark/zero_config_verify/run.py | 4 +- packages/flow/docs/API_TIER.md | 12 +- packages/flow/docs/NETWORK_CAPTURE.md | 40 +- packages/flow/openadapt_flow/__main__.py | 31 +- .../flow/openadapt_flow/capture_privacy.py | 362 ++++++++++++++++++ .../openadapt_flow/interactive_recorder.py | 8 +- .../flow/openadapt_flow/network_capture.py | 74 +++- packages/flow/openadapt_flow/tx/wire_tap.py | 52 ++- .../flow/tests/test_api_footprint_browser.py | 2 +- .../flow/tests/test_api_shape_boundaries.py | 6 +- packages/flow/tests/test_api_tier_web_form.py | 2 +- packages/flow/tests/test_capture_privacy.py | 341 +++++++++++++++++ .../tests/test_network_capture_live_django.py | 2 +- .../tests/test_network_capture_redact_json.py | 2 +- 20 files changed, 936 insertions(+), 28 deletions(-) create mode 100644 packages/flow/openadapt_flow/capture_privacy.py create mode 100644 packages/flow/tests/test_capture_privacy.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index cad88c6b1c..9fbb3e3e83 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -257,6 +257,7 @@ improvising or retrying when something is off. | Page structure (DOM, UI Automation, Accessibility) first, then template, OCR and geometry | Released | Real apps on the web; synthetic on Windows and macOS | [RESOLUTION_LADDER.md](packages/flow/docs/RESOLUTION_LADDER.md) | | Run a step as a direct API call (`ApiActuator`, `ApiBinding`) | Released, hand-authored bindings | Synthetic benchmarks | `runtime/actuators/api.py` | | Capture a recording's network traffic and compile a clean save into an API step, with the same record check | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic patients on a local OpenEMR test copy | network capture, `ApiBinding` | +| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash. Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest. Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | | Fall back from the API step to page structure when the API is unavailable, before anything is sent | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic | [#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269) | | Run a form's own script before an API save instead of refusing the form: field handlers, `onsubmit`, submit listeners and custom validate.js rules (OpenEMR's `pastDate`) run on the run's values in a scratch copy of the session with every write blocked, and the save is sent only when the page lets the submit through and would send the same body | On main | Synthetic (headless Chromium against a local test page) | [API_TIER.md](packages/flow/docs/API_TIER.md#what-happens-at-run-time), `runtime/actuators/form_eval.py` | | Compare paired GUI/API database changes with `api admit --footprint`: changed rows retain their identity and before/after values, and unexplained field differences refuse. Variation alone does not establish server ownership. | This PR | Synthetic headless Chromium and SQLite; generated insert ID/time differences conservatively refuse | `openadapt_flow/api_footprint.py` | diff --git a/llms-full.txt b/llms-full.txt index d67812cb9a..512881deda 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -691,6 +691,7 @@ improvising or retrying when something is off. | Page structure (DOM, UI Automation, Accessibility) first, then template, OCR and geometry | Released | Real apps on the web; synthetic on Windows and macOS | [RESOLUTION_LADDER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RESOLUTION_LADDER.md) | | Run a step as a direct API call (`ApiActuator`, `ApiBinding`) | Released, hand-authored bindings | Synthetic benchmarks | `runtime/actuators/api.py` | | Capture a recording's network traffic and compile a clean save into an API step, with the same record check | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic patients on a local OpenEMR test copy | network capture, `ApiBinding` | +| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash. Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest. Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | | Fall back from the API step to page structure when the API is unavailable, before anything is sent | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic | [#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269) | | Run a form's own script before an API save instead of refusing the form: field handlers, `onsubmit`, submit listeners and custom validate.js rules (OpenEMR's `pastDate`) run on the run's values in a scratch copy of the session with every write blocked, and the save is sent only when the page lets the submit through and would send the same body | On main | Synthetic (headless Chromium against a local test page) | [API_TIER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/API_TIER.md#what-happens-at-run-time), `runtime/actuators/form_eval.py` | | Compare paired GUI/API database changes with `api admit --footprint`: changed rows retain their identity and before/after values, and unexplained field differences refuse. Variation alone does not establish server ownership. | This PR | Synthetic headless Chromium and SQLite; generated insert ID/time differences conservatively refuse | `openadapt_flow/api_footprint.py` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 9469c2d499..6579935de3 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -17,6 +17,17 @@ ## Unreleased +### Changes + +- Network captures no longer write raw bodies by default. `record + --capture-network` keeps only the `--param` and `--identifier` values of + each request and response body, plus a per-capture keyed hash of every + other value and of each HTML, text or binary body; undeclared URL query + values are hashed too. `dump_har` and `save_har` do the same with the wire + policy's id and version fields. `--capture-network-bodies raw` (and + `raw_bodies=True`) keeps the redacted bodies, which API step and undo + proposals need, and is refused unless the recording is encrypted. + ### Fixes - `wrap publish` no longer refuses programs whose identity templates carry diff --git a/packages/flow/benchmark/api_generalization/harness.py b/packages/flow/benchmark/api_generalization/harness.py index d9a0e5725d..9a8ff71559 100644 --- a/packages/flow/benchmark/api_generalization/harness.py +++ b/packages/flow/benchmark/api_generalization/harness.py @@ -143,7 +143,7 @@ def cmd_record(a: argparse.Namespace, app: AppBase) -> None: page.goto(app.base + "/") if app.login_required: app.login(page) - capture = NetworkCapture(ctx).start() + capture = NetworkCapture(ctx, bodies="raw").start() app.open_form(page) rec = Recorder( PlaywrightBackend(page), diff --git a/packages/flow/benchmark/openemr_api_tier/feature_e2e.py b/packages/flow/benchmark/openemr_api_tier/feature_e2e.py index 4e8d3eb3de..175522a2e7 100644 --- a/packages/flow/benchmark/openemr_api_tier/feature_e2e.py +++ b/packages/flow/benchmark/openemr_api_tier/feature_e2e.py @@ -76,7 +76,11 @@ def cmd_record(a: argparse.Namespace) -> None: print(json.dumps({"record_gate": wait_quiet()}), flush=True) backend, close = demo._BasePlaywrightBackend.launch(f.ui_base_url, headless=True) try: - capture = None if a.no_capture else NetworkCapture(backend.page.context).start() + capture = ( + None + if a.no_capture + else NetworkCapture(backend.page.context, bodies="raw").start() + ) demo._preauthenticate_browser(backend, f) page = backend.page form = demo._form_frame(page) diff --git a/packages/flow/benchmark/undo_proposal/run.py b/packages/flow/benchmark/undo_proposal/run.py index 7661d80eb3..e38d7e41c7 100644 --- a/packages/flow/benchmark/undo_proposal/run.py +++ b/packages/flow/benchmark/undo_proposal/run.py @@ -113,7 +113,10 @@ def _record_with_capture(fixture: Fixture, url: str, out: Path) -> Path: def launch(*args: Any, **kwargs: Any): backend, close = original(*args, **kwargs) captures.append( - (NetworkCapture(backend.page.context).start(), time.monotonic()) + ( + NetworkCapture(backend.page.context, bodies="raw").start(), + time.monotonic(), + ) ) return backend, close diff --git a/packages/flow/benchmark/zero_config_verify/run.py b/packages/flow/benchmark/zero_config_verify/run.py index 0903554a6b..1b980987d9 100644 --- a/packages/flow/benchmark/zero_config_verify/run.py +++ b/packages/flow/benchmark/zero_config_verify/run.py @@ -91,7 +91,9 @@ def drive( from openadapt_flow.network_capture import NetworkCapture context = browser.new_context(viewport={"width": 1280, "height": 900}) - capture = NetworkCapture(context).start() if recording is not None else None + capture = ( + NetworkCapture(context, bodies="raw").start() if recording is not None else None + ) t0 = time.monotonic() events: list[dict[str, Any]] = [] page = context.new_page() diff --git a/packages/flow/docs/API_TIER.md b/packages/flow/docs/API_TIER.md index 68ca0b0c19..8388087f57 100644 --- a/packages/flow/docs/API_TIER.md +++ b/packages/flow/docs/API_TIER.md @@ -35,16 +35,20 @@ against 15.95 s and two approvals with API steps off (20 runs each, ## How to use it ```bash -openadapt-flow record --backend web --url https://app.example/ --capture-network --out rec/ +openadapt-flow record --backend web --url https://app.example/ --capture-network \ + --capture-network-bodies raw --out rec/ openadapt-flow compile rec/ --out bundle/ --name referral openadapt-flow api show bundle/ openadapt-flow api admit bundle/ --identity subject_name=lname # a person, at a terminal openadapt-flow run bundle/ ... ``` -1. **Record with `--capture-network`.** Flow keeps the page's requests next - to the recorded events in `network.jsonl`. Start the recording before you - open the form, so the page that serves the form is captured. +1. **Record with `--capture-network --capture-network-bodies raw`.** Flow + keeps the page's requests next to the recorded events in `network.jsonl`. + The proposal needs the raw (redacted) bodies; the default keeps only + declared fields ([NETWORK_CAPTURE.md](NETWORK_CAPTURE.md)), and raw needs + an encrypted recording. Start the recording before you open the form, so + the page that serves the form is captured. 2. **Compile.** If the save can be repeated as one request, `compile` proposes an API step on the save step. `api_proposal.json` in the bundle says either which step got the proposal, or why there is none. diff --git a/packages/flow/docs/NETWORK_CAPTURE.md b/packages/flow/docs/NETWORK_CAPTURE.md index dc209efd9f..9dbd91563b 100644 --- a/packages/flow/docs/NETWORK_CAPTURE.md +++ b/packages/flow/docs/NETWORK_CAPTURE.md @@ -22,6 +22,10 @@ order the browser finished them: {"seq": 0, "t": -2.102, "method": "GET", "url": "http://127.0.0.1:9811/", "status": 302, ...} ``` +The header's `bodies` is `"minimized"` (the default) or `"raw"`; a file +without it was written before minimization existed and is raw. +`network_capture.bodies_mode(recording_dir)` reads it. + `meta.json` also records `network_capture: {"file": "network.jsonl", "exchanges": N}`. @@ -52,6 +56,36 @@ order the browser finished them: Static assets (images, fonts, style sheets, scripts, media, manifests) are not captured. +## Bodies: minimized by default + +`record --capture-network-bodies minimized` (the default) parses each body in +memory and writes only what the recording declared +(`openadapt_flow/capture_privacy.py`): + +- **Kept:** the values of the recording's `--param` and `--identifier` + fields, wherever they appear in a JSON, url-encoded or plain multipart + body, or a URL query. +- **Hashed:** every other value, as `hmac-sha256:` under a key made + for this capture and never written. Equal values hash equally within one + file; hashes from different files can't be compared, and a short value + (a birth date) can't be recovered by trying candidates. +- **Opaque:** HTML, plain text, binary, a cut body or a multipart body + with a file keeps only its length, content type and hash. + +So `form`, `body` and `response_text` are replaced by `form_minimized`, +`body_minimized` and `response_minimized`, each `{"kept": [[path, value]], +"withheld": [[path, hash]]}` (bodies also carry `format`, `bytes`, +`content_type` and a whole-body `hmac`), and `url`, `frame_url` and +`location` have undeclared query values hashed. Not minimized: URL path +segments (`/patients/1234`) and JSON keys that look like field names. + +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 +refused unless the recording is encrypted (the default for web recordings; +not with `--no-encrypt`) or `OPENADAPT_FLOW_PLAINTEXT_AT_REST` allows +plaintext. The redaction below applies to raw bodies. + ## Redaction, before anything is written Nothing below reaches the disk. Values are held in memory during the @@ -83,9 +117,9 @@ JSON body, a password-like or token-like field is replaced field by field, whatever the length of its value. Replacement is by exact value (and its URL-encoded form), longest value -first. Business values the person typed (names, dates, addresses) are not -redacted, as in `events.jsonl`. Treat a recording with capture as you treat -any recording: it can contain patient or customer data. +first. In a raw capture, business values the person typed (names, dates, +addresses) are not redacted, as in `events.jsonl`. Treat a recording with +capture as you treat any recording: it can contain patient or customer data. ## Lining up requests and events diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 931f0ee13a..3dfee193ba 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -1547,6 +1547,7 @@ def _cmd_record_capture(args: argparse.Namespace) -> int: stop_when=_record_until_stop(args), surface="web", capture_network=bool(getattr(args, "capture_network", False)), + network_bodies=_network_bodies(args, recording_key), encryption_key=recording_key, ) except BrowserAttachError as exc: @@ -1743,6 +1744,22 @@ def _records_automatically(args: argparse.Namespace) -> bool: return not any(getattr(args, attr, None) for attr in target_flags) +def _network_bodies(args: argparse.Namespace, recording_key: Optional[str]) -> str: + """``--capture-network-bodies``, refused up front when raw can't be sealed.""" + + from openadapt_flow import at_rest + + mode = getattr(args, "capture_network_bodies", None) or "minimized" + if mode == "raw" and recording_key is None: + purpose = "raw network bodies (network.jsonl, bodies=raw)" + if not at_rest.plaintext_allowed(purpose): + raise SystemExit( + "record: --capture-network-bodies raw needs an encrypted " + "recording (drop --no-encrypt). Nothing was recorded." + ) + return mode + + def _cmd_record_surfaces(args: argparse.Namespace) -> int: """``record`` across windows: found automatically, or ``--surface``.""" @@ -9584,11 +9601,23 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help=( "Web only: also keep the page's requests (network.jsonl; cookies, " - "passwords and session tokens withheld). compile then proposes an " + "passwords and session tokens withheld; bodies minimized, see " + "--capture-network-bodies). With raw bodies, compile proposes an " "API step for a save it can repeat as one request; a person admits " "it with 'api admit'" ), ) + p.add_argument( + "--capture-network-bodies", + choices=("minimized", "raw"), + default="minimized", + help=( + "With --capture-network: 'minimized' (default) keeps only the " + "--param and --identifier values of each body and a keyed hash of " + "the rest; 'raw' keeps the redacted bodies, which API step " + "proposals and debugging need, and requires an encrypted recording" + ), + ) p.add_argument( "--with-check", action="store_true", diff --git a/packages/flow/openadapt_flow/capture_privacy.py b/packages/flow/openadapt_flow/capture_privacy.py new file mode 100644 index 0000000000..9c3e050c61 --- /dev/null +++ b/packages/flow/openadapt_flow/capture_privacy.py @@ -0,0 +1,362 @@ +"""Keep only declared fields of captured request and response bodies. + +A network capture (``network.jsonl``) or a saved wire-tap HAR can hold +patient data in its bodies: a search result, a chart page, a JSON record. +Credential redaction (:mod:`openadapt_flow.secret_redaction`, +:func:`openadapt_flow.network_capture.redact`) removes passwords, cookies and +tokens, but leaves every business value in place. This module is the next +step, applied in memory on the device before anything is written: + +* A JSON body, a ``application/x-www-form-urlencoded`` body and a + ``multipart/form-data`` body without files are parsed. The value of a + *declared* field (a recording's parameter and identifier fields, or a wire + policy's id and version fields) is kept. Every other scalar value is + replaced by a keyed hash. +* Anything that does not parse that way (HTML, plain text, binary, a cut + body, a multipart body that carries a file) keeps only its length, its + content type and a keyed hash of the whole body. +* URL query values are treated the same way, because a ``GET`` form puts the + person's input there. Path segments are kept (see "Not covered"). + +The hash is HMAC-SHA256 under a key made for one capture and held only in +memory. It is never written, so a hash of a short value (a birth date, a +name) cannot be reversed by trying every candidate offline. The cost: hashes +from two captures cannot be compared; within one capture, equal values have +equal hashes, so "the value sent was the value read back" stays checkable. + +Not covered: URL path segments (``/patients/1234``) and JSON object keys +that look like ordinary field names are kept as written. A key that does not +look like a field name (spaces, punctuation, over 64 characters) is hashed +like a value. Header values are handled by the credential redaction only. + +Stdlib only, and no ``openadapt_flow`` import at module level, so the wire +tap and the recorder can load it lazily without changing their import cost. +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import re +import secrets +import urllib.parse as up +from typing import Any, Iterable, Mapping, Optional + +#: Marks a body or a whole capture whose bodies were minimized. +MINIMIZED_SCHEMA = "openadapt.capture-minimized/1" +#: The ``bodies`` value of a capture header. +MINIMIZED = "minimized" +RAW = "raw" +BODY_MODES = (MINIMIZED, RAW) + +#: HAR custom field (HAR 1.2 allows names starting with ``_``). +HAR_FIELD = "_openadapt_minimized" + +_FIELD_NAME = re.compile(r"^[A-Za-z_$@][A-Za-z0-9_.$@:\-\[\]]{0,63}$") +_JSON_START = ("{", "[") + + +class BodyMinimizer: + """Minimize the bodies and URLs of one capture. + + ``keep_fields`` are the declared field names. A JSON value is kept when + its leaf key or its dotted path (``data.id``, list indices dropped) + equals a declared name, compared case-insensitively. One instance per + capture: its hash key lives only as long as the instance. + """ + + def __init__(self, keep_fields: Iterable[str] = (), *, key: Optional[bytes] = None): + self._keep = frozenset(str(f).lower() for f in keep_fields if str(f)) + self._key = key if key is not None else secrets.token_bytes(32) + + @property + def keep_fields(self) -> frozenset[str]: + return self._keep + + def tag(self, value: Any) -> str: + """The keyed hash that stands in for ``value``.""" + if isinstance(value, (bytes, bytearray)): + data = bytes(value) + else: + data = json.dumps(value, ensure_ascii=False).encode("utf-8") + digest = hmac.new(self._key, data, hashlib.sha256).hexdigest() + return f"hmac-sha256:{digest}" + + def _declared(self, path: list[str]) -> bool: + if not path or not self._keep: + return False + named = [p for p in path if not p.isdigit()] + if not named: + return False + return named[-1].lower() in self._keep or ".".join(named).lower() in self._keep + + def _segment(self, key: str) -> str: + return key if _FIELD_NAME.match(key) else self.tag(key) + + # -- bodies ---------------------------------------------------------- + + def _walk( + self, + node: Any, + path: list[str], + kept: list[list[Any]], + withheld: list[list[str]], + ) -> None: + if isinstance(node, Mapping): + for k, v in node.items(): + self._walk(v, path + [self._segment(str(k))], kept, withheld) + return + if isinstance(node, list): + for i, v in enumerate(node): + self._walk(v, path + [str(i)], kept, withheld) + return + dotted = ".".join(path) + if self._declared(path) and ( + node is None or isinstance(node, (str, int, float)) + ): + kept.append([dotted, node]) + else: + withheld.append([dotted, self.tag(node)]) + + def pairs(self, pairs: Iterable[Iterable[Any]]) -> dict[str, Any]: + """Minimize ``[name, value]`` pairs (a parsed form body).""" + kept: list[list[Any]] = [] + withheld: list[list[str]] = [] + for pair in pairs: + name, value = (list(pair) + ["", ""])[:2] + segment = self._segment(str(name)) + if self._declared([segment]): + kept.append([segment, value]) + else: + withheld.append([segment, self.tag(value)]) + return {"kept": kept, "withheld": withheld} + + def body( + self, + raw: bytes | str | None, + content_type: str = "", + *, + truncated: bool = False, + ) -> Optional[dict[str, Any]]: + """A minimized description of one body, or None for an empty body.""" + if raw is None: + return None + data = raw.encode("utf-8") if isinstance(raw, str) else bytes(raw) + if not data: + return None + ctype = (content_type or "").split(";")[0].strip().lower() + out: dict[str, Any] = { + "schema": MINIMIZED_SCHEMA, + "bytes": len(data), + "content_type": ctype, + "hmac": self.tag(data), + } + if truncated: + out["format"] = "opaque" + out["truncated"] = True + return out + parsed = self._parse(data, ctype, content_type or "") + if parsed is None: + out["format"] = "opaque" + return out + fmt, result = parsed + out["format"] = fmt + out.update(result) + return out + + def _parse( + self, data: bytes, ctype: str, full_type: str + ) -> Optional[tuple[str, dict[str, Any]]]: + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + return None + if ctype == "application/x-www-form-urlencoded": + return "form", self.pairs(up.parse_qsl(text, keep_blank_values=True)) + if ctype == "multipart/form-data": + from openadapt_flow.network_capture import parse_multipart + + parsed = parse_multipart(data, full_type) + if parsed is None: + return None + fields, _files = parsed + return "form", self.pairs(fields) + if text.lstrip().startswith(_JSON_START): + try: + document = json.loads(text) + except ValueError: + return None + kept: list[list[Any]] = [] + withheld: list[list[str]] = [] + self._walk(document, [], kept, withheld) + return "json", {"kept": kept, "withheld": withheld} + return None + + # -- URLs ------------------------------------------------------------ + + def url(self, url: Any) -> Any: + """``url`` with every undeclared query value replaced by its hash.""" + if not isinstance(url, str) or "?" not in url: + return url + parts = up.urlsplit(url) + if not parts.query: + return url + items = [] + for name, value in up.parse_qsl(parts.query, keep_blank_values=True): + segment = self._segment(name) + keep = self._declared([segment]) + items.append((segment, value if keep or not value else self.tag(value))) + return up.urlunsplit(parts._replace(query=up.urlencode(items))) + + +def restore_kept_json(minimized: Mapping[str, Any]) -> bytes: + """A JSON body holding only the kept fields of a minimized JSON body. + + Lets a replay of a minimized HAR still read declared id and version + fields. Every withheld value is absent, not guessed. Empty for any other + format. + """ + if minimized.get("format") != "json": + return b"" + root: dict[str, Any] = {} + for item in minimized.get("kept") or []: + if not isinstance(item, list) or len(item) != 2: + continue + path, value = str(item[0]), item[1] + names = [p for p in path.split(".") if p and not p.isdigit()] + if not names: + continue + node = root + for name in names[:-1]: + child = node.get(name) + if not isinstance(child, dict): + child = {} + node[name] = child + node = child + node.setdefault(names[-1], value) + return json.dumps(root, sort_keys=True).encode("utf-8") if root else b"" + + +def _har_text(container: Mapping[str, Any]) -> Optional[bytes]: + text = container.get("text") + if not isinstance(text, str) or not text: + return None + if container.get("encoding") == "base64": + try: + return base64.b64decode(text) + except (ValueError, TypeError): + return text.encode("utf-8") + return text.encode("utf-8") + + +def minimize_har(har: Mapping[str, Any], minimizer: BodyMinimizer) -> dict[str, Any]: + """A copy of a HAR 1.2 document with every body minimized. + + Request ``postData.text`` and response ``content.text`` become empty and + the minimized description goes in ``_openadapt_minimized`` beside them. + Request URLs, ``queryString`` values, ``redirectURL`` and ``Location`` + headers are minimized like any other URL. + """ + doc = json.loads(json.dumps(har)) + log = doc.get("log") if isinstance(doc, dict) else None + if not isinstance(log, dict): + return doc + log[HAR_FIELD] = {"schema": MINIMIZED_SCHEMA, "bodies": MINIMIZED} + for entry in log.get("entries") or []: + if not isinstance(entry, dict): + continue + request = entry.get("request") + if isinstance(request, dict): + if isinstance(request.get("url"), str): + request["url"] = minimizer.url(request["url"]) + if isinstance(request.get("queryString"), list): + request["queryString"] = [ + {"name": n, "value": v} + for n, v in up.parse_qsl( + up.urlsplit(request.get("url") or "").query, + keep_blank_values=True, + ) + ] + post = request.get("postData") + if isinstance(post, dict): + _minimize_har_body(post, minimizer, str(post.get("mimeType") or "")) + if isinstance(post.get("params"), list): + post["params"] = [] + response = entry.get("response") + if isinstance(response, dict): + if isinstance(response.get("redirectURL"), str): + response["redirectURL"] = minimizer.url(response["redirectURL"]) + for header in response.get("headers") or []: + if ( + isinstance(header, dict) + and str(header.get("name", "")).lower() == "location" + ): + header["value"] = minimizer.url(header.get("value")) + content = response.get("content") + if isinstance(content, dict): + _minimize_har_body( + content, minimizer, str(content.get("mimeType") or "") + ) + meta = entry.get("_tx") + if isinstance(meta, dict): + # Wire-tap metadata keeps classifications, ids and versions only. + entry["_tx"] = { + k: v + for k, v in meta.items() + if k + in ( + "blocked", + "block_reason", + "is_mutation", + "is_graphql_mutation", + "extracted_entity_id", + "etag", + "version", + ) + } + return doc + + +def _minimize_har_body( + container: dict[str, Any], minimizer: BodyMinimizer, content_type: str +) -> None: + raw = _har_text(container) + container.pop("encoding", None) + container["text"] = "" + container[HAR_FIELD] = minimizer.body(raw, content_type) + + +def is_minimized_har(har: Mapping[str, Any]) -> bool: + log = har.get("log") + return isinstance(log, Mapping) and isinstance(log.get(HAR_FIELD), Mapping) + + +def minimize_line(line: Mapping[str, Any], minimizer: BodyMinimizer) -> dict[str, Any]: + """One ``network.jsonl`` line with its bodies and URLs minimized. + + ``body``, ``form`` and ``response_text`` are removed; ``body_minimized``, + ``form_minimized`` and ``response_minimized`` describe them instead. + Readers that need a body find none and propose nothing from it. + """ + out = dict(line) + for key in ("url", "frame_url", "location"): + if key in out: + out[key] = minimizer.url(out[key]) + request_type = str(out.get("request_type") or "") + if "form" in out: + out["form_minimized"] = minimizer.pairs(out.pop("form") or []) + if "body" in out: + out["body_minimized"] = minimizer.body( + out.pop("body"), + request_type, + truncated=bool(out.get("request_truncated")), + ) + if "response_text" in out: + out["response_minimized"] = minimizer.body( + out.pop("response_text"), + str(out.get("response_type") or ""), + truncated=bool(out.get("response_truncated")), + ) + return out diff --git a/packages/flow/openadapt_flow/interactive_recorder.py b/packages/flow/openadapt_flow/interactive_recorder.py index 417fcffe4c..421900747c 100644 --- a/packages/flow/openadapt_flow/interactive_recorder.py +++ b/packages/flow/openadapt_flow/interactive_recorder.py @@ -2334,6 +2334,7 @@ def __init__( stop_when: Optional[Callable[[], bool]] = None, surface: str = "web", capture_network: bool = False, + network_bodies: str = "minimized", encryption_key: Optional[str] = None, event_clock: Optional[list[float]] = None, ) -> None: @@ -2349,6 +2350,8 @@ def __init__( # ``record --capture-network``: keep the page's requests next to the # events (openadapt_flow.network_capture). Off by default. self._capture_network = capture_network + # Only declared field values leave memory unless "raw" (sealed). + self._network_bodies = network_bodies self._network = None self._out_dir = Path(out_dir) self._secret_fields = set(secret_fields) @@ -2519,7 +2522,10 @@ def start(self) -> None: # Attach before navigating, so the page that serves the form # is in the capture. self._network = NetworkCapture( - self._context, secret_names=self._secret_fields + self._context, + secret_names=self._secret_fields, + keep_fields=self._param_fields | self._identifier_fields, + bodies=self._network_bodies, ).start() if self._owns_browser: self._context.on("page", self._context_page_listener) diff --git a/packages/flow/openadapt_flow/network_capture.py b/packages/flow/openadapt_flow/network_capture.py index f36791ddbe..5257807570 100644 --- a/packages/flow/openadapt_flow/network_capture.py +++ b/packages/flow/openadapt_flow/network_capture.py @@ -26,9 +26,13 @@ whatever their length, then every value found is withheld wherever else it appears. -Patient or other business values the person typed stay in the file, as they -do in ``events.jsonl``. A recording made with capture is as sensitive as any -other recording. +Bodies are minimized before they are written (``bodies="minimized"``, the +default; :mod:`openadapt_flow.capture_privacy`): only the values of the +recording's declared fields (its parameter and identifier fields) are kept; +every other value, every HTML or text page and every URL query value is +replaced by a keyed hash. ``bodies="raw"`` keeps the redacted bodies as +before, for API step proposals and debugging, and is refused unless the +recording is encrypted (or plaintext at rest was explicitly allowed). Static assets (images, fonts, style sheets, scripts, media) are skipped. Request and response bodies are cut at :data:`MAX_REQUEST_BYTES` and @@ -100,9 +104,24 @@ class NetworkCapture: to password-like names (the recorder's declared secret fields). """ - def __init__(self, context: Any, *, secret_names: Iterable[str] = ()) -> None: + def __init__( + self, + context: Any, + *, + secret_names: Iterable[str] = (), + keep_fields: Iterable[str] = (), + bodies: str = "minimized", + ) -> None: + from openadapt_flow.capture_privacy import BODY_MODES + + if bodies not in BODY_MODES: + raise ValueError(f"bodies must be one of {BODY_MODES}, not {bodies!r}") self._context = context self._secret_names = frozenset(secret_names) + # Declared fields whose values survive minimization; ``bodies`` says + # whether anything else of a body reaches disk (only "raw", sealed). + self._keep_fields = frozenset(keep_fields) - self._secret_names + self._bodies = bodies # Cookie values the browser sent or a response set, and Authorization # values, kept in memory only so they can be withheld wherever a page # echoes one. Never written. @@ -309,17 +328,62 @@ def lines(self, t0_monotonic: float) -> list[dict[str, Any]]: ) def write(self, recording_dir: Path | str, t0_monotonic: float) -> Path: + from openadapt_flow import capture_privacy as cp from openadapt_flow import sealed_set path = Path(recording_dir) / NETWORK_FILE lines = self.lines(t0_monotonic) - text = json.dumps({"schema": SCHEMA, "exchanges": len(lines)}) + "\n" + if self._bodies == cp.RAW: + _require_sealed_or_allowed(path) + else: + minimizer = cp.BodyMinimizer(self._keep_fields) + lines = [cp.minimize_line(line, minimizer) for line in lines] + header = {"schema": SCHEMA, "exchanges": len(lines), "bodies": self._bodies} + text = json.dumps(header) + "\n" text += "".join(json.dumps(line, sort_keys=True) + "\n" for line in lines) # Sealed in memory when the recording is encrypted. sealed_set.write_text(path, text) return path +def _require_sealed_or_allowed(path: Path) -> None: + """Refuse raw bodies on disk unless the recording is encrypted. + + TODO(#2423): once the key hierarchy lands, seal raw captures under the + recording's own data key rather than relying on the recording writer. + """ + from openadapt_flow import at_rest, sealed_set + + if sealed_set.is_sealed_path(path): + return + purpose = "raw network bodies (network.jsonl, bodies=raw)" + if at_rest.plaintext_allowed(purpose): + return + raise at_rest.AtRestRefused( + at_rest.refusal(purpose, "the recording is not encrypted") + ) + + +def bodies_mode(recording_dir: Path | str) -> Optional[str]: + """``"minimized"`` or ``"raw"`` for a recording's capture, None if absent. + + A capture written before minimization existed has no ``bodies`` field + and is raw. + """ + + from openadapt_flow import sealed_set + + path = Path(recording_dir) / NETWORK_FILE + if not sealed_set.is_file(path): + return None + first = sealed_set.read_text(path).split("\n", 1)[0] + try: + header = json.loads(first) + except ValueError: + return None + return str(header.get("bodies") or "raw") if isinstance(header, dict) else None + + def parse_multipart( raw: bytes, content_type: str ) -> Optional[tuple[list[list[str]], list[str]]]: diff --git a/packages/flow/openadapt_flow/tx/wire_tap.py b/packages/flow/openadapt_flow/tx/wire_tap.py index aa2a947828..d03baea968 100644 --- a/packages/flow/openadapt_flow/tx/wire_tap.py +++ b/packages/flow/openadapt_flow/tx/wire_tap.py @@ -1082,10 +1082,10 @@ def export_har(self) -> dict[str, Any]: } return _scrub_har_value(har_doc, self._policy.secrets) - def save_har(self, path: str | Path) -> Path: - """Write ``export_har()`` to ``path`` as UTF-8 JSON.""" + def save_har(self, path: str | Path, *, raw_bodies: bool = False) -> Path: + """Write the session to ``path`` as sealed HAR (bodies minimized).""" out_path = Path(path) - dump_har(self, out_path, secrets=self._policy.secrets) + dump_har(self, out_path, secrets=self._policy.secrets, raw_bodies=raw_bodies) return out_path def import_har( @@ -1885,8 +1885,19 @@ def dump_har( path: Optional[str | Path] = None, *, secrets: Iterable[str] = (), + keep_fields: Optional[Iterable[str]] = None, + raw_bodies: bool = False, ) -> str: - """Serialize a ``SessionWireTap`` or HAR dictionary to secret-masked HAR 1.2 JSON.""" + """Serialize a ``SessionWireTap`` or HAR dictionary to secret-masked HAR 1.2 JSON. + + Bodies are minimized by default (:mod:`openadapt_flow.capture_privacy`): + only ``keep_fields`` values survive (default: the policy's id and version + fields), the rest become keyed hashes. ``raw_bodies=True`` keeps them for + debugging; a file is always sealed under the at-rest key + (``write_private_record``). TODO(#2423): use the key hierarchy's data key. + """ + from openadapt_flow import capture_privacy as cp + raw_har: Mapping[str, Any] = ( har_or_tap.export_har() if isinstance(har_or_tap, SessionWireTap) @@ -1894,6 +1905,18 @@ def dump_har( ) secret_tuple = tuple(s for s in secrets if s) scrubbed = _scrub_har_value(dict(raw_har), secret_tuple) + if not raw_bodies and not cp.is_minimized_har(scrubbed): + policy = ( + har_or_tap.policy + if isinstance(har_or_tap, SessionWireTap) + else WirePolicy() + ) + fields = ( + (*policy.id_fields, *policy.version_fields) + if keep_fields is None + else tuple(keep_fields) + ) + scrubbed = cp.minimize_har(scrubbed, cp.BodyMinimizer(fields)) payload = json.dumps(scrubbed, indent=2, sort_keys=False) if path is not None: out = Path(path) @@ -1952,10 +1975,31 @@ def parse_bytes(raw: bytes) -> Any: "entries": list(entries), } } + from openadapt_flow.capture_privacy import HAR_FIELD, is_minimized_har + + if is_minimized_har(data): + # Kept declared fields come back as JSON text; withheld values do not. + normalized["log"][HAR_FIELD] = log[HAR_FIELD] + normalized["log"]["entries"] = [ + _restore_minimized_entry(e) if isinstance(e, Mapping) else e + for e in entries + ] secret_tuple = tuple(s for s in secrets if s) return _scrub_har_value(normalized, secret_tuple) +def _restore_minimized_entry(entry: Mapping[str, Any]) -> dict[str, Any]: + """A minimized entry with each body replaced by its kept JSON fields.""" + from openadapt_flow.capture_privacy import HAR_FIELD, restore_kept_json + + out = json.loads(json.dumps(entry)) + for side, key in (("request", "postData"), ("response", "content")): + container = (out.get(side) or {}).get(key) + if isinstance(container, dict) and isinstance(container.get(HAR_FIELD), dict): + container["text"] = restore_kept_json(container[HAR_FIELD]).decode("utf-8") + return out + + def har_to_summary( source: str | Path | bytes | Mapping[str, Any], *, diff --git a/packages/flow/tests/test_api_footprint_browser.py b/packages/flow/tests/test_api_footprint_browser.py index 3d738e73e9..8a9171ef5c 100644 --- a/packages/flow/tests/test_api_footprint_browser.py +++ b/packages/flow/tests/test_api_footprint_browser.py @@ -188,7 +188,7 @@ def gui_save(page, title): def capture_save(app, context, page, tmp_path): rec = tmp_path / "capture" rec.mkdir() - capture = nc.NetworkCapture(context).start() + capture = nc.NetworkCapture(context, bodies="raw").start() try: open_editor(app, page) start = time.monotonic() diff --git a/packages/flow/tests/test_api_shape_boundaries.py b/packages/flow/tests/test_api_shape_boundaries.py index 4f185bc28d..9aa84e8c88 100644 --- a/packages/flow/tests/test_api_shape_boundaries.py +++ b/packages/flow/tests/test_api_shape_boundaries.py @@ -203,7 +203,7 @@ def binding_from_browser(tmp_path: Path, site: Site, page: Any): json.dumps({"params": {"title": "Note Alpha"}}) ) clock = time.monotonic() - capture = NetworkCapture(page.context).start() + capture = NetworkCapture(page.context, bodies="raw").start() try: page.goto(site.base + "/compose") # Finish capturing the form before recording its first input event. @@ -349,7 +349,9 @@ def test_declared_multipart_secret_is_scrubbed_before_persistence( site.html = FORM.replace( 'method="post"', 'method="post" enctype="multipart/form-data"' ).replace(" list[bytes]: + raw = value.encode("utf-8") + return [ + raw, + quote(value, safe="").encode(), + quote_plus(value).encode(), + json.dumps(value)[1:-1].encode(), + json.dumps(value, ensure_ascii=True)[1:-1].encode(), + base64.b64encode(raw), + base64.urlsafe_b64encode(raw).rstrip(b"="), + ] + + +def _plain(data: bytes) -> bytes: + """``data`` decrypted (Flow's at-rest format) and gunzipped when it is.""" + if crypto.is_encrypted(data): + for aad in (b"openadapt-flow/tx-private-state",): + try: + data = crypto.decrypt_bytes( + data, crypto.resolve_read_key(None), aad=aad + ) + break + except Exception: # noqa: BLE001 - try the next context + continue + if data[:2] == b"\x1f\x8b": + data = gzip.decompress(data) + return data + + +def _leaks(root: Path) -> list[tuple[str, str]]: + found = [] + for path in sorted(p for p in root.rglob("*") if p.is_file()): + data = _plain(path.read_bytes()) + for value in PHI: + for form in _forms(value): + if form in data: + found.append((str(path.relative_to(root)), value)) + return found + + +# -- network.jsonl ------------------------------------------------------------ + + +class _Response: + def __init__(self, status: int, content_type: str, body: bytes) -> None: + self.status = status + self.headers = {"content-type": content_type} + self._body = body + + def body(self) -> bytes: + return self._body + + def headers_array(self) -> list[dict[str, str]]: + return [{"name": "Content-Type", "value": self.headers["content-type"]}] + + +class _Request: + def __init__(self, url, method, body, content_type, response) -> None: + self.url, self.method, self.resource_type = url, method, "fetch" + self.post_data_buffer = body + self.headers = {"content-type": content_type} if content_type else {} + self.frame = type("F", (), {"url": url})() + self._response = response + + def all_headers(self) -> dict[str, str]: + return dict(self.headers) + + def response(self) -> _Response: + return self._response + + +class _Context: + def __init__(self) -> None: + self.handlers: dict[str, Any] = {} + + def on(self, event, handler) -> None: + self.handlers[event] = handler + + def remove_listener(self, event, handler) -> None: + self.handlers.pop(event, None) + + +def _record(tmp_path: Path, **kwargs: Any) -> Path: + ctx = _Context() + cap = nc.NetworkCapture(ctx, keep_fields=("note", "patient_id"), **kwargs) + cap.start() + finished = ctx.handlers["requestfinished"] + # A search: the name is in the query, the chart page holds every value. + finished( + _Request( + f"http://app.test/patients?q={quote_plus(PATIENT)}", + "GET", + None, + None, + _Response( + 200, + "text/html", + ( + f"" + f"
{PATIENT}{DOB}{MRN}{DIAGNOSIS}
" + ).encode(), + ), + ) + ) + # A JSON save: one declared field typed, the response echoes the chart. + finished( + _Request( + "http://app.test/api/notes", + "POST", + json.dumps({"patient_id": "4417", "note": "follow up"}).encode(), + "application/json", + _Response( + 201, + "application/json", + json.dumps( + { + "id": 91, + "patient_id": "4417", + "note": "follow up", + "patient": {"name": PATIENT, "dob": DOB, "mrn": MRN}, + "problems": [{"text": DIAGNOSIS}], + } + ).encode(), + ), + ) + ) + # A form post that carries an undeclared value. + finished( + _Request( + "http://app.test/intake", + "POST", + f"note=ok&diagnosis={quote_plus(DIAGNOSIS)}".encode(), + "application/x-www-form-urlencoded", + _Response(302, "text/html", b""), + ) + ) + cap.stop() + cap.write(tmp_path, t0_monotonic=0.0) + return tmp_path / nc.NETWORK_FILE + + +def test_default_network_capture_writes_no_phi(tmp_path: Path) -> None: + path = _record(tmp_path) + assert _leaks(tmp_path) == [] + rows = [json.loads(line) for line in path.read_text().splitlines()] + assert rows[0]["bodies"] == "minimized" + assert nc.bodies_mode(tmp_path) == "minimized" + for row in rows[1:]: + assert "body" not in row and "response_text" not in row + assert "form" not in row + + +def test_declared_fields_survive_and_the_rest_is_hashed(tmp_path: Path) -> None: + _record(tmp_path) + rows = nc.load(tmp_path) + save = rows[1] + assert ["patient_id", "4417"] in save["body_minimized"]["kept"] + assert ["note", "follow up"] in save["response_minimized"]["kept"] + withheld = dict(save["response_minimized"]["withheld"]) + assert withheld["patient.name"].startswith("hmac-sha256:") + assert "id" in withheld # not declared here, so not kept + page = rows[0]["response_minimized"] + assert page["format"] == "opaque" and page["bytes"] > 0 + form = rows[2]["form_minimized"] + assert ["note", "ok"] in form["kept"] + assert [name for name, _ in form["withheld"]] == ["diagnosis"] + + +def test_raw_bodies_need_encryption_or_an_explicit_plaintext_opt_out( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv(at_rest.OPT_OUT_ENV, raising=False) + with pytest.raises(at_rest.AtRestRefused): + _record(tmp_path, bodies="raw") + assert not (tmp_path / nc.NETWORK_FILE).exists() + + +def test_raw_bodies_opt_in_keeps_them_for_debugging( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # Positive control: the scanner does see PHI when it is written. + monkeypatch.setenv(at_rest.OPT_OUT_ENV, "test: synthetic data") + _record(tmp_path, bodies="raw") + assert nc.bodies_mode(tmp_path) == "raw" + assert {value for _, value in _leaks(tmp_path)} == set(PHI) + + +def test_raw_bodies_in_an_encrypted_recording_are_ciphertext( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from openadapt_flow import sealed_set + + monkeypatch.delenv(at_rest.OPT_OUT_ENV, raising=False) + root = tmp_path / "rec" + with sealed_set.writing(root, "recording", "synthetic-passphrase-for-tests"): + _record(root, bodies="raw") + on_disk = b"".join(p.read_bytes() for p in root.rglob("*") if p.is_file()) + for value in PHI: + for form in _forms(value): + assert form not in on_disk + reader = sealed_set.open_set(root, "synthetic-passphrase-for-tests") + assert PATIENT in reader.read_bytes(nc.NETWORK_FILE).decode() + + +def test_bad_body_mode_is_refused() -> None: + with pytest.raises(ValueError): + nc.NetworkCapture(_Context(), bodies="everything") + + +# -- wire-tap HAR --------------------------------------------------------------- + + +def _tap() -> SessionWireTap: + tap = SessionWireTap("http://app.test") + tap.record_exchange( + method="POST", + url=f"http://app.test/api/records?lookup={quote_plus(MRN)}", + request_body=json.dumps({"name": PATIENT, "dob": DOB}).encode(), + response_status=201, + response_body=json.dumps( + {"id": "51", "version": "3", "chart": {"dx": DIAGNOSIS, "mrn": MRN}} + ).encode(), + request_headers={"Content-Type": "application/json"}, + response_headers={"Content-Type": "application/json"}, + duration_ms=1.0, + ) + tap.record_exchange( + method="GET", + url="http://app.test/chart/51", + request_body=b"", + response_status=200, + response_body=f"

{PATIENT}

{DIAGNOSIS}

".encode(), + request_headers={}, + response_headers={"Content-Type": "text/html"}, + duration_ms=1.0, + ) + return tap + + +def test_saved_har_holds_no_phi_even_after_decryption(tmp_path: Path) -> None: + tap = _tap() + path = tap.save_har(tmp_path / "session.har") + assert crypto.is_encrypted(path.read_bytes()) + assert _leaks(tmp_path) == [] + text = dump_har(tap) + for value in PHI: + for form in _forms(value): + assert form.decode("latin-1") not in text + + +def test_minimized_har_replays_declared_ids_and_fails_closed(tmp_path: Path) -> None: + path = _tap().save_har(tmp_path / "session.har") + har = load_har(path) + assert cp.is_minimized_har(har) + restored = SessionWireTap.from_har(path) + summary = restored.summary() + assert summary.mutations_allowed == 1 + assert summary.mutations[0].extracted_entity_id == "51" + assert summary.mutations[0].version == "3" + + +def test_raw_har_opt_in_is_sealed_on_disk(tmp_path: Path) -> None: + path = _tap().save_har(tmp_path / "raw.har", raw_bodies=True) + on_disk = path.read_bytes() + for value in PHI: + for form in _forms(value): + assert form not in on_disk + # Positive control: decrypted, the raw bodies are there. + assert {value for _, value in _leaks(tmp_path)} == set(PHI) + + +# -- minimizer ------------------------------------------------------------------- + + +def test_hash_key_is_per_capture_and_never_written() -> None: + a, b = cp.BodyMinimizer(), cp.BodyMinimizer() + assert a.tag(DOB) == a.tag(DOB) + assert a.tag(DOB) != b.tag(DOB) + out = a.body(json.dumps({"dob": DOB}).encode(), "application/json") + assert out is not None and DOB not in json.dumps(out) + + +def test_keys_that_are_not_field_names_are_hashed() -> None: + m = cp.BodyMinimizer(("status",)) + out = m.body(json.dumps({PATIENT: {"status": "seen"}}).encode(), "application/json") + assert out is not None + assert PATIENT not in json.dumps(out) + assert out["kept"][0][1] == "seen" + + +def test_unparsed_and_truncated_bodies_keep_only_size_and_hash() -> None: + m = cp.BodyMinimizer(("note",)) + out = m.body( + json.dumps({"note": PATIENT}).encode(), "application/json", truncated=True + ) + assert out is not None and out["format"] == "opaque" and "kept" not in out + binary = m.body(b"\xff\xfe" + PATIENT.encode(), "application/octet-stream") + assert binary is not None and binary["format"] == "opaque" + assert m.body(b"", "text/html") is None + + +def test_url_query_values_are_hashed_unless_declared() -> None: + m = cp.BodyMinimizer(("page",)) + url = m.url(f"http://app.test/s?q={quote_plus(PATIENT)}&page=2") + assert quote_plus(PATIENT) not in url and PATIENT not in url + assert "page=2" in url diff --git a/packages/flow/tests/test_network_capture_live_django.py b/packages/flow/tests/test_network_capture_live_django.py index cdc0af307c..f696ed3f5d 100644 --- a/packages/flow/tests/test_network_capture_live_django.py +++ b/packages/flow/tests/test_network_capture_live_django.py @@ -134,7 +134,7 @@ def test_a_django_admin_recording_keeps_no_rendered_token(django_admin, tmp_path pytest.skip(f"chromium unavailable: {exc}") try: context = browser.new_context() - capture = nc.NetworkCapture(context).start() + capture = nc.NetworkCapture(context, bodies="raw").start() t0 = time.monotonic() page = context.new_page() page.goto(f"{base}/admin/login/?next=/admin/auth/group/add/") diff --git a/packages/flow/tests/test_network_capture_redact_json.py b/packages/flow/tests/test_network_capture_redact_json.py index 2befc026d1..974ef22a2c 100644 --- a/packages/flow/tests/test_network_capture_redact_json.py +++ b/packages/flow/tests/test_network_capture_redact_json.py @@ -69,7 +69,7 @@ def remove_listener(self, event, handler): def _capture(tmp_path): ctx = _Context() - cap = nc.NetworkCapture(ctx).start() + cap = nc.NetworkCapture(ctx, bodies="raw").start() finished = ctx.handlers["requestfinished"] login = json.dumps( {"user": {"login": "amy.synthetic", "password": PASSWORD, "pin": "1234"}} From 1217bb5d6b428304ed24d42555f85038d99df72e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:18:40 -0500 Subject: [PATCH 2/9] fix(flow): keep the minimizer stdlib-only and inside the wire-tap import boundary --- .../flow/openadapt_flow/capture_privacy.py | 63 +++++++++++++++++-- .../flow/openadapt_flow/network_capture.py | 59 +---------------- packages/flow/openadapt_flow/tx/wire_tap.py | 10 ++- packages/flow/tests/test_tx_har_redaction.py | 4 +- packages/flow/tests/test_tx_wire_tap.py | 8 +++ 5 files changed, 79 insertions(+), 65 deletions(-) diff --git a/packages/flow/openadapt_flow/capture_privacy.py b/packages/flow/openadapt_flow/capture_privacy.py index 9c3e050c61..b9abb4a8de 100644 --- a/packages/flow/openadapt_flow/capture_privacy.py +++ b/packages/flow/openadapt_flow/capture_privacy.py @@ -29,8 +29,8 @@ look like a field name (spaces, punctuation, over 64 characters) is hashed like a value. Header values are handled by the credential redaction only. -Stdlib only, and no ``openadapt_flow`` import at module level, so the wire -tap and the recorder can load it lazily without changing their import cost. +Stdlib only (no ``openadapt_flow`` import), so the wire tap and the +recorder load it without changing their import cost. """ from __future__ import annotations @@ -176,8 +176,6 @@ def _parse( if ctype == "application/x-www-form-urlencoded": return "form", self.pairs(up.parse_qsl(text, keep_blank_values=True)) if ctype == "multipart/form-data": - from openadapt_flow.network_capture import parse_multipart - parsed = parse_multipart(data, full_type) if parsed is None: return None @@ -360,3 +358,60 @@ def minimize_line(line: Mapping[str, Any], minimizer: BodyMinimizer) -> dict[str truncated=bool(out.get("response_truncated")), ) return out + + +def parse_multipart( + raw: bytes, content_type: str +) -> Optional[tuple[list[list[str]], list[str]]]: + """The fields of a ``multipart/form-data`` body that carries no file. + + Returns ``([[name, value], ...], [file field names])`` in the order sent: + a file input left empty is a part with ``filename=""`` and no content, + kept as ``[name, ""]`` and named in the second list. ``None`` when a part + carries a file, a part has a header other than its disposition and an + ``application/octet-stream`` type for an empty file, a value isn't UTF-8, + or the body doesn't parse: those bodies aren't kept. + """ + + m = re.search(r'boundary=(?:"([^"]+)"|([^;\s]+))', content_type, re.I) + if not m: + return None + delimiter = b"--" + (m.group(1) or m.group(2)).encode("latin-1") + chunks = raw.split(delimiter) + if len(chunks) < 2 or chunks[0].strip() or not chunks[-1].startswith(b"--"): + return None + pairs: list[list[str]] = [] + files: list[str] = [] + for chunk in chunks[1:-1]: + if not chunk.startswith(b"\r\n") or not chunk.endswith(b"\r\n"): + return None + head, sep, value = chunk[2:-2].partition(b"\r\n\r\n") + if not sep: + return None + try: + head_lines = head.decode("utf-8").split("\r\n") + text = value.decode("utf-8") + except UnicodeDecodeError: + return None + disposition = head_lines[0] + extra = [h.lower() for h in head_lines[1:]] + name = re.fullmatch( + r'(?i)content-disposition: form-data; name="([^"]*)"(; filename="([^"]*)")?', + disposition, + ) + if name is None: + return None + if name.group(2) is None: + if extra: + return None + pairs.append([name.group(1), text]) + continue + if ( + name.group(3) + or text + or extra not in ([], ["content-type: application/octet-stream"]) + ): + return None # a file was attached + pairs.append([name.group(1), ""]) + files.append(name.group(1)) + return pairs, files diff --git a/packages/flow/openadapt_flow/network_capture.py b/packages/flow/openadapt_flow/network_capture.py index 5257807570..6c33af33b5 100644 --- a/packages/flow/openadapt_flow/network_capture.py +++ b/packages/flow/openadapt_flow/network_capture.py @@ -51,6 +51,8 @@ from pathlib import Path from typing import Any, Iterable, Optional +from openadapt_flow.capture_privacy import parse_multipart # noqa: F401 - public here + NETWORK_FILE = "network.jsonl" SCHEMA = "openadapt.network-capture/1" @@ -384,63 +386,6 @@ def bodies_mode(recording_dir: Path | str) -> Optional[str]: return str(header.get("bodies") or "raw") if isinstance(header, dict) else None -def parse_multipart( - raw: bytes, content_type: str -) -> Optional[tuple[list[list[str]], list[str]]]: - """The fields of a ``multipart/form-data`` body that carries no file. - - Returns ``([[name, value], ...], [file field names])`` in the order sent: - a file input left empty is a part with ``filename=""`` and no content, - kept as ``[name, ""]`` and named in the second list. ``None`` when a part - carries a file, a part has a header other than its disposition and an - ``application/octet-stream`` type for an empty file, a value isn't UTF-8, - or the body doesn't parse: those bodies aren't kept. - """ - - m = re.search(r'boundary=(?:"([^"]+)"|([^;\s]+))', content_type, re.I) - if not m: - return None - delimiter = b"--" + (m.group(1) or m.group(2)).encode("latin-1") - chunks = raw.split(delimiter) - if len(chunks) < 2 or chunks[0].strip() or not chunks[-1].startswith(b"--"): - return None - pairs: list[list[str]] = [] - files: list[str] = [] - for chunk in chunks[1:-1]: - if not chunk.startswith(b"\r\n") or not chunk.endswith(b"\r\n"): - return None - head, sep, value = chunk[2:-2].partition(b"\r\n\r\n") - if not sep: - return None - try: - head_lines = head.decode("utf-8").split("\r\n") - text = value.decode("utf-8") - except UnicodeDecodeError: - return None - disposition = head_lines[0] - extra = [h.lower() for h in head_lines[1:]] - name = re.fullmatch( - r'(?i)content-disposition: form-data; name="([^"]*)"(; filename="([^"]*)")?', - disposition, - ) - if name is None: - return None - if name.group(2) is None: - if extra: - return None - pairs.append([name.group(1), text]) - continue - if ( - name.group(3) - or text - or extra not in ([], ["content-type: application/octet-stream"]) - ): - return None # a file was attached - pairs.append([name.group(1), ""]) - files.append(name.group(1)) - return pairs, files - - def _frame_url(request: Any) -> Optional[str]: try: return request.frame.url diff --git a/packages/flow/openadapt_flow/tx/wire_tap.py b/packages/flow/openadapt_flow/tx/wire_tap.py index d03baea968..0167ca1fe5 100644 --- a/packages/flow/openadapt_flow/tx/wire_tap.py +++ b/packages/flow/openadapt_flow/tx/wire_tap.py @@ -1896,7 +1896,11 @@ def dump_har( debugging; a file is always sealed under the at-rest key (``write_private_record``). TODO(#2423): use the key hierarchy's data key. """ - from openadapt_flow import capture_privacy as cp + from openadapt_flow.capture_privacy import ( + BodyMinimizer, + is_minimized_har, + minimize_har, + ) raw_har: Mapping[str, Any] = ( har_or_tap.export_har() @@ -1905,7 +1909,7 @@ def dump_har( ) secret_tuple = tuple(s for s in secrets if s) scrubbed = _scrub_har_value(dict(raw_har), secret_tuple) - if not raw_bodies and not cp.is_minimized_har(scrubbed): + if not raw_bodies and not is_minimized_har(scrubbed): policy = ( har_or_tap.policy if isinstance(har_or_tap, SessionWireTap) @@ -1916,7 +1920,7 @@ def dump_har( if keep_fields is None else tuple(keep_fields) ) - scrubbed = cp.minimize_har(scrubbed, cp.BodyMinimizer(fields)) + scrubbed = minimize_har(scrubbed, BodyMinimizer(fields)) payload = json.dumps(scrubbed, indent=2, sort_keys=False) if path is not None: out = Path(path) diff --git a/packages/flow/tests/test_tx_har_redaction.py b/packages/flow/tests/test_tx_har_redaction.py index 22e66e3388..8ab154f117 100644 --- a/packages/flow/tests/test_tx_har_redaction.py +++ b/packages/flow/tests/test_tx_har_redaction.py @@ -195,10 +195,12 @@ def log_message(self, *_args): assert response.read() == payload conn.close() exported = tap.export_har() - path = tap.save_har(tmp_path / "session.har") + path = tap.save_har(tmp_path / "session.har", raw_bodies=True) assert crypto.is_encrypted(path.read_bytes()) restored = load_har(path) assert restored == exported + minimized = load_har(tap.save_har(tmp_path / "minimized.har")) + assert not carries_secret(json.dumps(minimized), (secret,)) assert path.stat().st_mode & 0o077 == 0 serialized = json.dumps(restored) assert not carries_secret(serialized, (secret,)) diff --git a/packages/flow/tests/test_tx_wire_tap.py b/packages/flow/tests/test_tx_wire_tap.py index 65ef3f5c32..7faaa3e8d7 100644 --- a/packages/flow/tests/test_tx_wire_tap.py +++ b/packages/flow/tests/test_tx_wire_tap.py @@ -1265,6 +1265,7 @@ def test_wire_tap_generality_and_import_boundaries(tmp_path: Path) -> None: "openadapt_flow.tx.types", "openadapt_flow.tx.receipt", # encrypted private-state writer, already import-light checked "openadapt_flow.wire_check", + "openadapt_flow.capture_privacy", # body minimizer, stdlib only (below) } stdlib_names = sys.stdlib_module_names @@ -1294,6 +1295,13 @@ def permitted_from_import(node): ): assert not permitted_from_import(ast.parse(unknown).body[0]) + minimizer_source = WIRE_TAP_PATH.parent.parent / "capture_privacy.py" + for node in ast.walk(ast.parse(minimizer_source.read_text())): + if isinstance(node, ast.Import): + assert all(alias.name.split(".")[0] in stdlib_names for alias in node.names) + elif isinstance(node, ast.ImportFrom): + assert node.module.split(".")[0] in stdlib_names + redaction_source = WIRE_TAP_PATH.parent.parent / "secret_redaction.py" for node in ast.walk(ast.parse(redaction_source.read_text())): if isinstance(node, ast.Import): From b44d8ad947ee980605dcc5a118c4cb8dfa434854 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:59:38 -0500 Subject: [PATCH 3/9] refactor(flow): keep record CLI plumbing in network_capture under the line budgets --- packages/flow/openadapt_flow/__main__.py | 45 ++---------- .../openadapt_flow/interactive_recorder.py | 18 ++--- .../flow/openadapt_flow/network_capture.py | 71 ++++++++++++++++++- packages/flow/tests/test_capture_privacy.py | 23 ++++++ 4 files changed, 102 insertions(+), 55 deletions(-) diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 3dfee193ba..a66b39fc8d 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -1533,6 +1533,7 @@ def _cmd_record_capture(args: argparse.Namespace) -> int: BrowserAttachError, record_interactive, ) + from openadapt_flow.network_capture import cli_mode try: out = record_interactive( @@ -1546,8 +1547,7 @@ def _cmd_record_capture(args: argparse.Namespace) -> int: browser_page_url=getattr(args, "browser_page_url", None), stop_when=_record_until_stop(args), surface="web", - capture_network=bool(getattr(args, "capture_network", False)), - network_bodies=_network_bodies(args, recording_key), + capture_network=cli_mode(args, recording_key), encryption_key=recording_key, ) except BrowserAttachError as exc: @@ -1744,22 +1744,6 @@ def _records_automatically(args: argparse.Namespace) -> bool: return not any(getattr(args, attr, None) for attr in target_flags) -def _network_bodies(args: argparse.Namespace, recording_key: Optional[str]) -> str: - """``--capture-network-bodies``, refused up front when raw can't be sealed.""" - - from openadapt_flow import at_rest - - mode = getattr(args, "capture_network_bodies", None) or "minimized" - if mode == "raw" and recording_key is None: - purpose = "raw network bodies (network.jsonl, bodies=raw)" - if not at_rest.plaintext_allowed(purpose): - raise SystemExit( - "record: --capture-network-bodies raw needs an encrypted " - "recording (drop --no-encrypt). Nothing was recorded." - ) - return mode - - def _cmd_record_surfaces(args: argparse.Namespace) -> int: """``record`` across windows: found automatically, or ``--surface``.""" @@ -9596,28 +9580,9 @@ def build_parser() -> argparse.ArgumentParser: "refused under OPENADAPT_FLOW_AT_REST=strict" ), ) - p.add_argument( - "--capture-network", - action="store_true", - help=( - "Web only: also keep the page's requests (network.jsonl; cookies, " - "passwords and session tokens withheld; bodies minimized, see " - "--capture-network-bodies). With raw bodies, compile proposes an " - "API step for a save it can repeat as one request; a person admits " - "it with 'api admit'" - ), - ) - p.add_argument( - "--capture-network-bodies", - choices=("minimized", "raw"), - default="minimized", - help=( - "With --capture-network: 'minimized' (default) keeps only the " - "--param and --identifier values of each body and a keyed hash of " - "the rest; 'raw' keeps the redacted bodies, which API step " - "proposals and debugging need, and requires an encrypted recording" - ), - ) + from openadapt_flow.network_capture import add_cli_arguments as _network_args + + _network_args(p) p.add_argument( "--with-check", action="store_true", diff --git a/packages/flow/openadapt_flow/interactive_recorder.py b/packages/flow/openadapt_flow/interactive_recorder.py index 421900747c..facbbc9eee 100644 --- a/packages/flow/openadapt_flow/interactive_recorder.py +++ b/packages/flow/openadapt_flow/interactive_recorder.py @@ -2333,8 +2333,7 @@ def __init__( ] = None, stop_when: Optional[Callable[[], bool]] = None, surface: str = "web", - capture_network: bool = False, - network_bodies: str = "minimized", + capture_network: bool | str = False, encryption_key: Optional[str] = None, event_clock: Optional[list[float]] = None, ) -> None: @@ -2348,10 +2347,8 @@ def __init__( # finalized sealed set. self._encryption_key = encryption_key # ``record --capture-network``: keep the page's requests next to the - # events (openadapt_flow.network_capture). Off by default. + # events (openadapt_flow.network_capture); "raw" keeps whole bodies. self._capture_network = capture_network - # Only declared field values leave memory unless "raw" (sealed). - self._network_bodies = network_bodies self._network = None self._out_dir = Path(out_dir) self._secret_fields = set(secret_fields) @@ -2519,13 +2516,10 @@ def start(self) -> None: if self._capture_network: from openadapt_flow.network_capture import NetworkCapture - # Attach before navigating, so the page that serves the form - # is in the capture. - self._network = NetworkCapture( - self._context, - secret_names=self._secret_fields, - keep_fields=self._param_fields | self._identifier_fields, - bodies=self._network_bodies, + # Attach before navigating, so the form's page is captured. + declared = self._param_fields | self._identifier_fields + self._network = NetworkCapture.for_recording( + self._context, self._secret_fields, declared, self._capture_network ).start() if self._owns_browser: self._context.on("page", self._context_page_listener) diff --git a/packages/flow/openadapt_flow/network_capture.py b/packages/flow/openadapt_flow/network_capture.py index 6c33af33b5..2908bbbc7d 100644 --- a/packages/flow/openadapt_flow/network_capture.py +++ b/packages/flow/openadapt_flow/network_capture.py @@ -137,6 +137,23 @@ def __init__( # guard sends or refuses it. self._pending_writes: dict[Any, float] = {} + @classmethod + def for_recording( + cls, + context: Any, + secret_names: Iterable[str], + declared_fields: Iterable[str], + mode: bool | str, + ) -> "NetworkCapture": + """The recorder's capture: ``mode`` True means minimized bodies.""" + bodies = mode if isinstance(mode, str) else "minimized" + return cls( + context, + secret_names=secret_names, + keep_fields=declared_fields, + bodies=bodies, + ) + def start(self) -> "NetworkCapture": if not self._attached: self._context.on("request", self._on_request) @@ -358,14 +375,62 @@ def _require_sealed_or_allowed(path: Path) -> None: if sealed_set.is_sealed_path(path): return - purpose = "raw network bodies (network.jsonl, bodies=raw)" - if at_rest.plaintext_allowed(purpose): + if at_rest.plaintext_allowed(_RAW_PURPOSE): return raise at_rest.AtRestRefused( - at_rest.refusal(purpose, "the recording is not encrypted") + at_rest.refusal(_RAW_PURPOSE, "the recording is not encrypted") + ) + + +_RAW_PURPOSE = "raw network bodies (network.jsonl, bodies=raw)" + + +def add_cli_arguments(parser: Any) -> None: + """``record --capture-network`` and ``--capture-network-bodies``.""" + parser.add_argument( + "--capture-network", + action="store_true", + help=( + "Web only: also keep the page's requests (network.jsonl; cookies, " + "passwords and session tokens withheld; bodies minimized, see " + "--capture-network-bodies). With raw bodies, compile proposes an " + "API step for a save it can repeat as one request; a person admits " + "it with 'api admit'" + ), + ) + parser.add_argument( + "--capture-network-bodies", + choices=("minimized", "raw"), + default="minimized", + help=( + "With --capture-network: 'minimized' (default) keeps only the " + "--param and --identifier values of each body and a keyed hash of " + "the rest; 'raw' keeps the redacted bodies, which API step " + "proposals and debugging need, and requires an encrypted recording" + ), ) +def cli_mode(args: Any, recording_key: Optional[str]) -> bool | str: + """False without ``--capture-network``, else the body mode. + + Raw is refused before anything is recorded when the recording won't be + encrypted and plaintext at rest isn't explicitly allowed. + """ + from openadapt_flow import at_rest + + if not getattr(args, "capture_network", False): + return False + mode = getattr(args, "capture_network_bodies", None) or "minimized" + if mode == "raw" and recording_key is None: + if not at_rest.plaintext_allowed(_RAW_PURPOSE): + raise SystemExit( + "record: --capture-network-bodies raw needs an encrypted " + "recording (drop --no-encrypt). Nothing was recorded." + ) + return str(mode) + + def bodies_mode(recording_dir: Path | str) -> Optional[str]: """``"minimized"`` or ``"raw"`` for a recording's capture, None if absent. diff --git a/packages/flow/tests/test_capture_privacy.py b/packages/flow/tests/test_capture_privacy.py index 1a3291a6e0..db18c720da 100644 --- a/packages/flow/tests/test_capture_privacy.py +++ b/packages/flow/tests/test_capture_privacy.py @@ -237,6 +237,29 @@ def test_raw_bodies_in_an_encrypted_recording_are_ciphertext( assert PATIENT in reader.read_bytes(nc.NETWORK_FILE).decode() +def test_record_cli_refuses_raw_bodies_before_recording_without_a_key( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import argparse + + parser = argparse.ArgumentParser() + nc.add_cli_arguments(parser) + monkeypatch.delenv(at_rest.OPT_OUT_ENV, raising=False) + assert nc.cli_mode(parser.parse_args([]), None) is False + on = parser.parse_args(["--capture-network"]) + assert nc.cli_mode(on, None) == "minimized" + raw = parser.parse_args(["--capture-network", "--capture-network-bodies", "raw"]) + assert nc.cli_mode(raw, "recording-passphrase") == "raw" + with pytest.raises(SystemExit, match="encrypted"): + nc.cli_mode(raw, None) + + +def test_recorder_capture_keeps_its_declared_fields() -> None: + cap = nc.NetworkCapture.for_recording(_Context(), {"pw"}, {"mrn_param"}, True) + assert cap._bodies == "minimized" and "mrn_param" in cap._keep_fields + assert nc.NetworkCapture.for_recording(_Context(), (), (), "raw")._bodies == "raw" + + def test_bad_body_mode_is_refused() -> None: with pytest.raises(ValueError): nc.NetworkCapture(_Context(), bodies="everything") From facb4ec31d03c3939701797476a0589cfacaea89 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:09:46 -0500 Subject: [PATCH 4/9] fix(flow): close the capture-minimization gaps found in cross-vendor review - Replay keeps a minimized HAR entry's recorded write as a floor, and treats a withheld write body or hashed GraphQL query as a write. - dump_har minimizes every entry, re-checks earlier kept values against the current fields, and hashes wire-tap ids and versions that were not kept; page titles are minimized like URLs. - Truncated forms are opaque; JSON is parsed only from JSON-labelled or unlabelled bodies; params-only HAR forms are minimized. - Declared secrets are withheld whatever their case; fragment queries and bare search terms are hashed; lone surrogates hash instead of failing. - Kept JSON is restored with its list structure and dotted-suffix fields (meta.versionId); colliding paths restore nothing. - Raw network.jsonl writes check and write in one sealed lookup; raw dump_har needs a path; benchmarks check raw readiness before driving. - The privacy scanner fails on undecryptable files, decodes HAR bodies, and has a distinct positive control per encoding. --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/CHANGELOG.md | 3 +- .../benchmark/api_generalization/harness.py | 4 +- .../benchmark/openemr_api_tier/feature_e2e.py | 5 +- packages/flow/benchmark/undo_proposal/run.py | 4 +- .../flow/benchmark/zero_config_verify/run.py | 5 +- packages/flow/docs/API_TIER.md | 4 +- packages/flow/docs/NETWORK_CAPTURE.md | 18 +- .../flow/openadapt_flow/capture_privacy.py | 348 +++++++++++++----- .../flow/openadapt_flow/network_capture.py | 59 ++- packages/flow/openadapt_flow/sealed_set.py | 16 +- packages/flow/openadapt_flow/tx/wire_tap.py | 29 +- packages/flow/tests/test_capture_privacy.py | 252 ++++++++++++- 14 files changed, 609 insertions(+), 142 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 9fbb3e3e83..0414c06877 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -257,7 +257,7 @@ improvising or retrying when something is off. | Page structure (DOM, UI Automation, Accessibility) first, then template, OCR and geometry | Released | Real apps on the web; synthetic on Windows and macOS | [RESOLUTION_LADDER.md](packages/flow/docs/RESOLUTION_LADDER.md) | | Run a step as a direct API call (`ApiActuator`, `ApiBinding`) | Released, hand-authored bindings | Synthetic benchmarks | `runtime/actuators/api.py` | | Capture a recording's network traffic and compile a clean save into an API step, with the same record check | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic patients on a local OpenEMR test copy | network capture, `ApiBinding` | -| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash. Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest. Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | +| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash (a body labelled JSON, or unlabelled `application/octet-stream`, is parsed as JSON). Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest or plaintext is explicitly allowed (`OPENADAPT_FLOW_PLAINTEXT_AT_REST`, warned and logged). Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | | Fall back from the API step to page structure when the API is unavailable, before anything is sent | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic | [#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269) | | Run a form's own script before an API save instead of refusing the form: field handlers, `onsubmit`, submit listeners and custom validate.js rules (OpenEMR's `pastDate`) run on the run's values in a scratch copy of the session with every write blocked, and the save is sent only when the page lets the submit through and would send the same body | On main | Synthetic (headless Chromium against a local test page) | [API_TIER.md](packages/flow/docs/API_TIER.md#what-happens-at-run-time), `runtime/actuators/form_eval.py` | | Compare paired GUI/API database changes with `api admit --footprint`: changed rows retain their identity and before/after values, and unexplained field differences refuse. Variation alone does not establish server ownership. | This PR | Synthetic headless Chromium and SQLite; generated insert ID/time differences conservatively refuse | `openadapt_flow/api_footprint.py` | diff --git a/llms-full.txt b/llms-full.txt index 512881deda..7572454e26 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -691,7 +691,7 @@ improvising or retrying when something is off. | Page structure (DOM, UI Automation, Accessibility) first, then template, OCR and geometry | Released | Real apps on the web; synthetic on Windows and macOS | [RESOLUTION_LADDER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RESOLUTION_LADDER.md) | | Run a step as a direct API call (`ApiActuator`, `ApiBinding`) | Released, hand-authored bindings | Synthetic benchmarks | `runtime/actuators/api.py` | | Capture a recording's network traffic and compile a clean save into an API step, with the same record check | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic patients on a local OpenEMR test copy | network capture, `ApiBinding` | -| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash. Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest. Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | +| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash (a body labelled JSON, or unlabelled `application/octet-stream`, is parsed as JSON). Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest or plaintext is explicitly allowed (`OPENADAPT_FLOW_PLAINTEXT_AT_REST`, warned and logged). Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | | Fall back from the API step to page structure when the API is unavailable, before anything is sent | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic | [#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269) | | Run a form's own script before an API save instead of refusing the form: field handlers, `onsubmit`, submit listeners and custom validate.js rules (OpenEMR's `pastDate`) run on the run's values in a scratch copy of the session with every write blocked, and the save is sent only when the page lets the submit through and would send the same body | On main | Synthetic (headless Chromium against a local test page) | [API_TIER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/API_TIER.md#what-happens-at-run-time), `runtime/actuators/form_eval.py` | | Compare paired GUI/API database changes with `api admit --footprint`: changed rows retain their identity and before/after values, and unexplained field differences refuse. Variation alone does not establish server ownership. | This PR | Synthetic headless Chromium and SQLite; generated insert ID/time differences conservatively refuse | `openadapt_flow/api_footprint.py` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 6579935de3..6b5d903d10 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -26,7 +26,8 @@ values are hashed too. `dump_har` and `save_har` do the same with the wire policy's id and version fields. `--capture-network-bodies raw` (and `raw_bodies=True`) keeps the redacted bodies, which API step and undo - proposals need, and is refused unless the recording is encrypted. + proposals need, and is refused unless the recording is encrypted or + `OPENADAPT_FLOW_PLAINTEXT_AT_REST` explicitly allows plaintext. ### Fixes diff --git a/packages/flow/benchmark/api_generalization/harness.py b/packages/flow/benchmark/api_generalization/harness.py index 9a8ff71559..08d61036a4 100644 --- a/packages/flow/benchmark/api_generalization/harness.py +++ b/packages/flow/benchmark/api_generalization/harness.py @@ -120,12 +120,14 @@ def cmd_record(a: argparse.Namespace, app: AppBase) -> None: from playwright.sync_api import sync_playwright from openadapt_flow.backends.playwright_backend import PlaywrightBackend - from openadapt_flow.network_capture import NetworkCapture + from openadapt_flow.network_capture import NetworkCapture, require_raw_ready from openadapt_flow.recorder import Recorder out = Path(a.out) if out.exists(): raise SystemExit(f"exists: {out}") + # Raw bodies (synthetic data) need OPENADAPT_FLOW_PLAINTEXT_AT_REST here. + require_raw_ready(out) start_proxy(app) values = app.recording_values() if a.tag: diff --git a/packages/flow/benchmark/openemr_api_tier/feature_e2e.py b/packages/flow/benchmark/openemr_api_tier/feature_e2e.py index 175522a2e7..46e7368a2a 100644 --- a/packages/flow/benchmark/openemr_api_tier/feature_e2e.py +++ b/packages/flow/benchmark/openemr_api_tier/feature_e2e.py @@ -64,13 +64,16 @@ def cmd_record(a: argparse.Namespace) -> None: from benchmark.harness.openemr_local import SyntheticPatientSpec - from openadapt_flow.network_capture import NetworkCapture + from openadapt_flow.network_capture import NetworkCapture, require_raw_ready from openadapt_flow.recorder import Recorder demo = load_demo() out = Path(a.out) if out.exists(): raise SystemExit(f"exists: {out}") + if not a.no_capture: + # Raw bodies (synthetic data) need OPENADAPT_FLOW_PLAINTEXT_AT_REST. + require_raw_ready(out) f = SpikeFixture() reset_and_seed(f) print(json.dumps({"record_gate": wait_quiet()}), flush=True) diff --git a/packages/flow/benchmark/undo_proposal/run.py b/packages/flow/benchmark/undo_proposal/run.py index e38d7e41c7..536bc8c4c4 100644 --- a/packages/flow/benchmark/undo_proposal/run.py +++ b/packages/flow/benchmark/undo_proposal/run.py @@ -105,8 +105,10 @@ def _fixtures() -> dict[str, Fixture]: def _record_with_capture(fixture: Fixture, url: str, out: Path) -> Path: """The demo driver's recording, with the browser's traffic captured.""" from openadapt_flow import demo_driver - from openadapt_flow.network_capture import NetworkCapture + from openadapt_flow.network_capture import NetworkCapture, require_raw_ready + # Raw bodies (synthetic data) need OPENADAPT_FLOW_PLAINTEXT_AT_REST here. + require_raw_ready(out) original = demo_driver.PlaywrightBackend.launch captures: list[tuple[NetworkCapture, float]] = [] diff --git a/packages/flow/benchmark/zero_config_verify/run.py b/packages/flow/benchmark/zero_config_verify/run.py index 1b980987d9..5ed1112aa8 100644 --- a/packages/flow/benchmark/zero_config_verify/run.py +++ b/packages/flow/benchmark/zero_config_verify/run.py @@ -88,8 +88,11 @@ def drive( """Run the task's selector solution. With ``recording``, write the recording the recorder would: events, params and the network capture.""" - from openadapt_flow.network_capture import NetworkCapture + from openadapt_flow.network_capture import NetworkCapture, require_raw_ready + if recording is not None: + # Raw bodies (synthetic data) need OPENADAPT_FLOW_PLAINTEXT_AT_REST. + require_raw_ready(recording) context = browser.new_context(viewport={"width": 1280, "height": 900}) capture = ( NetworkCapture(context, bodies="raw").start() if recording is not None else None diff --git a/packages/flow/docs/API_TIER.md b/packages/flow/docs/API_TIER.md index 8388087f57..670310a685 100644 --- a/packages/flow/docs/API_TIER.md +++ b/packages/flow/docs/API_TIER.md @@ -35,7 +35,9 @@ against 15.95 s and two approvals with API steps off (20 runs each, ## How to use it ```bash -openadapt-flow record --backend web --url https://app.example/ --capture-network \ +# Raw bodies need an encrypted recording: a recording key, or strict mode. +OPENADAPT_FLOW_AT_REST=strict openadapt-flow record --backend web \ + --url https://app.example/ --capture-network \ --capture-network-bodies raw --out rec/ openadapt-flow compile rec/ --out bundle/ --name referral openadapt-flow api show bundle/ diff --git a/packages/flow/docs/NETWORK_CAPTURE.md b/packages/flow/docs/NETWORK_CAPTURE.md index 9dbd91563b..80f39f2d42 100644 --- a/packages/flow/docs/NETWORK_CAPTURE.md +++ b/packages/flow/docs/NETWORK_CAPTURE.md @@ -69,22 +69,28 @@ memory and writes only what the recording declared for this capture and never written. Equal values hash equally within one file; hashes from different files can't be compared, and a short value (a birth date) can't be recovered by trying candidates. -- **Opaque:** HTML, plain text, binary, a cut body or a multipart body - with a file keeps only its length, content type and hash. +- **Opaque:** HTML, plain text, binary, a cut body or form, or a + multipart body with a file keeps only its length, content type and hash. + JSON is parsed only from a body labelled JSON or unlabelled + (`application/octet-stream`); JSON-looking text of any other type is + opaque. So `form`, `body` and `response_text` are replaced by `form_minimized`, `body_minimized` and `response_minimized`, each `{"kept": [[path, value]], "withheld": [[path, hash]]}` (bodies also carry `format`, `bytes`, `content_type` and a whole-body `hmac`), and `url`, `frame_url` and -`location` have undeclared query values hashed. Not minimized: URL path +`location` have undeclared query values hashed (also a query in the +fragment, `#/search?q=...`, and a bare search term, `?term`). Not minimized: URL path segments (`/patients/1234`) and JSON keys that look like field names. 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 -refused unless the recording is encrypted (the default for web recordings; -not with `--no-encrypt`) or `OPENADAPT_FLOW_PLAINTEXT_AT_REST` allows -plaintext. The redaction below applies to raw bodies. +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 +plaintext, which is warned about and logged. Code that builds +`NetworkCapture(bodies="raw")` itself calls `require_raw_ready()` first. The redaction below applies to raw bodies. ## Redaction, before anything is written diff --git a/packages/flow/openadapt_flow/capture_privacy.py b/packages/flow/openadapt_flow/capture_privacy.py index b9abb4a8de..9e9e136cef 100644 --- a/packages/flow/openadapt_flow/capture_privacy.py +++ b/packages/flow/openadapt_flow/capture_privacy.py @@ -14,7 +14,10 @@ replaced by a keyed hash. * Anything that does not parse that way (HTML, plain text, binary, a cut body, a multipart body that carries a file) keeps only its length, its - content type and a keyed hash of the whole body. + content type and a keyed hash of the whole body. JSON is parsed only from + a body labelled JSON or unlabelled (``application/octet-stream``, the wire + tap's type for a missing header); JSON-looking text in any other type is + opaque. * URL query values are treated the same way, because a ``GET`` form puts the person's input there. Path segments are kept (see "Not covered"). @@ -56,19 +59,35 @@ _FIELD_NAME = re.compile(r"^[A-Za-z_$@][A-Za-z0-9_.$@:\-\[\]]{0,63}$") _JSON_START = ("{", "[") +#: A value this module already replaced (left as is when minimized again). +TAG = re.compile(r"hmac-sha256:[0-9a-f]{64}") +_READ_METHODS = frozenset({"GET", "HEAD", "OPTIONS"}) class BodyMinimizer: """Minimize the bodies and URLs of one capture. ``keep_fields`` are the declared field names. A JSON value is kept when - its leaf key or its dotted path (``data.id``, list indices dropped) - equals a declared name, compared case-insensitively. One instance per - capture: its hash key lives only as long as the instance. + its leaf key or a dotted suffix of its path (``id``, ``meta.versionId``, + ``data.id``; list indices dropped) equals a declared name, compared + case-insensitively. ``withhold`` names are never kept, whatever their + case (a declared secret). One instance per capture: its hash key lives + only as long as the instance. """ - def __init__(self, keep_fields: Iterable[str] = (), *, key: Optional[bytes] = None): - self._keep = frozenset(str(f).lower() for f in keep_fields if str(f)) + def __init__( + self, + keep_fields: Iterable[str] = (), + *, + key: Optional[bytes] = None, + withhold: Iterable[str] = (), + ): + withheld = {str(f).lower() for f in withhold} + self._keep = frozenset( + str(f).lower() + for f in keep_fields + if str(f) and str(f).lower() not in withheld + ) self._key = key if key is not None else secrets.token_bytes(32) @property @@ -80,7 +99,10 @@ def tag(self, value: Any) -> str: if isinstance(value, (bytes, bytearray)): data = bytes(value) else: - data = json.dumps(value, ensure_ascii=False).encode("utf-8") + # surrogatepass: a lone escaped surrogate parses but isn't UTF-8. + data = json.dumps(value, ensure_ascii=False).encode( + "utf-8", "surrogatepass" + ) digest = hmac.new(self._key, data, hashlib.sha256).hexdigest() return f"hmac-sha256:{digest}" @@ -90,7 +112,12 @@ def _declared(self, path: list[str]) -> bool: named = [p for p in path if not p.isdigit()] if not named: return False - return named[-1].lower() in self._keep or ".".join(named).lower() in self._keep + lowered = [p.lower() for p in named] + return any(".".join(lowered[i:]) in self._keep for i in range(len(lowered))) + + def declared(self, name: str) -> bool: + """Whether a top-level field ``name`` is kept.""" + return self._declared([self._segment(str(name))]) def _segment(self, key: str) -> str: return key if _FIELD_NAME.match(key) else self.tag(key) @@ -181,7 +208,12 @@ def _parse( return None fields, _files = parsed return "form", self.pairs(fields) - if text.lstrip().startswith(_JSON_START): + # JSON only when labelled JSON or unlabelled: octet-stream is the wire + # tap's type for a missing header. HTML and text stay opaque. + json_type = ctype in ("", "application/octet-stream") or ctype.endswith( + ("/json", "+json") + ) + if json_type and text.lstrip().startswith(_JSON_START): try: document = json.loads(text) except ValueError: @@ -195,18 +227,60 @@ def _parse( # -- URLs ------------------------------------------------------------ def url(self, url: Any) -> Any: - """``url`` with every undeclared query value replaced by its hash.""" - if not isinstance(url, str) or "?" not in url: + """``url`` with every undeclared query value replaced by its hash. + + Also a query inside the fragment (``#/search?q=...``, ``#q=...``) and + a bare search term (``?term``, which has no name to declare). + """ + if not isinstance(url, str) or ("?" not in url and "#" not in url): return url parts = up.urlsplit(url) - if not parts.query: - return url + fragment = parts.fragment + if "?" in fragment: + head, _, tail = fragment.partition("?") + fragment = head + "?" + self.query(tail) + elif "=" in fragment: + fragment = self.query(fragment) + return up.urlunsplit( + parts._replace(query=self.query(parts.query), fragment=fragment) + ) + + def query(self, query: str) -> str: + """A query string with undeclared values (and bare terms) hashed.""" items = [] - for name, value in up.parse_qsl(parts.query, keep_blank_values=True): + for component in query.split("&"): + if not component: + continue + name, sep, value = component.partition("=") + name = up.unquote_plus(name) + if not sep: + items.append( + up.quote_plus(name if TAG.fullmatch(name) else self.tag(name)) + ) + continue + value = up.unquote_plus(value) segment = self._segment(name) - keep = self._declared([segment]) - items.append((segment, value if keep or not value else self.tag(value))) - return up.urlunsplit(parts._replace(query=up.urlencode(items))) + keep = not value or TAG.fullmatch(value) or self._declared([segment]) + items.append(up.urlencode([(segment, value if keep else self.tag(value))])) + return "&".join(items) + + def refilter(self, minimized: Mapping[str, Any]) -> dict[str, Any]: + """An already minimized body under this policy: a kept value that + this policy doesn't declare is withheld (hashed).""" + out = dict(minimized) + if isinstance(out.get("kept"), list): + kept: list[Any] = [] + withheld = list(out.get("withheld") or []) + for item in out["kept"]: + if not isinstance(item, list) or len(item) != 2: + continue + path = [p for p in str(item[0]).split(".") if p] + if self._declared(path): + kept.append(item) + else: + withheld.append([str(item[0]), self.tag(item[1])]) + out["kept"], out["withheld"] = kept, withheld + return out def restore_kept_json(minimized: Mapping[str, Any]) -> bytes: @@ -218,25 +292,46 @@ def restore_kept_json(minimized: Mapping[str, Any]) -> bytes: """ if minimized.get("format") != "json": return b"" - root: dict[str, Any] = {} + holder: dict[str, Any] = {} for item in minimized.get("kept") or []: if not isinstance(item, list) or len(item) != 2: continue - path, value = str(item[0]), item[1] - names = [p for p in path.split(".") if p and not p.isdigit()] - if not names: - continue - node = root - for name in names[:-1]: - child = node.get(name) - if not isinstance(child, dict): - child = {} - node[name] = child - node = child - node.setdefault(names[-1], value) + segments = [p for p in str(item[0]).split(".") if p] + if segments and not _place(holder, [""] + segments, item[1]): + return b"" # paths that collide: restore nothing rather than guess + root = holder.get("") return json.dumps(root, sort_keys=True).encode("utf-8") if root else b"" +def _place(node: Any, segments: list[str], value: Any) -> bool: + """Set ``value`` at ``segments`` (digits index lists); False on a clash.""" + for i, seg in enumerate(segments): + last = i == len(segments) - 1 + if isinstance(node, list): + if not seg.isdigit() or int(seg) > 10_000: + return False + index: Any = int(seg) + while len(node) <= index: + node.append(None) + elif isinstance(node, dict): + index = seg + else: + return False + current = node[index] if isinstance(node, list) else node.get(index) + if last: + if current is not None: + return False + node[index] = value + return True + if current is None: + current = [] if segments[i + 1].isdigit() else {} + node[index] = current + if isinstance(current, list) != segments[i + 1].isdigit(): + return False + node = current + return False + + def _har_text(container: Mapping[str, Any]) -> Optional[bytes]: text = container.get("text") if not isinstance(text, str) or not text: @@ -252,78 +347,148 @@ def _har_text(container: Mapping[str, Any]) -> Optional[bytes]: def minimize_har(har: Mapping[str, Any], minimizer: BodyMinimizer) -> dict[str, Any]: """A copy of a HAR 1.2 document with every body minimized. - Request ``postData.text`` and response ``content.text`` become empty and - the minimized description goes in ``_openadapt_minimized`` beside them. - Request URLs, ``queryString`` values, ``redirectURL`` and ``Location`` - headers are minimized like any other URL. + Request ``postData.text`` (or ``params``) and response ``content.text`` + become empty and the minimized description goes in + ``_openadapt_minimized`` beside them. Request URLs, ``queryString`` + values, ``redirectURL``, ``Location`` headers and page titles are + minimized like any other URL. Every entry is minimized on its own, so a + raw entry added to an already minimized HAR is minimized too, and a body + minimized before is re-checked against this policy's fields. Wire-tap + ids and versions survive only when they are a kept value. """ doc = json.loads(json.dumps(har)) log = doc.get("log") if isinstance(doc, dict) else None if not isinstance(log, dict): return doc log[HAR_FIELD] = {"schema": MINIMIZED_SCHEMA, "bodies": MINIMIZED} + for page in log.get("pages") or []: + if isinstance(page, dict) and isinstance(page.get("title"), str): + page["title"] = minimizer.url(page["title"]) for entry in log.get("entries") or []: - if not isinstance(entry, dict): - continue - request = entry.get("request") - if isinstance(request, dict): - if isinstance(request.get("url"), str): - request["url"] = minimizer.url(request["url"]) - if isinstance(request.get("queryString"), list): - request["queryString"] = [ - {"name": n, "value": v} - for n, v in up.parse_qsl( - up.urlsplit(request.get("url") or "").query, - keep_blank_values=True, - ) - ] - post = request.get("postData") - if isinstance(post, dict): - _minimize_har_body(post, minimizer, str(post.get("mimeType") or "")) - if isinstance(post.get("params"), list): - post["params"] = [] - response = entry.get("response") - if isinstance(response, dict): - if isinstance(response.get("redirectURL"), str): - response["redirectURL"] = minimizer.url(response["redirectURL"]) - for header in response.get("headers") or []: - if ( - isinstance(header, dict) - and str(header.get("name", "")).lower() == "location" - ): - header["value"] = minimizer.url(header.get("value")) - content = response.get("content") - if isinstance(content, dict): - _minimize_har_body( - content, minimizer, str(content.get("mimeType") or "") + if isinstance(entry, dict): + _minimize_har_entry(entry, minimizer) + return doc + + +_TX_KEPT = ("blocked", "block_reason", "is_mutation", "is_graphql_mutation", "etag") +_TX_VALUES = ("extracted_entity_id", "version") + + +def _minimize_har_entry(entry: dict[str, Any], minimizer: BodyMinimizer) -> None: + kept_values: list[Any] = [] + request = entry.get("request") + if isinstance(request, dict): + if isinstance(request.get("url"), str): + request["url"] = minimizer.url(request["url"]) + if isinstance(request.get("queryString"), list): + request["queryString"] = [ + {"name": n, "value": v} + for n, v in up.parse_qsl( + up.urlsplit(request.get("url") or "").query, + keep_blank_values=True, ) - meta = entry.get("_tx") - if isinstance(meta, dict): - # Wire-tap metadata keeps classifications, ids and versions only. - entry["_tx"] = { - k: v - for k, v in meta.items() - if k - in ( - "blocked", - "block_reason", - "is_mutation", - "is_graphql_mutation", - "extracted_entity_id", - "etag", - "version", + ] + post = request.get("postData") + if isinstance(post, dict): + kept_values += _minimize_har_body( + post, minimizer, str(post.get("mimeType") or "") + ) + response = entry.get("response") + if isinstance(response, dict): + if isinstance(response.get("redirectURL"), str): + response["redirectURL"] = minimizer.url(response["redirectURL"]) + for header in response.get("headers") or []: + if ( + isinstance(header, dict) + and str(header.get("name", "")).lower() == "location" + ): + header["value"] = minimizer.url(header.get("value")) + content = response.get("content") + if isinstance(content, dict): + kept_values += _minimize_har_body( + content, minimizer, str(content.get("mimeType") or "") + ) + meta = entry.get("_tx") + if isinstance(meta, dict): + # Wire-tap metadata keeps classifications; an id or version only + # when the body kept it, else its hash. + out = {k: v for k, v in meta.items() if k in _TX_KEPT} + for k in _TX_VALUES: + if k in meta: + value = meta[k] + out[k] = ( + value + if value is None or value in kept_values + else minimizer.tag(value) ) - } - return doc + entry["_tx"] = out def _minimize_har_body( container: dict[str, Any], minimizer: BodyMinimizer, content_type: str -) -> None: +) -> list[Any]: + """Minimize one HAR body in place; returns the values it kept.""" raw = _har_text(container) + previous = container.get(HAR_FIELD) + params = container.get("params") container.pop("encoding", None) container["text"] = "" - container[HAR_FIELD] = minimizer.body(raw, content_type) + if isinstance(params, list): + container["params"] = [] + if raw is None and isinstance(previous, Mapping): + descriptor: Optional[dict[str, Any]] = minimizer.refilter(previous) + elif raw is None and isinstance(params, list) and params: + descriptor = _minimize_params(params, minimizer) + else: + descriptor = minimizer.body(raw, content_type) + container[HAR_FIELD] = descriptor + if not descriptor: + return [] + return [item[1] for item in descriptor.get("kept") or [] if isinstance(item, list)] + + +def _minimize_params(params: list[Any], minimizer: BodyMinimizer) -> dict[str, Any]: + pairs = [p for p in params if isinstance(p, Mapping)] + out: dict[str, Any] = {"schema": MINIMIZED_SCHEMA, "content_type": ""} + if any(p.get("fileName") or p.get("contentType") for p in pairs) or len( + pairs + ) != len(params): + out.update( + format="opaque", hmac=minimizer.tag(json.dumps(params, sort_keys=True)) + ) + return out + out["format"] = "form" + out.update(minimizer.pairs([p.get("name", ""), p.get("value", "")] for p in pairs)) + return out + + +def mutation_floor(entry: Mapping[str, Any]) -> bool: + """Whether a minimized HAR entry must replay as a write. + + Replay classifies from what was kept, which can make a write look like a + read (a GraphQL document hashed in a ``GET`` query, an operation lost + from a batch). The wire tap's recorded ``is_mutation`` is the floor; + without one, a withheld or opaque write body or a hashed GraphQL + document is. + """ + meta = entry.get("_tx") + if isinstance(meta, Mapping) and isinstance(meta.get("is_mutation"), bool): + return meta["is_mutation"] + request = entry.get("request") + if not isinstance(request, Mapping): + return False + method = str(request.get("method") or "GET").upper() + post = request.get("postData") + body = post.get(HAR_FIELD) if isinstance(post, Mapping) else None + if method not in _READ_METHODS and isinstance(body, Mapping): + if body.get("withheld") or body.get("format") not in ("json", "form"): + return True + parts = up.urlsplit(str(request.get("url") or "")) + graphql = parts.path.rstrip("/").lower().endswith("/graphql") + return any( + (graphql or name == "query") and TAG.fullmatch(value) + for name, value in up.parse_qsl(parts.query, keep_blank_values=True) + ) def is_minimized_har(har: Mapping[str, Any]) -> bool: @@ -344,7 +509,16 @@ def minimize_line(line: Mapping[str, Any], minimizer: BodyMinimizer) -> dict[str out[key] = minimizer.url(out[key]) request_type = str(out.get("request_type") or "") if "form" in out: - out["form_minimized"] = minimizer.pairs(out.pop("form") or []) + form = out.pop("form") or [] + if out.get("request_truncated"): + # A cut form may end mid-value: keep nothing of it. + out["form_minimized"] = { + "format": "opaque", + "truncated": True, + "hmac": minimizer.tag(json.dumps(form)), + } + else: + out["form_minimized"] = minimizer.pairs(form) if "body" in out: out["body_minimized"] = minimizer.body( out.pop("body"), diff --git a/packages/flow/openadapt_flow/network_capture.py b/packages/flow/openadapt_flow/network_capture.py index 2908bbbc7d..faba1e26b8 100644 --- a/packages/flow/openadapt_flow/network_capture.py +++ b/packages/flow/openadapt_flow/network_capture.py @@ -352,33 +352,62 @@ def write(self, recording_dir: Path | str, t0_monotonic: float) -> Path: path = Path(recording_dir) / NETWORK_FILE lines = self.lines(t0_monotonic) - if self._bodies == cp.RAW: - _require_sealed_or_allowed(path) - else: - minimizer = cp.BodyMinimizer(self._keep_fields) + if self._bodies != cp.RAW: + minimizer = cp.BodyMinimizer( + {f for f in self._keep_fields if not SECRET_NAME.search(f)}, + withhold=self._secret_names, + ) lines = [cp.minimize_line(line, minimizer) for line in lines] header = {"schema": SCHEMA, "exchanges": len(lines), "bodies": self._bodies} text = json.dumps(header) + "\n" text += "".join(json.dumps(line, sort_keys=True) + "\n" for line in lines) + data = text.encode("utf-8") + if self._bodies == cp.RAW and not raw_plaintext_allowed(path): + # Checked and written in one lookup: never plaintext if unsealed. + try: + sealed_set.write_bytes(path, data, sealed_only=True) + except PermissionError: + raise _raw_refusal() from None + return path # Sealed in memory when the recording is encrypted. - sealed_set.write_text(path, text) + sealed_set.write_bytes(path, data) return path -def _require_sealed_or_allowed(path: Path) -> None: - """Refuse raw bodies on disk unless the recording is encrypted. +def raw_plaintext_allowed(path: Path | str) -> bool: + """Whether raw bodies may go to ``path`` in plaintext: not sealed, and + ``OPENADAPT_FLOW_PLAINTEXT_AT_REST`` allows it (recorded if so).""" + from openadapt_flow import at_rest, sealed_set + + if sealed_set.is_sealed_path(path): + return False + return at_rest.plaintext_allowed(_RAW_PURPOSE) + + +def require_raw_ready(recording_dir: Path | str) -> None: + """Refuse raw bodies unless the recording is encrypted or plaintext is + explicitly allowed. Callers that build ``NetworkCapture(bodies="raw")`` + themselves call it before driving the app, so nothing runs in vain. TODO(#2423): once the key hierarchy lands, seal raw captures under the recording's own data key rather than relying on the recording writer. """ - from openadapt_flow import at_rest, sealed_set + from openadapt_flow import sealed_set - if sealed_set.is_sealed_path(path): + if sealed_set.is_sealed_path(recording_dir) or raw_plaintext_allowed(recording_dir): return - if at_rest.plaintext_allowed(_RAW_PURPOSE): - return - raise at_rest.AtRestRefused( - at_rest.refusal(_RAW_PURPOSE, "the recording is not encrypted") + raise _raw_refusal() + + +def _raw_refusal() -> Exception: + from openadapt_flow import at_rest + + return at_rest.AtRestRefused( + at_rest.refusal( + _RAW_PURPOSE, + "the recording is not encrypted (set OPENADAPT_RECORDING_KEY or " + "OPENADAPT_BUNDLE_KEY, or use OPENADAPT_FLOW_AT_REST=strict)", + ) ) @@ -426,7 +455,9 @@ def cli_mode(args: Any, recording_key: Optional[str]) -> bool | str: if not at_rest.plaintext_allowed(_RAW_PURPOSE): raise SystemExit( "record: --capture-network-bodies raw needs an encrypted " - "recording (drop --no-encrypt). Nothing was recorded." + "recording: set OPENADAPT_RECORDING_KEY or OPENADAPT_BUNDLE_KEY, " + "or use OPENADAPT_FLOW_AT_REST=strict, and drop --no-encrypt. " + "Nothing was recorded." ) return str(mode) diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index 9416f65096..c78c1bfc35 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -1116,10 +1116,22 @@ def open_text(path: Path | str, encoding: str = "utf-8") -> io.StringIO: return io.StringIO(read_text(path, encoding)) -def write_bytes(path: Path | str, data: bytes, *, key: Optional[str] = None) -> None: - """Write ``path``; sealed if it lies in an active writer or a sealed set.""" +def write_bytes( + path: Path | str, + data: bytes, + *, + key: Optional[str] = None, + sealed_only: bool = False, +) -> None: + """Write ``path``; sealed if it lies in an active writer or a sealed set. + + ``sealed_only`` refuses (``PermissionError``) instead of writing plaintext + when ``path`` turns out not to be sealed, in the same lookup as the write. + """ root, rel = _locate(path) if root is None: + if sealed_only: + raise PermissionError(f"{path} is not in a sealed set; not written") target = Path(path) target.write_bytes(data) return diff --git a/packages/flow/openadapt_flow/tx/wire_tap.py b/packages/flow/openadapt_flow/tx/wire_tap.py index 0167ca1fe5..fa03a4d70d 100644 --- a/packages/flow/openadapt_flow/tx/wire_tap.py +++ b/packages/flow/openadapt_flow/tx/wire_tap.py @@ -1092,7 +1092,10 @@ def import_har( self, source: str | Path | bytes | Mapping[str, Any] ) -> WireSessionSummary: """Replay entries from a HAR 1.2 document into the current wire-tap session.""" + from openadapt_flow.capture_privacy import is_minimized_har, mutation_floor + har = load_har(source, secrets=self._policy.secrets) + minimized = is_minimized_har(har) entries = har.get("log", {}).get("entries", []) for entry in entries: if not isinstance(entry, Mapping): @@ -1153,6 +1156,7 @@ def import_har( request_headers=dict(req_headers), response_headers=dict(resp_headers), duration_ms=duration_ms, + assume_mutation=minimized and mutation_floor(entry), ) return self.summary() @@ -1287,6 +1291,7 @@ def _begin_request( raw_target: str, request_headers: list[tuple[str, str]], request_body: bytes, + assume_mutation: bool = False, ) -> dict[str, Any]: """Atomically classify and gate a request before any upstream network I/O.""" upper_method = method.strip().upper() @@ -1298,6 +1303,7 @@ def _begin_request( request_body, request_headers, ) + is_mut = is_mut or assume_mutation started_utc = _utc_now_iso() req_sha = hashlib.sha256(request_body).hexdigest() masked_url = _mask_if_needed(full_url, self._policy.secrets) @@ -1700,8 +1706,13 @@ def record_exchange( Mapping[str, str] | Iterable[tuple[str, str]] ] = None, duration_ms: float = 0.0, + assume_mutation: bool = False, ) -> Optional[WireMutationRecord]: - """Programmatically gate and record an HTTP exchange in-process.""" + """Programmatically gate and record an HTTP exchange in-process. + + ``assume_mutation`` counts it as a write whatever it looks like (a + minimized HAR's recorded write whose body was withheld). + """ req_bytes = _to_bytes(request_body) req_hdrs = _header_pairs(request_headers) ticket = self._begin_request( @@ -1709,6 +1720,7 @@ def record_exchange( raw_target=url, request_headers=req_hdrs, request_body=req_bytes, + assume_mutation=assume_mutation, ) if ticket["blocked"]: status, _reason, err_hdrs, err_body = self._blocked_http_payload( @@ -1893,14 +1905,10 @@ def dump_har( Bodies are minimized by default (:mod:`openadapt_flow.capture_privacy`): only ``keep_fields`` values survive (default: the policy's id and version fields), the rest become keyed hashes. ``raw_bodies=True`` keeps them for - debugging; a file is always sealed under the at-rest key + debugging and needs ``path``; a file is always sealed under the at-rest key (``write_private_record``). TODO(#2423): use the key hierarchy's data key. """ - from openadapt_flow.capture_privacy import ( - BodyMinimizer, - is_minimized_har, - minimize_har, - ) + from openadapt_flow.capture_privacy import BodyMinimizer, minimize_har raw_har: Mapping[str, Any] = ( har_or_tap.export_har() @@ -1909,7 +1917,12 @@ def dump_har( ) secret_tuple = tuple(s for s in secrets if s) scrubbed = _scrub_har_value(dict(raw_har), secret_tuple) - if not raw_bodies and not is_minimized_har(scrubbed): + if raw_bodies and path is None: + # Raw bodies go only to a sealed file, never back as plain text. + raise ValueError("dump_har(raw_bodies=True) needs a path to seal them to") + if not raw_bodies: + # Every entry, even in a HAR minimized before (a raw entry added to + # it is minimized, and earlier kept values are re-checked). policy = ( har_or_tap.policy if isinstance(har_or_tap, SessionWireTap) diff --git a/packages/flow/tests/test_capture_privacy.py b/packages/flow/tests/test_capture_privacy.py index db18c720da..3aaae75fe9 100644 --- a/packages/flow/tests/test_capture_privacy.py +++ b/packages/flow/tests/test_capture_privacy.py @@ -39,7 +39,7 @@ def _forms(value: str) -> list[bytes]: raw, quote(value, safe="").encode(), quote_plus(value).encode(), - json.dumps(value)[1:-1].encode(), + json.dumps(value, ensure_ascii=False)[1:-1].encode(), json.dumps(value, ensure_ascii=True)[1:-1].encode(), base64.b64encode(raw), base64.urlsafe_b64encode(raw).rstrip(b"="), @@ -47,32 +47,82 @@ def _forms(value: str) -> list[bytes]: def _plain(data: bytes) -> bytes: - """``data`` decrypted (Flow's at-rest format) and gunzipped when it is.""" + """``data`` decrypted (Flow's at-rest format) and gunzipped when it is. + + A file that is encrypted but doesn't decrypt fails the test: the scan + must never pass by looking at ciphertext. + """ if crypto.is_encrypted(data): - for aad in (b"openadapt-flow/tx-private-state",): - try: - data = crypto.decrypt_bytes( - data, crypto.resolve_read_key(None), aad=aad - ) - break - except Exception: # noqa: BLE001 - try the next context - continue + data = crypto.decrypt_bytes( + data, crypto.resolve_read_key(None), aad=b"openadapt-flow/tx-private-state" + ) if data[:2] == b"\x1f\x8b": data = gzip.decompress(data) return data -def _leaks(root: Path) -> list[tuple[str, str]]: +def _decoded(data: bytes) -> list[bytes]: + """``data`` and every body inside it: JSON strings, base64 and gzip.""" + out = [data] + try: + document = json.loads(data) + except ValueError: + return out + stack = [document] + while stack: + node = stack.pop() + if isinstance(node, dict): + stack.extend(node.values()) + elif isinstance(node, list): + stack.extend(node) + elif isinstance(node, str): + out.append(node.encode("utf-8", "surrogatepass")) + try: + blob = base64.b64decode(node, validate=True) + except ValueError: + continue + out.append(blob) + if blob[:2] == b"\x1f\x8b": + out.append(gzip.decompress(blob)) + return out + + +def _leaks(root: Path, values: tuple[str, ...] = PHI) -> list[tuple[str, str]]: found = [] for path in sorted(p for p in root.rglob("*") if p.is_file()): - data = _plain(path.read_bytes()) - for value in PHI: - for form in _forms(value): - if form in data: - found.append((str(path.relative_to(root)), value)) + blobs = _decoded(_plain(path.read_bytes())) + for value in values: + if any(form in blob for blob in blobs for form in _forms(value)): + found.append((str(path.relative_to(root)), value)) return found +# A canary whose raw, percent, JSON-escaped and base64 spellings all differ. +CANARY = 'Zoë "Q" Ångström/1931' + + +@pytest.mark.parametrize("index", range(7)) +def test_scanner_finds_each_encoding(tmp_path: Path, index: int) -> None: + form = _forms(CANARY)[index] + others = [f for i, f in enumerate(_forms(CANARY)) if i != index] + assert form not in others # each control checks a distinct spelling + (tmp_path / "f.bin").write_bytes(b"x" + form + b"y") + assert _leaks(tmp_path, (CANARY,)) == [("f.bin", CANARY)] + + +def test_scanner_finds_gzip_inside_a_har_body_and_refuses_ciphertext( + tmp_path: Path, +) -> None: + body = base64.b64encode(gzip.compress(CANARY.encode())).decode() + har = {"log": {"entries": [{"response": {"content": {"text": body}}}]}} + (tmp_path / "s.har").write_text(json.dumps(har)) + assert _leaks(tmp_path, (CANARY,)) == [("s.har", CANARY)] + sealed = crypto.encrypt_bytes(b"{}", "a-different-key", aad=b"other") + (tmp_path / "s.har").write_bytes(sealed) + with pytest.raises(Exception): + _leaks(tmp_path, (CANARY,)) + + # -- network.jsonl ------------------------------------------------------------ @@ -330,12 +380,26 @@ def test_raw_har_opt_in_is_sealed_on_disk(tmp_path: Path) -> None: # -- minimizer ------------------------------------------------------------------- -def test_hash_key_is_per_capture_and_never_written() -> None: +def test_hash_key_is_per_capture_and_never_written( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: a, b = cp.BodyMinimizer(), cp.BodyMinimizer() assert a.tag(DOB) == a.tag(DOB) assert a.tag(DOB) != b.tag(DOB) out = a.body(json.dumps({"dob": DOB}).encode(), "application/json") assert out is not None and DOB not in json.dumps(out) + # A known key, injected where captures make theirs, is in no output. + key = bytes(range(32)) + monkeypatch.setattr(cp.secrets, "token_bytes", lambda n: key[:n]) + (tmp_path / "rec").mkdir() + _record(tmp_path / "rec") + _tap().save_har(tmp_path / "rec" / "s.har") + spellings = [key, key.hex().encode(), base64.b64encode(key)] + spellings += [base64.urlsafe_b64encode(key).rstrip(b"=")] + for path in (tmp_path / "rec").rglob("*"): + if path.is_file(): + for blob in _decoded(_plain(path.read_bytes())): + assert not any(k in blob for k in spellings), path def test_keys_that_are_not_field_names_are_hashed() -> None: @@ -362,3 +426,157 @@ def test_url_query_values_are_hashed_unless_declared() -> None: url = m.url(f"http://app.test/s?q={quote_plus(PATIENT)}&page=2") assert quote_plus(PATIENT) not in url and PATIENT not in url assert "page=2" in url + + +# -- review regressions ------------------------------------------------------------ + + +def _replayed(tap: SessionWireTap, tmp_path: Path, **kw: Any) -> Any: + path = tmp_path / "r.har" + dump_har(tap, path, **kw) + return SessionWireTap.from_har(path).summary() + + +def test_replay_keeps_writes_whose_evidence_was_withheld(tmp_path: Path) -> None: + tap = SessionWireTap("http://app.test") + batch = [{"query": "query A { a }"}, {"query": "mutation B { b }"}] + tap.record_exchange( + method="POST", + url="http://app.test/graphql", + request_body=json.dumps(batch).encode(), + request_headers={"Content-Type": "application/json"}, + response_body=b"{}", + ) + tap.record_exchange( + method="GET", url="http://app.test/api?query=" + quote("mutation { x }") + ) + live = tap.summary() + replay = _replayed(tap, tmp_path, keep_fields=("query",)) + assert replay.mutations_allowed + replay.mutations_blocked == ( + live.mutations_allowed + live.mutations_blocked + ) + assert replay.read_requests == live.read_requests + + +def test_floor_without_tap_metadata() -> None: + m = cp.BodyMinimizer() + entry = {"request": {"method": "GET", "url": m.url("http://a.test/x?query=m")}} + assert cp.mutation_floor(entry) + post = {"method": "POST", "url": "http://a.test/x", "postData": {}} + post["postData"][cp.HAR_FIELD] = m.body(b'{"a": 1}', "application/json") + assert cp.mutation_floor({"request": post}) + + +def test_raw_entry_added_to_a_minimized_har_is_minimized(tmp_path: Path) -> None: + har = load_har(dump_har(_tap())) + raw = json.loads(json.dumps(_tap().export_har()))["log"]["entries"][0] + har["log"]["entries"].append(raw) + har["log"]["pages"] = [{"title": f"http://app.test/?q={quote_plus(PATIENT)}"}] + (tmp_path / "s.har").write_text(dump_har(har)) + assert _leaks(tmp_path) == [] + narrowed = json.loads(dump_har(har, keep_fields=())) + for entry in narrowed["log"]["entries"]: + assert entry["_tx"].get("extracted_entity_id") != "51" + assert entry["_tx"].get("version") != "3" + + +def test_truncated_forms_and_non_json_types_keep_nothing() -> None: + m = cp.BodyMinimizer(("id", "note")) + line = cp.minimize_line({"form": [["note", PATIENT]], "request_truncated": True}, m) + assert PATIENT not in json.dumps(line) + for ctype in ("text/plain", "text/html", "image/png"): + out = m.body(json.dumps({"id": PATIENT}).encode(), ctype) + assert out is not None and out["format"] == "opaque" + assert PATIENT not in json.dumps(out) + + +def test_declared_secret_is_withheld_whatever_its_case(tmp_path: Path) -> None: + ctx = _Context() + cap = nc.NetworkCapture(ctx, secret_names={"code"}, keep_fields={"CODE"}) + cap.start() + ctx.handlers["requestfinished"]( + _Request( + "http://app.test/cb?code=xy", + "GET", + None, + None, + _Response(200, "text/html", b""), + ) + ) + cap.write(tmp_path, t0_monotonic=0.0) + assert "code=xy" not in (tmp_path / nc.NETWORK_FILE).read_text() + + +def test_fragment_queries_and_bare_terms_are_hashed() -> None: + m = cp.BodyMinimizer(("page",)) + for url in ( + f"http://a.test/#/search?q={quote_plus(PATIENT)}&page=2", + f"http://a.test/#q={quote_plus(PATIENT)}", + f"http://a.test/s?{quote_plus(PATIENT)}", + ): + out = m.url(url) + assert quote_plus(PATIENT) not in out and PATIENT not in out + assert "page=2" in m.url("http://a.test/#/s?q=x&page=2") + once = m.url(f"http://a.test/s?q={quote_plus(PATIENT)}") + assert m.url(once) == once + + +def test_restored_json_keeps_lists_and_dotted_versions() -> None: + m = cp.BodyMinimizer(("id", "meta.versionId")) + doc = {"data": {"id": ["one", "two"]}, "record": {"meta": {"versionId": "7"}}} + out = m.body(json.dumps(doc).encode(), "application/json") + assert out is not None + restored = json.loads(cp.restore_kept_json(out)) + assert restored == doc + + +def test_params_only_har_form_is_minimized() -> None: + har = { + "log": { + "entries": [ + { + "request": { + "method": "POST", + "url": "http://a.test/f", + "postData": { + "mimeType": "application/x-www-form-urlencoded", + "params": [ + {"name": "id", "value": "9"}, + {"name": "dx", "value": DIAGNOSIS}, + ], + }, + } + } + ] + } + } + out = cp.minimize_har(har, cp.BodyMinimizer(("id",))) + post = out["log"]["entries"][0]["request"]["postData"] + assert post["params"] == [] and DIAGNOSIS not in json.dumps(out) + assert ["id", "9"] in post[cp.HAR_FIELD]["kept"] + assert [n for n, _ in post[cp.HAR_FIELD]["withheld"]] == ["dx"] + + +def test_lone_surrogate_is_hashed_not_fatal() -> None: + out = cp.BodyMinimizer().body(b'{"a": "\\ud800"}', "application/json") + assert out is not None and out["withheld"][0][1].startswith("hmac-sha256:") + + +def test_raw_har_without_a_path_is_refused() -> None: + with pytest.raises(ValueError): + dump_har(_tap(), raw_bodies=True) + + +def test_raw_network_write_never_falls_back_to_plaintext( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from openadapt_flow import sealed_set + + monkeypatch.delenv(at_rest.OPT_OUT_ENV, raising=False) + with pytest.raises(PermissionError): + sealed_set.write_bytes(tmp_path / "x", b"raw", sealed_only=True) + assert not (tmp_path / "x").exists() + with pytest.raises(at_rest.AtRestRefused): + nc.require_raw_ready(tmp_path) + monkeypatch.setenv(at_rest.OPT_OUT_ENV, "test: synthetic data") + nc.require_raw_ready(tmp_path) From eb95a37ddbc319069a00804e6d1855c58064d880 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:15:29 -0500 Subject: [PATCH 5/9] fix(flow): keep minimized HAR descriptions across a reload and return no raw HAR text - A body minimized before and reloaded (its kept fields restored as text) keeps its description instead of being minimized again from the kept fields alone. - dump_har(raw_bodies=True) writes the sealed file and returns an empty string, so raw bodies are never handed back in memory. - The replay test also covers default fields, where the recorded write floor is what keeps the counts. --- .../flow/openadapt_flow/capture_privacy.py | 7 +++++- packages/flow/openadapt_flow/tx/wire_tap.py | 5 ++-- packages/flow/tests/test_capture_privacy.py | 25 +++++++++++++++---- 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/packages/flow/openadapt_flow/capture_privacy.py b/packages/flow/openadapt_flow/capture_privacy.py index 9e9e136cef..ab6239baa4 100644 --- a/packages/flow/openadapt_flow/capture_privacy.py +++ b/packages/flow/openadapt_flow/capture_privacy.py @@ -435,7 +435,12 @@ def _minimize_har_body( container["text"] = "" if isinstance(params, list): container["params"] = [] - if raw is None and isinstance(previous, Mapping): + if isinstance(previous, Mapping) and ( + raw is None or raw == restore_kept_json(previous) + ): + # Minimized before (and maybe reloaded, which put its kept fields + # back as text): keep its description, re-checked against this + # policy. Any other text is new and is minimized afresh. descriptor: Optional[dict[str, Any]] = minimizer.refilter(previous) elif raw is None and isinstance(params, list) and params: descriptor = _minimize_params(params, minimizer) diff --git a/packages/flow/openadapt_flow/tx/wire_tap.py b/packages/flow/openadapt_flow/tx/wire_tap.py index fa03a4d70d..e203f0955e 100644 --- a/packages/flow/openadapt_flow/tx/wire_tap.py +++ b/packages/flow/openadapt_flow/tx/wire_tap.py @@ -1906,7 +1906,7 @@ def dump_har( only ``keep_fields`` values survive (default: the policy's id and version fields), the rest become keyed hashes. ``raw_bodies=True`` keeps them for debugging and needs ``path``; a file is always sealed under the at-rest key - (``write_private_record``). TODO(#2423): use the key hierarchy's data key. + (``write_private_record``) and nothing is returned (``""``). TODO(#2423): use the key hierarchy's data key. """ from openadapt_flow.capture_privacy import BodyMinimizer, minimize_har @@ -1938,7 +1938,8 @@ def dump_har( if path is not None: out = Path(path) write_private_record(out, payload.encode("utf-8")) - return payload + # Raw bodies are only ever in the sealed file, not handed back. + return "" if raw_bodies else payload def load_har( diff --git a/packages/flow/tests/test_capture_privacy.py b/packages/flow/tests/test_capture_privacy.py index 3aaae75fe9..3ef79cfffb 100644 --- a/packages/flow/tests/test_capture_privacy.py +++ b/packages/flow/tests/test_capture_privacy.py @@ -451,11 +451,26 @@ def test_replay_keeps_writes_whose_evidence_was_withheld(tmp_path: Path) -> None method="GET", url="http://app.test/api?query=" + quote("mutation { x }") ) live = tap.summary() - replay = _replayed(tap, tmp_path, keep_fields=("query",)) - assert replay.mutations_allowed + replay.mutations_blocked == ( - live.mutations_allowed + live.mutations_blocked - ) - assert replay.read_requests == live.read_requests + # Default fields hash the GraphQL documents; "query" keeps them. + for kw in ({}, {"keep_fields": ("query",)}): + replay = _replayed(tap, tmp_path, **kw) + assert replay.mutations_allowed + replay.mutations_blocked == ( + live.mutations_allowed + live.mutations_blocked + ) + assert replay.read_requests == live.read_requests + + +def test_reloading_a_minimized_har_keeps_its_descriptions(tmp_path: Path) -> None: + first = json.loads(dump_har(_tap())) + second = json.loads(dump_har(load_har(json.dumps(first)))) + for a, b in zip(first["log"]["entries"], second["log"]["entries"]): + for side, key in (("request", "postData"), ("response", "content")): + if key in a[side]: + assert a[side][key][cp.HAR_FIELD] == b[side][key][cp.HAR_FIELD] + + +def test_raw_har_is_not_returned_in_memory(tmp_path: Path) -> None: + assert dump_har(_tap(), tmp_path / "raw.har", raw_bodies=True) == "" def test_floor_without_tap_metadata() -> None: From a6a8976e899a01f63223d632e4ff56dd16f3377e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:11:17 -0500 Subject: [PATCH 6/9] fix(flow): close the four capture-privacy findings left open - Size and hash every body from its bytes as sent; binary bodies, multipart files and non-text responses get an opaque descriptor, and url-encoded responses are minimized (Codex #10). - Minimize the query of meta.json app_url with the capture's key (#6). - Parse JSON only when labelled JSON or with no content type; the wire tap records a missing header as "" (#4). - load_har refuses a document marked minimized whose body carries raw text or params (#2). - Minimize URL-valued HAR headers (Referer, Content-Location, Refresh). --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/CHANGELOG.md | 7 +- packages/flow/docs/NETWORK_CAPTURE.md | 23 +- .../flow/openadapt_flow/capture_privacy.py | 81 +++- .../flow/openadapt_flow/network_capture.py | 141 +++++-- packages/flow/openadapt_flow/recorder.py | 6 +- packages/flow/openadapt_flow/tx/wire_tap.py | 36 +- packages/flow/tests/test_capture_privacy.py | 345 ++++++++++++++++++ packages/flow/tests/test_tx_har_redaction.py | 5 + 10 files changed, 575 insertions(+), 73 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 49250c7518..892f8f54ab 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -258,7 +258,7 @@ improvising or retrying when something is off. | Page structure (DOM, UI Automation, Accessibility) first, then template, OCR and geometry | Released | Real apps on the web; synthetic on Windows and macOS | [RESOLUTION_LADDER.md](packages/flow/docs/RESOLUTION_LADDER.md) | | Run a step as a direct API call (`ApiActuator`, `ApiBinding`) | Released, hand-authored bindings | Synthetic benchmarks | `runtime/actuators/api.py` | | Capture a recording's network traffic and compile a clean save into an API step, with the same record check | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic patients on a local OpenEMR test copy | network capture, `ApiBinding` | -| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash (a body labelled JSON, or unlabelled `application/octet-stream`, is parsed as JSON). Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest or plaintext is explicitly allowed (`OPENADAPT_FLOW_PLAINTEXT_AT_REST`, warned and logged). Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | +| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash, taken from the bytes as sent (only a body labelled JSON, or with no content type, is parsed as JSON); the recording's `app_url` query and URL-valued HAR headers are minimized too, and a HAR marked minimized that carries a raw body is refused on load. Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest or plaintext is explicitly allowed (`OPENADAPT_FLOW_PLAINTEXT_AT_REST`, warned and logged). Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | | Fall back from the API step to page structure when the API is unavailable, before anything is sent | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic | [#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269) | | Run a form's own script before an API save instead of refusing the form: field handlers, `onsubmit`, submit listeners and custom validate.js rules (OpenEMR's `pastDate`) run on the run's values in a scratch copy of the session with every write blocked, and the save is sent only when the page lets the submit through and would send the same body | On main | Synthetic (headless Chromium against a local test page) | [API_TIER.md](packages/flow/docs/API_TIER.md#what-happens-at-run-time), `runtime/actuators/form_eval.py` | | Compare paired GUI/API database changes with `api admit --footprint`: changed rows retain their identity and before/after values, and unexplained field differences refuse. Variation alone does not establish server ownership. | This PR | Synthetic headless Chromium and SQLite; generated insert ID/time differences conservatively refuse | `openadapt_flow/api_footprint.py` | diff --git a/llms-full.txt b/llms-full.txt index 25a2df6f6e..97f3bd0c44 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -698,7 +698,7 @@ improvising or retrying when something is off. | Page structure (DOM, UI Automation, Accessibility) first, then template, OCR and geometry | Released | Real apps on the web; synthetic on Windows and macOS | [RESOLUTION_LADDER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RESOLUTION_LADDER.md) | | Run a step as a direct API call (`ApiActuator`, `ApiBinding`) | Released, hand-authored bindings | Synthetic benchmarks | `runtime/actuators/api.py` | | Capture a recording's network traffic and compile a clean save into an API step, with the same record check | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic patients on a local OpenEMR test copy | network capture, `ApiBinding` | -| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash (a body labelled JSON, or unlabelled `application/octet-stream`, is parsed as JSON). Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest or plaintext is explicitly allowed (`OPENADAPT_FLOW_PLAINTEXT_AT_REST`, warned and logged). Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | +| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash, taken from the bytes as sent (only a body labelled JSON, or with no content type, is parsed as JSON); the recording's `app_url` query and URL-valued HAR headers are minimized too, and a HAR marked minimized that carries a raw body is refused on load. Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest or plaintext is explicitly allowed (`OPENADAPT_FLOW_PLAINTEXT_AT_REST`, warned and logged). Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | | Fall back from the API step to page structure when the API is unavailable, before anything is sent | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic | [#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269) | | Run a form's own script before an API save instead of refusing the form: field handlers, `onsubmit`, submit listeners and custom validate.js rules (OpenEMR's `pastDate`) run on the run's values in a scratch copy of the session with every write blocked, and the save is sent only when the page lets the submit through and would send the same body | On main | Synthetic (headless Chromium against a local test page) | [API_TIER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/API_TIER.md#what-happens-at-run-time), `runtime/actuators/form_eval.py` | | Compare paired GUI/API database changes with `api admit --footprint`: changed rows retain their identity and before/after values, and unexplained field differences refuse. Variation alone does not establish server ownership. | This PR | Synthetic headless Chromium and SQLite; generated insert ID/time differences conservatively refuse | `openadapt_flow/api_footprint.py` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 8647ad348e..832253c9f8 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -27,7 +27,12 @@ policy's id and version fields. `--capture-network-bodies raw` (and `raw_bodies=True`) keeps the redacted bodies, which API step and undo proposals need, and is refused unless the recording is encrypted or - `OPENADAPT_FLOW_PLAINTEXT_AT_REST` explicitly allows plaintext. + `OPENADAPT_FLOW_PLAINTEXT_AT_REST` explicitly allows plaintext. Binary + bodies, files and non-text responses are sized and hashed from their + bytes as sent; the recording's `app_url` query is minimized too; an + explicit `application/octet-stream` body is never parsed as JSON (a + missing content type still is); and `load_har` refuses a HAR marked + minimized that carries a raw body. ## v3.4.0 (2026-11-21) diff --git a/packages/flow/docs/NETWORK_CAPTURE.md b/packages/flow/docs/NETWORK_CAPTURE.md index 80f39f2d42..0965543d6a 100644 --- a/packages/flow/docs/NETWORK_CAPTURE.md +++ b/packages/flow/docs/NETWORK_CAPTURE.md @@ -71,17 +71,30 @@ memory and writes only what the recording declared (a birth date) can't be recovered by trying candidates. - **Opaque:** HTML, plain text, binary, a cut body or form, or a multipart body with a file keeps only its length, content type and hash. - JSON is parsed only from a body labelled JSON or unlabelled - (`application/octet-stream`); JSON-looking text of any other type is - opaque. + JSON is parsed only from a body labelled JSON or with no content type; + JSON-looking text of any other type, including an explicit + `application/octet-stream`, is opaque. Length and hash are taken from the + body's bytes as sent, before decoding, redaction or cutting. So `form`, `body` and `response_text` are replaced by `form_minimized`, `body_minimized` and `response_minimized`, each `{"kept": [[path, value]], "withheld": [[path, hash]]}` (bodies also carry `format`, `bytes`, `content_type` and a whole-body `hmac`), and `url`, `frame_url` and `location` have undeclared query values hashed (also a query in the -fragment, `#/search?q=...`, and a bare search term, `?term`). Not minimized: URL path -segments (`/patients/1234`) and JSON keys that look like field names. +fragment, `#/search?q=...`, and a bare search term, `?term`). The +recording's starting URL in `meta.json` (`app_url`) gets the same +treatment, under the same key. Not minimized: URL path segments +(`/patients/1234`) and JSON keys that look like field names. + +Every response that is not a static asset is described: a binary or other +non-text response (a PDF, a download) and a url-encoded response get a +`response_minimized` too. A binary body is never written as text, raw mode +included. + +A saved wire-tap HAR is minimized the same way, including URL-valued +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 diff --git a/packages/flow/openadapt_flow/capture_privacy.py b/packages/flow/openadapt_flow/capture_privacy.py index ab6239baa4..ec8bce1750 100644 --- a/packages/flow/openadapt_flow/capture_privacy.py +++ b/packages/flow/openadapt_flow/capture_privacy.py @@ -15,9 +15,9 @@ * Anything that does not parse that way (HTML, plain text, binary, a cut body, a multipart body that carries a file) keeps only its length, its content type and a keyed hash of the whole body. JSON is parsed only from - a body labelled JSON or unlabelled (``application/octet-stream``, the wire - tap's type for a missing header); JSON-looking text in any other type is - opaque. + a body labelled JSON (``application/json``, ``*/*+json``) or with no + content type at all; JSON-looking text in any other type, including an + explicit ``application/octet-stream``, is opaque. * URL query values are treated the same way, because a ``GET`` form puts the person's input there. Path segments are kept (see "Not covered"). @@ -30,7 +30,9 @@ Not covered: URL path segments (``/patients/1234``) and JSON object keys that look like ordinary field names are kept as written. A key that does not look like a field name (spaces, punctuation, over 64 characters) is hashed -like a value. Header values are handled by the credential redaction only. +like a value. Header values are handled by the credential redaction only, +except URL-valued HAR headers (``Location``, ``Referer``), whose query is +minimized like any URL. Stdlib only (no ``openadapt_flow`` import), so the wire tap and the recorder load it without changing their import cost. @@ -193,6 +195,24 @@ def body( out.update(result) return out + def opaque( + self, raw: bytes, content_type: str = "", *, truncated: bool = False + ) -> Optional[dict[str, Any]]: + """Size, type and keyed hash of ``raw`` as sent (bytes, undecoded); + nothing of its content. None for an empty body.""" + if not raw: + return None + out: dict[str, Any] = { + "schema": MINIMIZED_SCHEMA, + "bytes": len(raw), + "content_type": (content_type or "").split(";")[0].strip().lower(), + "hmac": self.tag(bytes(raw)), + "format": "opaque", + } + if truncated: + out["truncated"] = True + return out + def _parse( self, data: bytes, ctype: str, full_type: str ) -> Optional[tuple[str, dict[str, Any]]]: @@ -208,11 +228,9 @@ def _parse( return None fields, _files = parsed return "form", self.pairs(fields) - # JSON only when labelled JSON or unlabelled: octet-stream is the wire - # tap's type for a missing header. HTML and text stay opaque. - json_type = ctype in ("", "application/octet-stream") or ctype.endswith( - ("/json", "+json") - ) + # JSON only when labelled JSON or unlabelled (no content type at + # all). An explicit octet-stream, HTML or text body stays opaque. + json_type = ctype == "" or ctype.endswith(("/json", "+json")) if json_type and text.lstrip().startswith(_JSON_START): try: document = json.loads(text) @@ -350,7 +368,8 @@ def minimize_har(har: Mapping[str, Any], minimizer: BodyMinimizer) -> dict[str, Request ``postData.text`` (or ``params``) and response ``content.text`` become empty and the minimized description goes in ``_openadapt_minimized`` beside them. Request URLs, ``queryString`` - values, ``redirectURL``, ``Location`` headers and page titles are + values, ``redirectURL``, URL-valued headers (``Location``, ``Referer``, + ``Content-Location``, ``Refresh``) and page titles are minimized like any other URL. Every entry is minimized on its own, so a raw entry added to an already minimized HAR is minimized too, and a body minimized before is re-checked against this policy's fields. Wire-tap @@ -388,6 +407,7 @@ def _minimize_har_entry(entry: dict[str, Any], minimizer: BodyMinimizer) -> None keep_blank_values=True, ) ] + _minimize_url_headers(request, minimizer) post = request.get("postData") if isinstance(post, dict): kept_values += _minimize_har_body( @@ -397,12 +417,7 @@ def _minimize_har_entry(entry: dict[str, Any], minimizer: BodyMinimizer) -> None if isinstance(response, dict): if isinstance(response.get("redirectURL"), str): response["redirectURL"] = minimizer.url(response["redirectURL"]) - for header in response.get("headers") or []: - if ( - isinstance(header, dict) - and str(header.get("name", "")).lower() == "location" - ): - header["value"] = minimizer.url(header.get("value")) + _minimize_url_headers(response, minimizer) content = response.get("content") if isinstance(content, dict): kept_values += _minimize_har_body( @@ -424,6 +439,18 @@ def _minimize_har_entry(entry: dict[str, Any], minimizer: BodyMinimizer) -> None entry["_tx"] = out +#: Headers whose value is a URL, so a query in it is minimized like one. +_URL_HEADERS = frozenset({"location", "content-location", "referer", "refresh"}) + + +def _minimize_url_headers(side: dict[str, Any], minimizer: BodyMinimizer) -> None: + for header in side.get("headers") or []: + if isinstance(header, dict) and ( + str(header.get("name", "")).lower() in _URL_HEADERS + ): + header["value"] = minimizer.url(header.get("value")) + + def _minimize_har_body( container: dict[str, Any], minimizer: BodyMinimizer, content_type: str ) -> list[Any]: @@ -536,7 +563,27 @@ def minimize_line(line: Mapping[str, Any], minimizer: BodyMinimizer) -> dict[str str(out.get("response_type") or ""), truncated=bool(out.get("response_truncated")), ) - return out + # The capture measured and hashed each body as sent, before decoding, + # redaction or truncation: those, not the redacted text's, describe it. + for key, digest_key in ( + ("body_minimized", DIGEST_REQUEST), + ("response_minimized", DIGEST_RESPONSE), + ): + digest = out.pop(digest_key, None) + if isinstance(out.get(key), dict) and isinstance(digest, Mapping): + out[key] = {**out[key], **digest} + return strip_private(out) + + +#: In-memory keys of a capture line: the size and keyed hash of a body as +#: sent. Never written under these names (:func:`strip_private`). +DIGEST_REQUEST = "_request_digest" +DIGEST_RESPONSE = "_response_digest" + + +def strip_private(line: Mapping[str, Any]) -> dict[str, Any]: + """``line`` without its in-memory-only keys (those starting with ``_``).""" + return {k: v for k, v in line.items() if not str(k).startswith("_")} def parse_multipart( diff --git a/packages/flow/openadapt_flow/network_capture.py b/packages/flow/openadapt_flow/network_capture.py index faba1e26b8..46be13a6b5 100644 --- a/packages/flow/openadapt_flow/network_capture.py +++ b/packages/flow/openadapt_flow/network_capture.py @@ -114,7 +114,7 @@ def __init__( keep_fields: Iterable[str] = (), bodies: str = "minimized", ) -> None: - from openadapt_flow.capture_privacy import BODY_MODES + from openadapt_flow.capture_privacy import BODY_MODES, BodyMinimizer if bodies not in BODY_MODES: raise ValueError(f"bodies must be one of {BODY_MODES}, not {bodies!r}") @@ -124,6 +124,12 @@ def __init__( # whether anything else of a body reaches disk (only "raw", sealed). self._keep_fields = frozenset(keep_fields) - self._secret_names self._bodies = bodies + # One hash key for the whole capture, made now and held only in + # memory, so each body is sized and hashed as sent (raw bytes). + self._minimizer = BodyMinimizer( + {f for f in self._keep_fields if not SECRET_NAME.search(f)}, + withhold=self._secret_names, + ) # Cookie values the browser sent or a response set, and Authorization # values, kept in memory only so they can be withheld wherever a page # echoes one. Never written. @@ -248,17 +254,34 @@ def _on_finished(self, request: Any) -> None: ) if headers.get("location"): line["location"] = headers["location"] - if _TEXT_MIME.search(line["response_type"]): - try: - body = response.body() - except Exception: # noqa: BLE001 - redirect or evicted body - body = b"" - if len(body) > MAX_RESPONSE_BYTES: - line["response_truncated"] = True - body = body[:MAX_RESPONSE_BYTES] - line["response_text"] = body.decode("utf-8", errors="replace") + try: + body = response.body() + except Exception: # noqa: BLE001 - redirect or evicted body + body = b"" + if body: + self._response_body(line, body) self._append(line) + def _response_body(self, line: dict[str, Any], body: bytes) -> None: + """Text, JSON and form responses as text (redacted, then minimized + unless raw); any other or undecodable body as its size and hash.""" + from openadapt_flow.capture_privacy import DIGEST_RESPONSE + + rtype = line["response_type"] + truncated = len(body) > MAX_RESPONSE_BYTES + if truncated: + line["response_truncated"] = True + line[DIGEST_RESPONSE] = self._digest(body) + text = None + if _TEXT_MIME.search(rtype) or rtype == _FORM: + text = _utf8(body[:MAX_RESPONSE_BYTES], cut=truncated) + if text is None: + line["response_minimized"] = self._minimizer.opaque( + body, rtype, truncated=truncated + ) + else: + line["response_text"] = text + def _request_line(self, request: Any) -> dict[str, Any]: try: headers = {k.lower(): v for k, v in request.all_headers().items()} @@ -299,31 +322,50 @@ def _request_line(self, request: Any) -> dict[str, Any]: except Exception: # noqa: BLE001 - binary or unavailable body raw = None if raw: - if len(raw) > MAX_REQUEST_BYTES: - line["request_truncated"] = True - raw = raw[:MAX_REQUEST_BYTES] - text = raw.decode("utf-8", errors="replace") - if content_type == "application/x-www-form-urlencoded": - line["form"] = [ - list(p) for p in up.parse_qsl(text, keep_blank_values=True) - ] - elif content_type.startswith("multipart/"): - parsed = None - if content_type == "multipart/form-data" and not line.get( - "request_truncated" - ): - parsed = parse_multipart(raw, headers.get("content-type") or "") - if parsed is None: - # An attached file, or a body that isn't plain form data. - line["body_omitted"] = "multipart" - else: - line["form"], files = parsed - if files: - line["multipart_files"] = files - else: - line["body"] = text + self._request_body(line, bytes(raw), content_type, headers) return line + def _digest(self, raw: bytes) -> dict[str, Any]: + """Size and keyed hash of a whole body as sent.""" + return {"bytes": len(raw), "hmac": self._minimizer.tag(raw)} + + def _request_body( + self, + line: dict[str, Any], + full: bytes, + content_type: str, + headers: dict[str, str], + ) -> None: + from openadapt_flow.capture_privacy import DIGEST_REQUEST + + truncated = len(full) > MAX_REQUEST_BYTES + if truncated: + line["request_truncated"] = True + raw = full[:MAX_REQUEST_BYTES] + line[DIGEST_REQUEST] = self._digest(full) + text = _utf8(raw, cut=truncated) + parsed = None + if content_type.startswith("multipart/"): + if content_type == "multipart/form-data" and not truncated: + parsed = parse_multipart(raw, headers.get("content-type") or "") + if parsed is None: + # An attached file, or a body that isn't plain form data. + line["body_omitted"] = "multipart" + if text is None or (content_type.startswith("multipart/") and not parsed): + # Binary, or a multipart body with a file: its size and hash as + # sent, nothing of its content. + line["body_minimized"] = self._minimizer.opaque( + full, content_type, truncated=truncated + ) + elif content_type == _FORM: + line["form"] = [list(p) for p in up.parse_qsl(text, keep_blank_values=True)] + elif parsed is not None: + line["form"], files = parsed + if files: + line["multipart_files"] = files + else: + line["body"] = text + def _append(self, line: dict[str, Any]) -> None: with self._lock: line["seq"] = len(self._lines) @@ -353,11 +395,9 @@ def write(self, recording_dir: Path | str, t0_monotonic: float) -> Path: path = Path(recording_dir) / NETWORK_FILE lines = self.lines(t0_monotonic) if self._bodies != cp.RAW: - minimizer = cp.BodyMinimizer( - {f for f in self._keep_fields if not SECRET_NAME.search(f)}, - withhold=self._secret_names, - ) - lines = [cp.minimize_line(line, minimizer) for line in lines] + lines = [cp.minimize_line(line, self._minimizer) for line in lines] + else: + lines = [cp.strip_private(line) for line in lines] header = {"schema": SCHEMA, "exchanges": len(lines), "bodies": self._bodies} text = json.dumps(header) + "\n" text += "".join(json.dumps(line, sort_keys=True) + "\n" for line in lines) @@ -373,6 +413,31 @@ def write(self, recording_dir: Path | str, t0_monotonic: float) -> Path: sealed_set.write_bytes(path, data) return path + def minimize_url(self, url: Any) -> Any: + """``url`` under this capture's policy: undeclared query values + hashed (same key as ``network.jsonl``) unless bodies are raw. For + the recording's ``meta.json`` ``app_url``.""" + from openadapt_flow.capture_privacy import RAW + + return url if self._bodies == RAW else self._minimizer.url(url) + + +_FORM = "application/x-www-form-urlencoded" + + +def _utf8(data: bytes, *, cut: bool = False) -> Optional[str]: + """``data`` as UTF-8 text, or None when it isn't (a binary body). + + ``cut``: the body was truncated, so up to three trailing bytes may be + a character split by the cut, and are dropped. + """ + for drop in range(4 if cut else 1): + try: + return data[: len(data) - drop].decode("utf-8") + except UnicodeDecodeError: + continue + return None + def raw_plaintext_allowed(path: Path | str) -> bool: """Whether raw bodies may go to ``path`` in plaintext: not sealed, and diff --git a/packages/flow/openadapt_flow/recorder.py b/packages/flow/openadapt_flow/recorder.py index caa720d3b8..c6cdbd884e 100644 --- a/packages/flow/openadapt_flow/recorder.py +++ b/packages/flow/openadapt_flow/recorder.py @@ -525,7 +525,11 @@ def finish(self) -> Path: # coordinate space: a framed target's point in one may be # frame-local. "coordinate_space": "page", - "app_url": self._app_url, + "app_url": ( + self._app_url + if self._network_capture is None + else self._network_capture.minimize_url(self._app_url) + ), "params": dict(self._params), "secret_params": sorted(self._withheld_param_names), } diff --git a/packages/flow/openadapt_flow/tx/wire_tap.py b/packages/flow/openadapt_flow/tx/wire_tap.py index f4d87239db..8ce5081075 100644 --- a/packages/flow/openadapt_flow/tx/wire_tap.py +++ b/packages/flow/openadapt_flow/tx/wire_tap.py @@ -688,9 +688,9 @@ def _build_har_entry( } for k, v in request_headers ] - req_mime = ( - _get_header(request_headers, "content-type") or "application/octet-stream" - ) + # "" for a missing header, so it stays apart from an explicit + # octet-stream (whose body capture minimization never parses). + req_mime = _get_header(request_headers, "content-type") or "" req_obj: dict[str, Any] = { "method": method, "url": _mask_if_needed(url, secrets), @@ -721,9 +721,7 @@ def _build_har_entry( } for k, v in response_headers ] - resp_mime = ( - _get_header(response_headers, "content-type") or "application/octet-stream" - ) + resp_mime = _get_header(response_headers, "content-type") or "" resp_text, resp_encoding = _encode_har_body(resp_bytes, response_headers, secrets) content_obj: dict[str, Any] = { "size": len(resp_bytes), @@ -2017,14 +2015,34 @@ def parse_bytes(raw: bytes) -> Any: def _restore_minimized_entry(entry: Mapping[str, Any]) -> dict[str, Any]: - """A minimized entry with each body replaced by its kept JSON fields.""" + """A minimized entry with each body replaced by its kept JSON fields. + + A document marked minimized must be minimized throughout: a body that + carries any text other than its own kept fields, or form ``params``, is + raw data under the marker and the whole document is refused. + """ from openadapt_flow.capture_privacy import HAR_FIELD, restore_kept_json out = json.loads(json.dumps(entry)) for side, key in (("request", "postData"), ("response", "content")): container = (out.get(side) or {}).get(key) - if isinstance(container, dict) and isinstance(container.get(HAR_FIELD), dict): - container["text"] = restore_kept_json(container[HAR_FIELD]).decode("utf-8") + if not isinstance(container, dict): + continue + descriptor = container.get(HAR_FIELD) + kept = ( + restore_kept_json(descriptor).decode("utf-8") + if isinstance(descriptor, dict) + else "" + ) + text = container.get("text") + if (text not in (None, "", kept)) or container.get("params"): + raise ValueError( + "Invalid HAR payload: marked minimized, but an entry's body " + "is not minimized" + ) + container.pop("encoding", None) + if isinstance(descriptor, dict): + container["text"] = kept return out diff --git a/packages/flow/tests/test_capture_privacy.py b/packages/flow/tests/test_capture_privacy.py index 3ef79cfffb..c53533b5e5 100644 --- a/packages/flow/tests/test_capture_privacy.py +++ b/packages/flow/tests/test_capture_privacy.py @@ -595,3 +595,348 @@ def test_raw_network_write_never_falls_back_to_plaintext( nc.require_raw_ready(tmp_path) monkeypatch.setenv(at_rest.OPT_OUT_ENV, "test: synthetic data") nc.require_raw_ready(tmp_path) + + +# -- second review: the four blockers left open after eb95a37dd ------------------ + + +def _capture(**kw: Any) -> tuple[nc.NetworkCapture, Any, Any]: + ctx = _Context() + cap = nc.NetworkCapture(ctx, keep_fields=("note", "id"), **kw).start() + return cap, ctx.handlers["requestfinished"], ctx.handlers["requestfailed"] + + +def _rows(tmp_path: Path) -> list[dict[str, Any]]: + text = (tmp_path / nc.NETWORK_FILE).read_text() + return [json.loads(line) for line in text.splitlines()[1:]] + + +def _multipart(boundary: str, filename: str, payload: bytes) -> bytes: + return ( + ( + f"--{boundary}\r\n" + 'Content-Disposition: form-data; name="note"\r\n\r\nok\r\n' + f"--{boundary}\r\n" + f'Content-Disposition: form-data; name="scan"; filename="{filename}"\r\n' + "Content-Type: application/octet-stream\r\n\r\n" + ).encode() + + payload + + f"\r\n--{boundary}--\r\n".encode() + ) + + +def _opaque_bodies() -> list[tuple[str, bytes, str, bytes, str]]: + """(method, request body, request type, response body, response type).""" + binary = b"\xff\xfe" + PATIENT.encode("utf-16-le") + b"\x00\x81" + MRN.encode() + return [ + ("POST", b"\xff\xfe", "application/octet-stream", b"", "text/html"), + ("POST", binary, "application/octet-stream", b"", "text/html"), + ("GET", b"", "", b"%PDF-1.7\n\xe2\xe3" + DIAGNOSIS.encode(), "application/pdf"), + ( + "POST", + _multipart("bX", "chart.bin", b"\x89" + DOB.encode()), + "multipart/form-data; boundary=bX", + b"", + "text/html", + ), + ] + + +def test_binary_and_file_bodies_are_measured_and_hashed_as_sent( + tmp_path: Path, +) -> None: + """#10: size and hash come from the original bytes; binary responses and + multipart files get a descriptor; nothing of their content is kept.""" + cap, finished, _ = _capture() + for method, body, rtype, resp, resp_type in _opaque_bodies(): + finished( + _Request( + "http://app.test/upload", + method, + body or None, + rtype, + _Response(200, resp_type, resp), + ) + ) + cap.write(tmp_path, t0_monotonic=0.0) + assert _leaks(tmp_path) == [] + rows = _rows(tmp_path) + for row, (_, body, rtype, resp, _) in zip(rows, _opaque_bodies()): + assert not any(k.startswith("_") for k in row) + if body: + desc = row["body_minimized"] + assert desc["format"] == "opaque" + assert desc["bytes"] == len(body) + assert desc["hmac"] == cap._minimizer.tag(body) + assert "body" not in row and "form" not in row + if resp: + desc = row["response_minimized"] + assert desc["format"] == "opaque" + assert desc["bytes"] == len(resp) + assert desc["hmac"] == cap._minimizer.tag(resp) + assert rows[0]["body_minimized"]["bytes"] == 2 # not 6 replacement bytes + assert rows[3]["body_omitted"] == "multipart" + + +def test_text_bodies_report_the_size_and_hash_sent_not_the_redacted_text( + tmp_path: Path, +) -> None: + cap, finished, _ = _capture(secret_names={"pin"}) + body = json.dumps({"note": "ok", "pin": "pin-Quokka", "dx": DIAGNOSIS}).encode() + big = ("x" * nc.MAX_REQUEST_BYTES + DIAGNOSIS).encode() + for payload in (body, big): + finished( + _Request( + "http://app.test/save", + "POST", + payload, + "application/json", + _Response(204, "text/html", b""), + ) + ) + cap.write(tmp_path, t0_monotonic=0.0) + assert _leaks(tmp_path) == [] + assert "Quokka" not in (tmp_path / nc.NETWORK_FILE).read_text() + saved, cut = (row["body_minimized"] for row in _rows(tmp_path)) + assert saved["bytes"] == len(body) and saved["hmac"] == cap._minimizer.tag(body) + assert ["note", "ok"] in saved["kept"] + assert cut["truncated"] and cut["bytes"] == len(big) + assert cut["hmac"] == cap._minimizer.tag(big) + + +def test_url_encoded_responses_are_captured_and_minimized(tmp_path: Path) -> None: + cap, finished, _ = _capture() + finished( + _Request( + "http://app.test/lookup", + "GET", + None, + None, + _Response( + 200, + "application/x-www-form-urlencoded", + f"id=51&dx={quote_plus(DIAGNOSIS)}".encode(), + ), + ) + ) + cap.write(tmp_path, t0_monotonic=0.0) + assert _leaks(tmp_path) == [] + desc = _rows(tmp_path)[0]["response_minimized"] + assert desc["format"] == "form" and ["id", "51"] in desc["kept"] + assert [n for n, _ in desc["withheld"]] == ["dx"] + + +def test_raw_mode_keeps_binary_bodies_out_and_writes_valid_json( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Raw mode has no in-memory keys to trip ``json.dumps`` (an error path + that would lose the capture) and writes binary bodies as descriptors.""" + monkeypatch.setenv(at_rest.OPT_OUT_ENV, "test: synthetic data") + cap, finished, _ = _capture(bodies="raw") + for method, body, rtype, resp, resp_type in _opaque_bodies(): + finished( + _Request( + "http://app.test/u", + method, + body or None, + rtype, + _Response(200, resp_type, resp), + ) + ) + cap.write(tmp_path, t0_monotonic=0.0) + rows = _rows(tmp_path) + assert not any(k.startswith("_") for row in rows for k in row) + assert rows[0]["body_minimized"]["bytes"] == 2 and "body" not in rows[0] + assert rows[2]["response_minimized"]["format"] == "opaque" + assert _leaks(tmp_path) == [] # binary content is never kept, even raw + + +def _recorder_backend() -> Any: + class Backend: + viewport = (320, 200) + + def screenshot(self) -> bytes: + return b"" + + return Backend() + + +def test_recording_meta_app_url_query_is_minimized(tmp_path: Path) -> None: + """#6: the starting URL in meta.json gets the capture's query policy, so + no plaintext copy of an undeclared query value sits beside network.jsonl.""" + from openadapt_flow.recorder import Recorder + + cap, finished, _ = _capture() + url = f"http://app.test/search?q={quote_plus(PATIENT)}&id=51#/r?dob={DOB}" + rec = Recorder( + _recorder_backend(), tmp_path / "rec", app_url=url, network_capture=cap + ) + finished(_Request(url, "GET", None, None, _Response(200, "text/html", b""))) + out = rec.finish() + assert _leaks(out) == [] + meta = json.loads((out / "meta.json").read_text()) + assert "id=51" in meta["app_url"] + assert meta["app_url"] == _rows(out)[0]["url"] # same key as network.jsonl + assert urlsplit_host(meta["app_url"]) == "app.test" + plain = Recorder(_recorder_backend(), tmp_path / "plain", app_url=url).finish() + assert json.loads((plain / "meta.json").read_text())["app_url"] == url + + +def urlsplit_host(url: str) -> str: + from urllib.parse import urlsplit + + return urlsplit(url).hostname or "" + + +def test_explicit_octet_stream_json_is_opaque_and_unlabelled_json_parses( + tmp_path: Path, +) -> None: + """#4: JSON is parsed only when labelled JSON or with no type at all; the + wire tap records a missing header as "" so the two stay apart.""" + m = cp.BodyMinimizer(("id",)) + body = json.dumps({"id": PATIENT}).encode() + out = m.body(body, "application/octet-stream") + assert out is not None and out["format"] == "opaque" + assert PATIENT not in json.dumps(out) + unlabelled = m.body(json.dumps({"id": "51"}).encode(), "") + assert unlabelled is not None and ["id", "51"] in unlabelled["kept"] + + from openadapt_flow.tx.wire_tap import WirePolicy + + tap = SessionWireTap("http://app.test", policy=WirePolicy(max_mutations=None)) + tap.record_exchange( + method="POST", + url="http://app.test/api/a", + request_body=json.dumps({"id": MRN}).encode(), + response_status=201, + response_body=json.dumps({"id": PATIENT}).encode(), + request_headers={"Content-Type": "application/octet-stream"}, + response_headers={"Content-Type": "application/octet-stream"}, + ) + tap.record_exchange( + method="POST", + url="http://app.test/api/b", + request_body=b'{"note": "x"}', + response_status=201, + response_body=b'{"id": "52"}', + ) + path = tap.save_har(tmp_path / "s.har") + assert _leaks(tmp_path) == [] + entries = load_har(path)["log"]["entries"] + assert entries[0]["response"]["content"][cp.HAR_FIELD]["format"] == "opaque" + assert entries[1]["response"]["content"]["mimeType"] == "" + replay = SessionWireTap.from_har(path, policy=WirePolicy(max_mutations=None)) + ids = [m.extracted_entity_id for m in replay.summary().mutations] + assert ids == [None, "52"] # live read "PATIENT" from the octet-stream body + + +def test_marked_har_with_a_raw_body_is_refused_on_load(tmp_path: Path) -> None: + """#2: a document marked minimized must be minimized in every entry.""" + good = load_har(dump_har(_tap())) + assert load_har(load_har(good)) == load_har(good) # a reload still loads + raw_entry = json.loads(json.dumps(_tap().export_har()))["log"]["entries"][0] + + def doctored(change: Any) -> dict[str, Any]: + doc = json.loads(dump_har(_tap())) + change(doc["log"]["entries"]) + return doc + + cases = [ + lambda e: e.append(raw_entry), # an entry with no descriptor + lambda e: e[0]["request"]["postData"].update(text=json.dumps({"n": PATIENT})), + lambda e: e[1]["response"]["content"].update( + text=base64.b64encode(PATIENT.encode()).decode(), encoding="base64" + ), + lambda e: e[0]["request"]["postData"].update( + params=[{"name": "dx", "value": DIAGNOSIS}] + ), + ] + for change in cases: + doc = doctored(change) + for source in (doc, json.dumps(doc), json.dumps(doc).encode()): + with pytest.raises(ValueError) as err: + load_har(source) + assert not any(v in str(err.value) for v in PHI) + with pytest.raises(ValueError): + SessionWireTap.from_har(source) + + +def test_url_valued_har_headers_are_minimized(tmp_path: Path) -> None: + tap = SessionWireTap("http://app.test") + search = f"http://app.test/s?q={quote_plus(PATIENT)}" + tap.record_exchange( + method="GET", + url="http://app.test/chart", + request_headers={"Referer": search}, + response_status=200, + response_headers={"Content-Location": search, "Refresh": f"0; url={search}"}, + response_body=b"", + ) + tap.save_har(tmp_path / "s.har") + assert _leaks(tmp_path) == [] + + +def test_no_phi_reaches_disk_on_error_and_debug_paths( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Every capture path, with DEBUG logging to a file in the scanned tree: + failed requests, refused raw writes, refused loads and raw exports.""" + import logging + + monkeypatch.delenv(at_rest.OPT_OUT_ENV, raising=False) + handler = logging.FileHandler(tmp_path / "debug.log") + root = logging.getLogger() + old_level = root.level + root.addHandler(handler) + root.setLevel(logging.DEBUG) + try: + cap, finished, failed = _capture() + failed( + _Request( + f"http://app.test/s?q={quote_plus(PATIENT)}", + "POST", + json.dumps({"dx": DIAGNOSIS, "mrn": MRN}).encode(), + "application/json", + None, + ) + ) + for method, body, rtype, resp, resp_type in _opaque_bodies(): + finished( + _Request( + "http://app.test/u", + method, + body or None, + rtype, + _Response(200, resp_type, resp), + ) + ) + (tmp_path / "rec").mkdir() + cap.write(tmp_path / "rec", t0_monotonic=0.0) + raw_cap, raw_finished, _ = _capture(bodies="raw") + raw_finished( + _Request( + "http://app.test/x", + "POST", + DOB.encode(), + "text/plain", + _Response(200, "text/plain", PATIENT.encode()), + ) + ) + (tmp_path / "raw").mkdir() + with pytest.raises(at_rest.AtRestRefused) as refused: + raw_cap.write(tmp_path / "raw", t0_monotonic=0.0) + assert not any(v in str(refused.value) for v in PHI) + with pytest.raises(ValueError): + dump_har(_tap(), raw_bodies=True) + _tap().save_har(tmp_path / "s.har") + doc = json.loads(dump_har(_tap())) + doc["log"]["entries"][0]["request"]["postData"]["text"] = PATIENT + with pytest.raises(ValueError): + load_har(doc) + dump_har(_tap(), tmp_path / "again.har") + finally: + root.removeHandler(handler) + root.setLevel(old_level) + handler.close() + assert not (tmp_path / "raw" / nc.NETWORK_FILE).exists() + assert _leaks(tmp_path) == [] diff --git a/packages/flow/tests/test_tx_har_redaction.py b/packages/flow/tests/test_tx_har_redaction.py index 8ab154f117..31a2c68d77 100644 --- a/packages/flow/tests/test_tx_har_redaction.py +++ b/packages/flow/tests/test_tx_har_redaction.py @@ -145,6 +145,11 @@ def test_nonsecret_text_and_binary_remain_usable(): assert kind == "base64" assert base64.b64decode(encoded, validate=True) == body entry = _entry(SECRETS[0], b'{"id":"17","status":"saved"}') + # Explicit octet-stream is opaque once minimized; labelled JSON keeps id. + opaque = load_har(dump_har({"log": {"entries": [entry]}}))["log"]["entries"][0] + assert opaque["response"]["status"] == 200 + assert opaque["response"]["content"]["text"] == "" + entry["response"]["content"]["mimeType"] = "application/json" out = load_har(dump_har({"log": {"entries": [entry]}})) record = out["log"]["entries"][0] assert record["response"]["status"] == 200 From 3fbfeb2ea2427eb79937d06106b786d69504c8aa Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 19:54:14 -0500 Subject: [PATCH 7/9] test(flow): support default-at-rest v3 sealed sets in capture privacy and raw-body tests --- .../flow/tests/test_api_footprint_browser.py | 5 +++++ .../flow/tests/test_api_shape_boundaries.py | 5 +++++ packages/flow/tests/test_api_tier_web_form.py | 3 ++- packages/flow/tests/test_capture_privacy.py | 22 +++++++++++++++---- .../tests/test_network_capture_live_django.py | 5 ++++- .../tests/test_network_capture_redact_json.py | 6 +++-- 6 files changed, 38 insertions(+), 8 deletions(-) diff --git a/packages/flow/tests/test_api_footprint_browser.py b/packages/flow/tests/test_api_footprint_browser.py index 8a9171ef5c..9950659ef2 100644 --- a/packages/flow/tests/test_api_footprint_browser.py +++ b/packages/flow/tests/test_api_footprint_browser.py @@ -185,6 +185,11 @@ def gui_save(page, title): page.wait_for_load_state("networkidle") +@pytest.fixture(autouse=True) +def _allow_raw_capture_plaintext(monkeypatch): + monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "synthetic test fixture") + + def capture_save(app, context, page, tmp_path): rec = tmp_path / "capture" rec.mkdir() diff --git a/packages/flow/tests/test_api_shape_boundaries.py b/packages/flow/tests/test_api_shape_boundaries.py index 9aa84e8c88..3bfb50a36b 100644 --- a/packages/flow/tests/test_api_shape_boundaries.py +++ b/packages/flow/tests/test_api_shape_boundaries.py @@ -195,6 +195,11 @@ def site_page(browser): site.close() +@pytest.fixture(autouse=True) +def _allow_raw_capture_plaintext(monkeypatch): + monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "synthetic test fixture") + + def binding_from_browser(tmp_path: Path, site: Site, page: Any): """Capture the real normal submit, then propose and test-admit its binding.""" recording = tmp_path / "recording" diff --git a/packages/flow/tests/test_api_tier_web_form.py b/packages/flow/tests/test_api_tier_web_form.py index d991074180..07286b63e9 100644 --- a/packages/flow/tests/test_api_tier_web_form.py +++ b/packages/flow/tests/test_api_tier_web_form.py @@ -160,7 +160,8 @@ def remove_listener(self, event, handler): self.handlers.pop(event, None) -def test_capture_writes_and_loads_without_static_assets(tmp_path): +def test_capture_writes_and_loads_without_static_assets(tmp_path, monkeypatch): + monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "synthetic test fixture") ctx = _FakeContext() cap = nc.NetworkCapture(ctx, bodies="raw").start() ctx.handlers["requestfinished"](_FakeRequest("http://app/form")) diff --git a/packages/flow/tests/test_capture_privacy.py b/packages/flow/tests/test_capture_privacy.py index c53533b5e5..137eef88f1 100644 --- a/packages/flow/tests/test_capture_privacy.py +++ b/packages/flow/tests/test_capture_privacy.py @@ -88,9 +88,19 @@ def _decoded(data: bytes) -> list[bytes]: def _leaks(root: Path, values: tuple[str, ...] = PHI) -> list[tuple[str, str]]: + from openadapt_flow import sealed_set + found = [] for path in sorted(p for p in root.rglob("*") if p.is_file()): - blobs = _decoded(_plain(path.read_bytes())) + if ( + sealed_set.is_sealed_path(path) + and path.name != sealed_set.HEADER + and path.name.endswith(".enc") + ): + raw = sealed_set.read_bytes(path.with_name(path.name[:-4])) + else: + raw = path.read_bytes() + blobs = _decoded(_plain(raw)) for value in values: if any(form in blob for blob in blobs for form in _forms(value)): found.append((str(path.relative_to(root)), value)) @@ -607,7 +617,9 @@ def _capture(**kw: Any) -> tuple[nc.NetworkCapture, Any, Any]: def _rows(tmp_path: Path) -> list[dict[str, Any]]: - text = (tmp_path / nc.NETWORK_FILE).read_text() + from openadapt_flow import sealed_set + + text = sealed_set.read_text(tmp_path / nc.NETWORK_FILE) return [json.loads(line) for line in text.splitlines()[1:]] @@ -774,12 +786,14 @@ def test_recording_meta_app_url_query_is_minimized(tmp_path: Path) -> None: finished(_Request(url, "GET", None, None, _Response(200, "text/html", b""))) out = rec.finish() assert _leaks(out) == [] - meta = json.loads((out / "meta.json").read_text()) + from openadapt_flow import sealed_set + + meta = json.loads(sealed_set.read_text(out / "meta.json")) assert "id=51" in meta["app_url"] assert meta["app_url"] == _rows(out)[0]["url"] # same key as network.jsonl assert urlsplit_host(meta["app_url"]) == "app.test" plain = Recorder(_recorder_backend(), tmp_path / "plain", app_url=url).finish() - assert json.loads((plain / "meta.json").read_text())["app_url"] == url + assert json.loads(sealed_set.read_text(plain / "meta.json"))["app_url"] == url def urlsplit_host(url: str) -> str: diff --git a/packages/flow/tests/test_network_capture_live_django.py b/packages/flow/tests/test_network_capture_live_django.py index f696ed3f5d..e5f96bbee6 100644 --- a/packages/flow/tests/test_network_capture_live_django.py +++ b/packages/flow/tests/test_network_capture_live_django.py @@ -124,7 +124,10 @@ def django_admin(tmp_path: Path): proc.kill() -def test_a_django_admin_recording_keeps_no_rendered_token(django_admin, tmp_path): +def test_a_django_admin_recording_keeps_no_rendered_token( + django_admin, tmp_path, monkeypatch +): + monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "synthetic test fixture") sync_api = pytest.importorskip("playwright.sync_api") base, password = django_admin with sync_api.sync_playwright() as pw: diff --git a/packages/flow/tests/test_network_capture_redact_json.py b/packages/flow/tests/test_network_capture_redact_json.py index 974ef22a2c..69399f3ebb 100644 --- a/packages/flow/tests/test_network_capture_redact_json.py +++ b/packages/flow/tests/test_network_capture_redact_json.py @@ -119,7 +119,8 @@ def _capture(tmp_path): return (tmp_path / nc.NETWORK_FILE).read_text() -def test_no_password_or_token_from_a_json_login_survives(tmp_path): +def test_no_password_or_token_from_a_json_login_survives(tmp_path, monkeypatch): + monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "synthetic test fixture") text = _capture(tmp_path) for leaked in (PASSWORD, ACCESS, REFRESH, SET_COOKIE, BEARER): assert leaked not in text, leaked @@ -134,7 +135,8 @@ def test_no_password_or_token_from_a_json_login_survives(tmp_path): assert "" in rows[2]["body"] -def test_a_short_json_secret_is_withheld_by_its_field_name(tmp_path): +def test_a_short_json_secret_is_withheld_by_its_field_name(tmp_path, monkeypatch): + monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "synthetic test fixture") _capture(tmp_path) echo = json.loads(nc.load(tmp_path)[2]["body"]) assert echo["secret"] == nc.SECRET From 0f65a6cc46ded2a5dc09b3ecedf4580e356637d0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 00:34:45 -0500 Subject: [PATCH 8/9] chore(flow): simplify _utf8 trailing-byte slice to satisfy verdict fold check --- packages/flow/openadapt_flow/network_capture.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/network_capture.py b/packages/flow/openadapt_flow/network_capture.py index 46be13a6b5..11dec811fd 100644 --- a/packages/flow/openadapt_flow/network_capture.py +++ b/packages/flow/openadapt_flow/network_capture.py @@ -432,8 +432,9 @@ def _utf8(data: bytes, *, cut: bool = False) -> Optional[str]: a character split by the cut, and are dropped. """ for drop in range(4 if cut else 1): + trimmed = data[:-drop] if drop else data try: - return data[: len(data) - drop].decode("utf-8") + return trimmed.decode("utf-8") except UnicodeDecodeError: continue return None From a78ea31ecc75059e92ed0689859d888ecc2f7986 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 01:18:55 -0500 Subject: [PATCH 9/9] test(flow): allow synthetic plaintext fixture in test_api_capture_refusals --- packages/flow/tests/test_api_capture_refusals.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/flow/tests/test_api_capture_refusals.py b/packages/flow/tests/test_api_capture_refusals.py index 14c33c1778..905c20a04d 100644 --- a/packages/flow/tests/test_api_capture_refusals.py +++ b/packages/flow/tests/test_api_capture_refusals.py @@ -12,6 +12,11 @@ from tests.test_api_shape_boundaries import site_page as site_page +@pytest.fixture(autouse=True) +def _allow_raw_capture_plaintext(monkeypatch): + monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "synthetic test fixture") + + def _observe_admission(monkeypatch): calls = [] original = boundaries.admit_api_step