diff --git a/capabilities/08-the-fastest-layer-the-app-allows/0035-keep-captured-bodies-off-disk-network-jsonl-and.md b/capabilities/08-the-fastest-layer-the-app-allows/0035-keep-captured-bodies-off-disk-network-jsonl-and.md new file mode 100644 index 0000000000..844a7670e0 --- /dev/null +++ b/capabilities/08-the-fastest-layer-the-app-allows/0035-keep-captured-bodies-off-disk-network-jsonl-and.md @@ -0,0 +1 @@ +| 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) | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index cf239e23c3..678590b8ab 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -127,6 +127,22 @@ application vocabulary: month names, yes and no words, currency signs and tables come from the pack. See docs/EFFECT_LOCATION.md. +### 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 or + `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. ### Fixes - `verify-run`: an effect list that is empty, or tiers that don't pair one to diff --git a/packages/flow/benchmark/api_generalization/harness.py b/packages/flow/benchmark/api_generalization/harness.py index d9a0e5725d..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: @@ -143,7 +145,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..46e7368a2a 100644 --- a/packages/flow/benchmark/openemr_api_tier/feature_e2e.py +++ b/packages/flow/benchmark/openemr_api_tier/feature_e2e.py @@ -64,19 +64,26 @@ 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) 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..536bc8c4c4 100644 --- a/packages/flow/benchmark/undo_proposal/run.py +++ b/packages/flow/benchmark/undo_proposal/run.py @@ -105,15 +105,20 @@ 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]] = [] 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..5ed1112aa8 100644 --- a/packages/flow/benchmark/zero_config_verify/run.py +++ b/packages/flow/benchmark/zero_config_verify/run.py @@ -88,10 +88,15 @@ 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).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..670310a685 100644 --- a/packages/flow/docs/API_TIER.md +++ b/packages/flow/docs/API_TIER.md @@ -35,16 +35,22 @@ 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/ +# 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/ 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..0965543d6a 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,55 @@ 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 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 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`). 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 +with `--capture-network-bodies raw` for those and for debugging. Raw is +refused unless the recording is encrypted (set `OPENADAPT_RECORDING_KEY` or +`OPENADAPT_BUNDLE_KEY`, or use `OPENADAPT_FLOW_AT_REST=strict`; never with +`--no-encrypt`) or `OPENADAPT_FLOW_PLAINTEXT_AT_REST` explicitly allows +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 Nothing below reaches the disk. Values are held in memory during the @@ -83,9 +136,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 66a046e9be..6f6531ac33 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -1532,6 +1532,7 @@ def _cmd_record_capture(args: argparse.Namespace) -> int: BrowserAttachError, record_interactive, ) + from openadapt_flow.network_capture import cli_mode try: out = record_interactive( @@ -1545,7 +1546,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)), + capture_network=cli_mode(args, recording_key), encryption_key=recording_key, ) except BrowserAttachError as exc: @@ -9583,16 +9584,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). compile then proposes an " - "API step for a save it can repeat as one request; a person admits " - "it with 'api admit'" - ), - ) + 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/capture_privacy.py b/packages/flow/openadapt_flow/capture_privacy.py new file mode 100644 index 0000000000..ec8bce1750 --- /dev/null +++ b/packages/flow/openadapt_flow/capture_privacy.py @@ -0,0 +1,643 @@ +"""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. JSON is parsed only from + 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"). + +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, +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. +""" + +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 = ("{", "[") +#: 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 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, + 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 + 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: + # 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}" + + 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 + 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) + + # -- 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 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]]]: + 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": + parsed = parse_multipart(data, full_type) + if parsed is None: + return None + fields, _files = parsed + return "form", self.pairs(fields) + # 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) + 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. + + 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) + 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 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 = 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: + """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"" + holder: dict[str, Any] = {} + for item in minimized.get("kept") or []: + if not isinstance(item, list) or len(item) != 2: + continue + 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: + 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`` (or ``params``) and response ``content.text`` + become empty and the minimized description goes in + ``_openadapt_minimized`` beside them. Request URLs, ``queryString`` + 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 + 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 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, + ) + ] + _minimize_url_headers(request, minimizer) + 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"]) + _minimize_url_headers(response, minimizer) + 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) + ) + 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]: + """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"] = "" + if isinstance(params, list): + container["params"] = [] + 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) + 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: + 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: + 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"), + 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")), + ) + # 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( + 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/interactive_recorder.py b/packages/flow/openadapt_flow/interactive_recorder.py index 1526126082..e27206b167 100644 --- a/packages/flow/openadapt_flow/interactive_recorder.py +++ b/packages/flow/openadapt_flow/interactive_recorder.py @@ -2333,7 +2333,7 @@ def __init__( ] = None, stop_when: Optional[Callable[[], bool]] = None, surface: str = "web", - capture_network: bool = False, + capture_network: bool | str = False, encryption_key: Optional[str] | object = POLICY, event_clock: Optional[list[float]] = None, ) -> None: @@ -2347,7 +2347,7 @@ 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 self._network = None self._out_dir = Path(out_dir) @@ -2516,10 +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 + # 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 f36791ddbe..11dec811fd 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 @@ -47,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" @@ -100,9 +106,30 @@ 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, BodyMinimizer + + 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 + # 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. @@ -116,6 +143,23 @@ def __init__(self, context: Any, *, secret_names: Iterable[str] = ()) -> None: # 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) @@ -210,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()} @@ -261,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) @@ -309,72 +389,163 @@ 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: + 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) + 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 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 -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. + return url if self._bodies == RAW else self._minimizer.url(url) - 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 +_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): + trimmed = data[:-drop] if drop else data try: - head_lines = head.decode("utf-8").split("\r\n") - text = value.decode("utf-8") + return trimmed.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 + return None + + +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 sealed_set + + if sealed_set.is_sealed_path(recording_dir) or raw_plaintext_allowed(recording_dir): + return + 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)", + ) + ) + + +_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: 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) + + +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 _frame_url(request: Any) -> Optional[str]: diff --git a/packages/flow/openadapt_flow/recorder.py b/packages/flow/openadapt_flow/recorder.py index 2f4f19f97e..d39c171b02 100644 --- a/packages/flow/openadapt_flow/recorder.py +++ b/packages/flow/openadapt_flow/recorder.py @@ -583,7 +583,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/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index 8d54c80163..e515f3732a 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -1549,10 +1549,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 06327fb679..17efd72682 100644 --- a/packages/flow/openadapt_flow/tx/wire_tap.py +++ b/packages/flow/openadapt_flow/tx/wire_tap.py @@ -819,9 +819,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), @@ -852,9 +852,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), @@ -1231,17 +1229,20 @@ 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( 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): @@ -1302,6 +1303,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() @@ -1438,6 +1440,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() @@ -1462,6 +1465,7 @@ def _begin_request( ) ): is_mut = False + 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) @@ -1864,8 +1868,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( @@ -1873,6 +1882,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( @@ -2039,8 +2049,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 and needs ``path``; a file is always sealed under the at-rest 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 + raw_har: Mapping[str, Any] = ( har_or_tap.export_har() if isinstance(har_or_tap, SessionWireTap) @@ -2048,11 +2069,29 @@ def dump_har( ) secret_tuple = tuple(s for s in secrets if s) scrubbed = _scrub_har_value(dict(raw_har), secret_tuple) + 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) + else WirePolicy() + ) + fields = ( + (*policy.id_fields, *policy.version_fields) + if keep_fields is None + else tuple(keep_fields) + ) + scrubbed = minimize_har(scrubbed, BodyMinimizer(fields)) payload = json.dumps(scrubbed, indent=2, sort_keys=False) 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( @@ -2106,10 +2145,51 @@ 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. + + 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 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 + + def har_to_summary( source: str | Path | bytes | Mapping[str, Any], *, diff --git a/packages/flow/tests/fixtures/cli_surface.json b/packages/flow/tests/fixtures/cli_surface.json index e47752224c..472eb517c2 100644 --- a/packages/flow/tests/fixtures/cli_surface.json +++ b/packages/flow/tests/fixtures/cli_surface.json @@ -216,7 +216,7 @@ "openadapt-flow receipt keys export": "usage: openadapt-flow receipt keys export [-h] dir\n\npositional arguments:\n dir\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow verify receipt keys export\n", "openadapt-flow receipt verify": "usage: openadapt-flow receipt verify [-h] --issuer-key ISSUER_KEY [--log-key LOG_KEY] [--no-log]\n [--evidence EVIDENCE] [--require-anchor] [--json]\n file\n\npositional arguments:\n file a .receipt.cbor file\n\noptions:\n -h, --help show this help message and exit\n --issuer-key ISSUER_KEY\n the issuer's public key (PEM or key entry)\n --log-key LOG_KEY the transparency log's public key (PEM)\n --no-log skip the log inclusion check (the output says so)\n --evidence EVIDENCE the private evidence file, to check the commitment opens\n --require-anchor also require a Rekor anchor (FILE.anchor.json), checked offline\n --json print the result as JSON\n\nAlso available as: openadapt-flow verify receipt verify\n", "openadapt-flow reconcile": "usage: openadapt-flow reconcile [-h] --spec SPEC [--param NAME=VALUE] [--worklist WORKLIST]\n [--now NOW] [--out OUT]\n\noptions:\n -h, --help show this help message and exit\n --spec SPEC an openadapt.reconcile/v1 YAML\n --param NAME=VALUE the unit's identity (repeatable)\n --worklist WORKLIST JSON Lines: one unit's parameters per line\n --now NOW judge due times at this ISO 8601 time\n --out OUT write the JSON reply here too\n\nAlso available as: openadapt-flow verify reconcile\n", - "openadapt-flow record": "usage: openadapt-flow record [-h] [--url URL] [--browser-cdp-endpoint URL]\n [--browser-page-url URL] --out OUT [--secret FIELD] [--param FIELD]\n [--identifier FIELD|X,Y,W,H] [--task TASK] [--until-cmd CMD]\n [--window OWNER] [--window-title SUBSTRING] [--headless]\n [--profile {demo,standard,regulated}] [--no-encrypt]\n [--capture-network] [--with-check] [--verify [VERIFY_YAML]]\n [--surface NAME=KIND:WINDOW] [--yes]\n [--backend {web,windows,macos,linux,rdp,citrix}] [--agent-url URL]\n [--macos-app APP] [--macos-window-title TITLE] [--linux-app APP]\n [--linux-window-title TITLE] [--linux-allow-physical-input]\n [--rdp-host HOST] [--rdp-window OWNER] [--rdp-window-title TITLE]\n [--rdp-readiness-text TEXT] [--allow-surface-override]\n\noptions:\n -h, --help show this help message and exit\n --url URL URL of the app to record against (required for --backend web)\n --browser-cdp-endpoint URL\n Attach the web recorder to an already-running local Chromium browser\n through its loopback DevTools endpoint (for example,\n http://127.0.0.1:9222). The recorder selects a tab on the --url origin and\n does not launch, navigate, or close the browser.\n --browser-page-url URL\n Exact current URL of the existing tab to record. Use this with --browser-\n cdp-endpoint when more than one open tab has the --url origin.\n --out OUT Recording output directory\n --secret FIELD Mark a typed field (by name or id) as a SECRET; its value is never\n persisted and is injected at replay from OPENADAPT_FLOW_SECRET_.\n input[type=password] is always treated as secret. Repeatable.\n --param FIELD Record a typed value as a PARAMETER; its demonstrated value becomes the\n default, overridable at replay with --param. For --backend web, FIELD is\n the field name/id. For --backend windows/macos/linux/rdp/citrix (capture\n has no field identity), use NAME=VALUE \u2014 the typed value equal to VALUE is\n marked as parameter NAME. Repeatable.\n --identifier FIELD|X,Y,W,H\n Mark the RECORD-IDENTIFYING region (patient banner / MRN field) so the\n compiler crops its pixels (anchor.identifier_crop) and the pixel-compare\n identity tier arms on remote-display/pixel replays (Citrix/RDP). For\n --backend web, FIELD is the field name/id (repeatable; the first marked\n field present at each click contributes its rect). For --backend\n windows/macos/linux/rdp/citrix (a pixel capture has no field identity),\n give the region once as X,Y,W,H in recording pixels. Unmarked recordings\n still get automatic crops on identity-armed pixel steps (from the OCR\n identity band).\n --task TASK Task description for a desktop (--backend windows/macos/linux/rdp/citrix)\n capture session (stored in the recording metadata).\n --until-cmd CMD Run CMD on an interval while recording. Exit 0 stops the record. The\n command is not captured as clicks. Ctrl-C still stops. A non-zero exit\n keeps recording (probe failure is not done).\n --window OWNER Scope a desktop capture (--backend windows/macos/linux/rdp/citrix) to ONE\n window, recorded in that window's OWN pixel space (owner-app substring,\n e.g. --window Parallels / --window 'Citrix Workspace'). Closes the\n coordinate-space gap with the pixel (rdp) replay surface. Combine with\n --window-title to disambiguate. Supported on macOS and Windows hosts;\n refused elsewhere. Ignored (rejected) for --backend web.\n --window-title SUBSTRING\n Title substring to disambiguate the --window target when the owner app has\n multiple windows (case-insensitive; may be used with or without --window).\n The resolved title is stored in the LOCAL recording metadata only.\n --headless Run the browser headless (scripted/CI recording)\n --profile {demo,standard,regulated}\n Recording posture (Section 5). standard/regulated REQUIRE an explicit\n --backend (no implicit browser default in production). demo may omit\n --backend: it defaults to capture on this OS (macos/windows/linux), or to\n the browser when --url is given, and prints a visible notice. Omitted: the\n same permissive pre-profile default.\n --no-encrypt Write a web recording in plaintext (recorded in ~/.openadapt/plaintext-at-\n rest.jsonl). Web recordings are encrypted by default, under the configured\n key or a local one; refused under OPENADAPT_FLOW_AT_REST=strict\n --capture-network Web only: also keep the page's requests (network.jsonl; cookies, passwords\n and session tokens withheld). compile then proposes an API step for a save\n it can repeat as one request; a person admits it with 'api admit'\n --with-check After the save, also show how you'd check it saved (reload or search\n again, open the record). Flow then asks which fields show the values you\n typed and writes check.json\n --verify [VERIFY_YAML]\n Read the system of record through the verifier: section of this file\n (rest, sql, fhir, graphql or file) before and after the recording, and\n propose the checks for what changed in verify.proposed.yaml. Both reads go\n to sor_snapshots.json (mode 0600). With no file, look the record up after\n you save: that look-up becomes the proposed check\n --surface NAME=KIND:WINDOW\n With no --backend or --url, record follows you across windows on its own.\n Use --surface to name the windows yourself instead, or --surface auto with\n --url to add automatic windows to a browser recording. Declare each\n desktop or remote window the person works in (repeatable). KIND is\n windows, macos, linux, rdp or citrix; WINDOW is part of that window's\n title (on macOS, the app name). Repeat a NAME to add another window to it,\n such as its dialog. With --url the browser leads; otherwise the first\n --surface does. Each change of window becomes a checked switch step. An\n action in a window you did not declare stops the recording. See\n docs/MULTI_SURFACE.md.\n --yes Keep a cross-window recording's surfaces without asking. Without a\n terminal and without --yes, the recording is kept unconfirmed and compile\n refuses it until confirm-surfaces is run.\n --backend {web,windows,macos,linux,rdp,citrix}\n Backend to drive: 'web' (Playwright/Chromium), 'windows' (native Windows\n via the WAA HTTP agent at replay), 'macos' (one native Mac app window),\n 'linux' (one exact AT-SPI app window at replay), 'rdp' (pixel-only network\n or local remote desktop), or 'citrix' (the local Citrix Workspace window;\n its owner defaults by host OS and a configured rdp_window may override\n it). Overrides backend.kind from --config. Omit on record to capture on\n this OS, or pass --url to record the browser.\n --agent-url URL Base URL of the in-guest Windows (WAA) agent for --backend windows (e.g.\n http://localhost:5001). Replay/run only: desktop record refuses this flag\n because local Capture cannot bind to a WAA endpoint. Overrides\n backend.agent_url.\n --macos-app APP Owner application for --backend macos (e.g. MyApp). During record this\n scopes Capture to that local app window; during replay/run it overrides\n backend.macos_app.\n --macos-window-title TITLE\n Window-title substring for --backend macos. Ambiguous matches are refused.\n During record this scopes Capture; during replay/run it overrides\n backend.macos_window_title.\n --linux-app APP Exact AT-SPI application name for --backend linux (e.g. gedit). Replay/run\n only: the current Capture path records the local Linux desktop and refuses\n this flag. Overrides backend.linux_app.\n --linux-window-title TITLE\n Exact top-level window title for --backend linux. Zero or multiple matches\n are refused. Replay/run only: the current Capture path records the local\n Linux desktop and refuses this flag. Overrides backend.linux_window_title.\n --linux-allow-physical-input\n Explicitly allow window-bound X11 pointer/keyboard fallback for --backend\n linux replay/run when native AT-SPI actuation is unavailable. Record\n refuses this replay-only flag.\n --rdp-host HOST RDP host/IP for --backend rdp (network RDP via FreeRDP). Overrides\n backend.rdp_host. Replay/run only: record cannot connect local Capture to\n this endpoint. Record inside the remote session, or capture a local client\n with --window/--rdp-window.\n --rdp-window OWNER Exact local remote-display window owner/process for --backend rdp or\n citrix. On Windows this is the process basename (for example wfica32); on\n macOS it is the app owner (for example 'Citrix Viewer'). During record it\n also scopes local Capture to that window; during replay/run it overrides\n backend.rdp_window.\n --rdp-window-title TITLE\n Exact local remote-display window title used to disambiguate multiple\n matching RDP/Citrix client windows. During record it also scopes local\n Capture; during replay/run it overrides backend.rdp_window_title.\n --rdp-readiness-text TEXT\n Stable text that must be visible in the current remote frame before input.\n Required for governed Citrix `run`; overrides backend.rdp_readiness_text.\n --allow-surface-override\n Explicitly permit executing a workflow on a DIFFERENT surface than the one\n it was recorded/qualified on (Workflow.surface). Off by default: a cross-\n surface run is refused. The override is recorded in the run report\n (surface_override) as compatibility evidence; it is never silent.\n\nRelated operations (immediately after the task name): confirm-surfaces, narration, sections\n", + "openadapt-flow record": "usage: openadapt-flow record [-h] [--url URL] [--browser-cdp-endpoint URL]\n [--browser-page-url URL] --out OUT [--secret FIELD] [--param FIELD]\n [--identifier FIELD|X,Y,W,H] [--task TASK] [--until-cmd CMD]\n [--window OWNER] [--window-title SUBSTRING] [--headless]\n [--profile {demo,standard,regulated}] [--no-encrypt]\n [--capture-network] [--capture-network-bodies {minimized,raw}]\n [--with-check] [--verify [VERIFY_YAML]] [--surface NAME=KIND:WINDOW]\n [--yes] [--backend {web,windows,macos,linux,rdp,citrix}]\n [--agent-url URL] [--macos-app APP] [--macos-window-title TITLE]\n [--linux-app APP] [--linux-window-title TITLE]\n [--linux-allow-physical-input] [--rdp-host HOST] [--rdp-window OWNER]\n [--rdp-window-title TITLE] [--rdp-readiness-text TEXT]\n [--allow-surface-override]\n\noptions:\n -h, --help show this help message and exit\n --url URL URL of the app to record against (required for --backend web)\n --browser-cdp-endpoint URL\n Attach the web recorder to an already-running local Chromium browser\n through its loopback DevTools endpoint (for example,\n http://127.0.0.1:9222). The recorder selects a tab on the --url origin and\n does not launch, navigate, or close the browser.\n --browser-page-url URL\n Exact current URL of the existing tab to record. Use this with --browser-\n cdp-endpoint when more than one open tab has the --url origin.\n --out OUT Recording output directory\n --secret FIELD Mark a typed field (by name or id) as a SECRET; its value is never\n persisted and is injected at replay from OPENADAPT_FLOW_SECRET_.\n input[type=password] is always treated as secret. Repeatable.\n --param FIELD Record a typed value as a PARAMETER; its demonstrated value becomes the\n default, overridable at replay with --param. For --backend web, FIELD is\n the field name/id. For --backend windows/macos/linux/rdp/citrix (capture\n has no field identity), use NAME=VALUE \u2014 the typed value equal to VALUE is\n marked as parameter NAME. Repeatable.\n --identifier FIELD|X,Y,W,H\n Mark the RECORD-IDENTIFYING region (patient banner / MRN field) so the\n compiler crops its pixels (anchor.identifier_crop) and the pixel-compare\n identity tier arms on remote-display/pixel replays (Citrix/RDP). For\n --backend web, FIELD is the field name/id (repeatable; the first marked\n field present at each click contributes its rect). For --backend\n windows/macos/linux/rdp/citrix (a pixel capture has no field identity),\n give the region once as X,Y,W,H in recording pixels. Unmarked recordings\n still get automatic crops on identity-armed pixel steps (from the OCR\n identity band).\n --task TASK Task description for a desktop (--backend windows/macos/linux/rdp/citrix)\n capture session (stored in the recording metadata).\n --until-cmd CMD Run CMD on an interval while recording. Exit 0 stops the record. The\n command is not captured as clicks. Ctrl-C still stops. A non-zero exit\n keeps recording (probe failure is not done).\n --window OWNER Scope a desktop capture (--backend windows/macos/linux/rdp/citrix) to ONE\n window, recorded in that window's OWN pixel space (owner-app substring,\n e.g. --window Parallels / --window 'Citrix Workspace'). Closes the\n coordinate-space gap with the pixel (rdp) replay surface. Combine with\n --window-title to disambiguate. Supported on macOS and Windows hosts;\n refused elsewhere. Ignored (rejected) for --backend web.\n --window-title SUBSTRING\n Title substring to disambiguate the --window target when the owner app has\n multiple windows (case-insensitive; may be used with or without --window).\n The resolved title is stored in the LOCAL recording metadata only.\n --headless Run the browser headless (scripted/CI recording)\n --profile {demo,standard,regulated}\n Recording posture (Section 5). standard/regulated REQUIRE an explicit\n --backend (no implicit browser default in production). demo may omit\n --backend: it defaults to capture on this OS (macos/windows/linux), or to\n the browser when --url is given, and prints a visible notice. Omitted: the\n same permissive pre-profile default.\n --no-encrypt Write a web recording in plaintext (recorded in ~/.openadapt/plaintext-at-\n rest.jsonl). Web recordings are encrypted by default, under the configured\n key or a local one; refused under OPENADAPT_FLOW_AT_REST=strict\n --capture-network Web only: also keep the page's requests (network.jsonl; cookies, passwords\n and session tokens withheld; bodies minimized, see --capture-network-\n bodies). With raw bodies, compile proposes an API step for a save it can\n repeat as one request; a person admits it with 'api admit'\n --capture-network-bodies {minimized,raw}\n With --capture-network: 'minimized' (default) keeps only the --param and\n --identifier values of each body and a keyed hash of the rest; 'raw' keeps\n the redacted bodies, which API step proposals and debugging need, and\n requires an encrypted recording\n --with-check After the save, also show how you'd check it saved (reload or search\n again, open the record). Flow then asks which fields show the values you\n typed and writes check.json\n --verify [VERIFY_YAML]\n Read the system of record through the verifier: section of this file\n (rest, sql, fhir, graphql or file) before and after the recording, and\n propose the checks for what changed in verify.proposed.yaml. Both reads go\n to sor_snapshots.json (mode 0600). With no file, look the record up after\n you save: that look-up becomes the proposed check\n --surface NAME=KIND:WINDOW\n With no --backend or --url, record follows you across windows on its own.\n Use --surface to name the windows yourself instead, or --surface auto with\n --url to add automatic windows to a browser recording. Declare each\n desktop or remote window the person works in (repeatable). KIND is\n windows, macos, linux, rdp or citrix; WINDOW is part of that window's\n title (on macOS, the app name). Repeat a NAME to add another window to it,\n such as its dialog. With --url the browser leads; otherwise the first\n --surface does. Each change of window becomes a checked switch step. An\n action in a window you did not declare stops the recording. See\n docs/MULTI_SURFACE.md.\n --yes Keep a cross-window recording's surfaces without asking. Without a\n terminal and without --yes, the recording is kept unconfirmed and compile\n refuses it until confirm-surfaces is run.\n --backend {web,windows,macos,linux,rdp,citrix}\n Backend to drive: 'web' (Playwright/Chromium), 'windows' (native Windows\n via the WAA HTTP agent at replay), 'macos' (one native Mac app window),\n 'linux' (one exact AT-SPI app window at replay), 'rdp' (pixel-only network\n or local remote desktop), or 'citrix' (the local Citrix Workspace window;\n its owner defaults by host OS and a configured rdp_window may override\n it). Overrides backend.kind from --config. Omit on record to capture on\n this OS, or pass --url to record the browser.\n --agent-url URL Base URL of the in-guest Windows (WAA) agent for --backend windows (e.g.\n http://localhost:5001). Replay/run only: desktop record refuses this flag\n because local Capture cannot bind to a WAA endpoint. Overrides\n backend.agent_url.\n --macos-app APP Owner application for --backend macos (e.g. MyApp). During record this\n scopes Capture to that local app window; during replay/run it overrides\n backend.macos_app.\n --macos-window-title TITLE\n Window-title substring for --backend macos. Ambiguous matches are refused.\n During record this scopes Capture; during replay/run it overrides\n backend.macos_window_title.\n --linux-app APP Exact AT-SPI application name for --backend linux (e.g. gedit). Replay/run\n only: the current Capture path records the local Linux desktop and refuses\n this flag. Overrides backend.linux_app.\n --linux-window-title TITLE\n Exact top-level window title for --backend linux. Zero or multiple matches\n are refused. Replay/run only: the current Capture path records the local\n Linux desktop and refuses this flag. Overrides backend.linux_window_title.\n --linux-allow-physical-input\n Explicitly allow window-bound X11 pointer/keyboard fallback for --backend\n linux replay/run when native AT-SPI actuation is unavailable. Record\n refuses this replay-only flag.\n --rdp-host HOST RDP host/IP for --backend rdp (network RDP via FreeRDP). Overrides\n backend.rdp_host. Replay/run only: record cannot connect local Capture to\n this endpoint. Record inside the remote session, or capture a local client\n with --window/--rdp-window.\n --rdp-window OWNER Exact local remote-display window owner/process for --backend rdp or\n citrix. On Windows this is the process basename (for example wfica32); on\n macOS it is the app owner (for example 'Citrix Viewer'). During record it\n also scopes local Capture to that window; during replay/run it overrides\n backend.rdp_window.\n --rdp-window-title TITLE\n Exact local remote-display window title used to disambiguate multiple\n matching RDP/Citrix client windows. During record it also scopes local\n Capture; during replay/run it overrides backend.rdp_window_title.\n --rdp-readiness-text TEXT\n Stable text that must be visible in the current remote frame before input.\n Required for governed Citrix `run`; overrides backend.rdp_readiness_text.\n --allow-surface-override\n Explicitly permit executing a workflow on a DIFFERENT surface than the one\n it was recorded/qualified on (Workflow.surface). Off by default: a cross-\n surface run is refused. The override is recorded in the run report\n (surface_override) as compatibility evidence; it is never silent.\n\nRelated operations (immediately after the task name): confirm-surfaces, narration, sections\n", "openadapt-flow redact-report": "usage: openadapt-flow redact-report [-h] [--policy POLICY] [--json] run_dir\n\npositional arguments:\n run_dir Run directory holding report.json\n\noptions:\n -h, --help show this help message and exit\n --policy POLICY Redaction policy JSON (default OPENADAPT_FLOW_REPORT_REDACTION, else\n $OPENADAPT_HOME/report-redaction.json, else the built-in list)\n --json Print the result as JSON\n\nAlso available as: openadapt-flow inspect redact-report\n", "openadapt-flow repair": "usage: openadapt-flow repair [-h]\n {register,list,show,review,campaign,approve,stage,canary,canary-record,rollback,status,revert,standard-changes,clear-hold}\n ...\n\npositional arguments:\n {register,list,show,review,campaign,approve,stage,canary,canary-record,rollback,status,revert,standard-changes,clear-hold}\n register Register a (prior, proposed) bundle pair as a repair candidate; refuses\n (fail closed) any contract weakening without a new qualification revision\n list List candidates and their lifecycle states\n show Show a candidate's reviewable diff, campaigns, and state\n review Record a human review of the candidate's diff\n campaign Run a campaign against the candidate's evidence frames: 'replay' (healthy\n drift battery must all pass) or 'fault' (ambiguity / wrong-entity / stale-\n target / dialog / verifier-failure frames must all be REFUSED)\n approve HUMAN approval gating promotion; refuses unless the diff was reviewed and\n BOTH campaigns passed. Binds the exact bundle hashes\n stage Copy BOTH bundles into the store by content hash and re-verify them byte-\n exact (prior too, so rollback is always local)\n canary Atomically activate the staged bundle in CANARY mode: a bounded first-N-\n runs window with per-run verification before full active\n canary-record Record one canary run from its run directory; any silent-incorrect or\n verification regression auto-reverts to the prior bundle\n rollback One-command rollback: restore the prior bundle hash as the active pointer\n status Show the atomic active-bundle pointer and its lineage\n revert Undo a repair that applied without a person: the prior bundle is active\n again, and repairs of that step go to a person\n standard-changes List the repairs that applied without a person (the daily digest)\n clear-hold Let repairs of a step apply without a person again after a revert\n\noptions:\n -h, --help show this help message and exit\n", "openadapt-flow repair approve": "usage: openadapt-flow repair approve [-h] [--approved-by APPROVED_BY] [--non-interactive]\n [--store STORE]\n candidate_id\n\npositional arguments:\n candidate_id\n\noptions:\n -h, --help show this help message and exit\n --approved-by APPROVED_BY\n Approver identity recorded on the approval (default: the invoking OS user;\n REQUIRED with --non-interactive)\n --non-interactive Skip the confirmation prompt (automation). Requires an explicit\n --approved-by human identity\n --store STORE Repair store directory (candidates, staged bundles by hash, and the atomic\n ACTIVE.json pointer). Default: repair-store/\n", @@ -19215,7 +19215,7 @@ "choices": null, "default": false, "dest": "capture_network", - "help": "Web only: also keep the page's requests (network.jsonl; cookies, passwords and session tokens withheld). compile then proposes an API step for a save it can repeat as one request; a person admits it with 'api admit'", + "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'", "metavar": null, "nargs": 0, "options": [ @@ -19224,6 +19224,23 @@ "required": false, "type": null }, + { + "action": "_StoreAction", + "choices": [ + "minimized", + "raw" + ], + "default": "minimized", + "dest": "capture_network_bodies", + "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", + "metavar": null, + "nargs": null, + "options": [ + "--capture-network-bodies" + ], + "required": false, + "type": null + }, { "action": "_StoreTrueAction", "choices": null, 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 diff --git a/packages/flow/tests/test_api_footprint_browser.py b/packages/flow/tests/test_api_footprint_browser.py index 3d738e73e9..9950659ef2 100644 --- a/packages/flow/tests/test_api_footprint_browser.py +++ b/packages/flow/tests/test_api_footprint_browser.py @@ -185,10 +185,15 @@ 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() - 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..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" @@ -203,7 +208,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 +354,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, ensure_ascii=False)[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. + + 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): + 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 _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]]: + from openadapt_flow import sealed_set + + found = [] + for path in sorted(p for p in root.rglob("*") if p.is_file()): + 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)) + 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 ------------------------------------------------------------ + + +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_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") + + +# -- 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( + 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: + 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 + + +# -- 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() + # 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: + 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) + + +# -- 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]]: + 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:]] + + +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) == [] + 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(sealed_set.read_text(plain / "meta.json"))["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_network_capture_live_django.py b/packages/flow/tests/test_network_capture_live_django.py index cdc0af307c..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: @@ -134,7 +137,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..69399f3ebb 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"}} @@ -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 diff --git a/packages/flow/tests/test_tx_har_redaction.py b/packages/flow/tests/test_tx_har_redaction.py index 22e66e3388..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 @@ -195,10 +200,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 978709f4ed..20d1a4f6c9 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 @@ -1299,6 +1300,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):