Skip to content
7 changes: 7 additions & 0 deletions packages/flow/docs/LIMITS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1140,6 +1140,13 @@ this computer's device key and, in organization mode, the organization's key
files at rest, not a running session: anyone who can run commands as the
signed-in person can read them, as Flow does.

A network capture keeps only declared fields by default. What reads a
capture (undo proposals, record checks, API steps, readiness import) works
from the kept fields or refuses, naming the withheld field. It never treats
a withheld body as empty. API steps and record checks from the app's reads
need `--capture-network-bodies raw`
([`NETWORK_CAPTURE.md`](NETWORK_CAPTURE.md#bodies-minimized-by-default)).

See [`SANITIZED_ARTIFACTS.md`](SANITIZED_ARTIFACTS.md) for the review and
exact-hash workflow, [`PRIVACY.md`](PRIVACY.md) for the field-level data map,
and [`ENTERPRISE_ARCHITECTURE.md`](ENTERPRISE_ARCHITECTURE.md) for component
Expand Down
29 changes: 26 additions & 3 deletions packages/flow/docs/NETWORK_CAPTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,32 @@ headers (`Location`, `Referer`, `Content-Location`, `Refresh`). A HAR that
is marked minimized but has a body with other text or form `params` is
refused when loaded (`load_har`, `from_har`).

Readers find no body in a minimized file and propose nothing from it: no
API step, no undo proposal, no record check from the app's reads. Record
with `--capture-network-bodies raw` for those and for debugging. Raw is
Readers rebuild what they need from the kept fields, or refuse and say
why; none reads a withheld body as an empty one
(`openadapt_flow/capture_bodies.py`):

- **Undo proposal** finds the save by its kept record fields and reads the
new record's id from the kept response fields (declare it with
`--identifier`). A selector field the capture withheld, a later write it
withheld, or a withheld id refuses the network undo.
- **Record check** (`scaffold-verifier`) matches on the save's kept sent
values and notes the withheld ones. A write it can't read is listed as
not covered, with that reason. It does not build a check from the app's
reads, since a minimized response keeps only declared fields (a page,
nothing). Read discovery (`--probe-reads`) refuses when the capture
withheld any field of a write, since a withheld value would count as
not sent.
- **`--prove`** sends the save's body, so it refuses unless every field was
kept.
- **Reference import** (`readiness import`) compares only fields that were
kept, and refuses when a task field was withheld.
- **API steps** are not proposed: they send every field of the save again,
and a form save also needs the form page.
- **Lens induction from a capture** (`tx.network_bridge`) raises an error.

An opaque or cut body is refused as unreadable. Record with
`--capture-network-bodies raw` for API steps, record checks from reads and
debugging, or declare the fields a reader needs. Raw is
refused unless the recording is encrypted (set `OPENADAPT_RECORDING_KEY` or
`OPENADAPT_BUNDLE_KEY`, or use `OPENADAPT_FLOW_AT_REST=strict`; never with
`--no-encrypt`) or `OPENADAPT_FLOW_PLAINTEXT_AT_REST` explicitly allows
Expand Down
311 changes: 311 additions & 0 deletions packages/flow/openadapt_flow/capture_bodies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,311 @@
"""Read the request and response bodies of a network capture line.

Since captures keep only declared fields (:mod:`openadapt_flow.capture_privacy`),
a ``network.jsonl`` line usually has no ``body``, ``form`` or
``response_text``. It has ``body_minimized``, ``form_minimized`` or
``response_minimized`` instead: the declared (kept) fields with their values,
and every other field as a keyed hash (withheld). A reader that looks only at
``body`` or ``form`` sees nothing in such a capture and must not treat that
as "the request sent nothing".

:func:`request_body` and :func:`response_body` give a reader one view of
either kind of line:

- a raw line (``body``, ``form`` or ``response_text``) is returned as it is;
- a minimized form is rebuilt as its kept ``[name, value]`` pairs, and a
minimized JSON body as a JSON document of its kept fields
(:func:`openadapt_flow.capture_privacy.restore_kept_json`). Withheld values
are absent, never guessed;
- an opaque or cut minimized body kept nothing to read and raises
:class:`BodyUnreadable`;
- a field the reader needs that the capture withheld raises
:class:`FieldsWithheld`, naming the field and the recording flags that keep
it. Session tokens and secrets (:func:`is_withheld_name`) are withheld like
any other field: a reader that needs one is refused.

A rebuilt JSON body is the kept fields only. Empty objects and lists, and the
order of keys, are not kept, so a rebuilt body is fit for finding and matching
a request, not for sending it again as the recorded request (an API step).
"""

from __future__ import annotations

import json
import re
from dataclasses import dataclass, field
from typing import Any, Iterable, Literal, Mapping, Optional, Union

#: ``need=ALL``: every field of the body must have been kept.
ALL = "all"

#: How to keep a field's value in the next recording.
RECORD_HINT = (
"record with each field declared (--param or --identifier), or with "
"--capture-network-bodies raw on a sealed recording"
)

#: Request types whose UTF-8 body a raw capture keeps as text.
_TEXT_REQUEST = re.compile(r"^text/|json|xml|javascript|graphql", re.I)


class CaptureBodyRefused(ValueError):
"""A body the reader can't read from the capture. ``code`` is closed."""

code = "body_refused"

def __init__(self, why: str, fields: Iterable[str] = ()) -> None:
super().__init__(why)
self.why = why
self.fields = tuple(fields)


class BodyUnreadable(CaptureBodyRefused):
"""The capture kept nothing of the body to read (opaque or cut)."""

code = "body_unreadable"


class FieldsWithheld(CaptureBodyRefused):
"""The capture withheld a field the reader needs."""

code = "fields_withheld"


@dataclass(frozen=True)
class CapturedBody:
"""One side of a capture line as a reader sees it.

``kind`` is ``"form"``, ``"json"`` (a minimized JSON body, rebuilt),
``"text"`` (a raw body: the reader parses it) or None (no body).
``form`` holds ``[name, value]`` pairs; ``text`` the body text
(for a minimized JSON body, the rebuilt kept fields). ``withheld`` and
``secrets`` are the full paths the capture withheld; both are empty for a
raw body.
"""

kind: Optional[Literal["form", "json", "text"]]
text: Optional[str] = None
form: Optional[list[list[Any]]] = None
minimized: bool = False
kept: tuple[str, ...] = ()
withheld: tuple[str, ...] = ()
secrets: tuple[str, ...] = field(default=())

@property
def withheld_all(self) -> tuple[str, ...]:
"""Every withheld path, secrets included."""
return self.withheld + self.secrets


def is_withheld_name(name: str) -> bool:
"""A session token or password-like field: never kept.

The same names as ``agent_guard.shadow_hold.is_withheld_name``, read from
the capture's own patterns so core readers don't import the agent guard.
"""
from openadapt_flow.network_capture import SECRET_NAME, TOKEN_NAME

leaf = name.rsplit(".", 1)[-1]
return bool(TOKEN_NAME.search(leaf) or SECRET_NAME.search(leaf))


def _leaf(path: str) -> str:
"""The last named segment of a dotted path (list indices dropped)."""
named = [p for p in str(path).split(".") if p and not p.isdigit()]
return named[-1] if named else str(path)


def withheld_leaves(body: CapturedBody) -> frozenset[str]:
"""The leaf names of every withheld path (secrets included)."""
return frozenset(_leaf(p) for p in body.withheld_all)


def request_body(
line: Mapping[str, Any],
*,
need: Union[None, str, Iterable[str]] = None,
what: str = "request",
) -> CapturedBody:
"""The request body of ``line``, rebuilt from a minimized capture.

``need`` is checked only for a minimized body: :data:`ALL` (every field
but session tokens and secrets), or the full paths (case-exact) the
reader needs. ``what`` names the request in a refusal ("the save").
"""
if "form" in line or "body" in line:
form = line.get("form")
if isinstance(form, list):
return CapturedBody(kind="form", form=[list(p) for p in form])
body = line.get("body")
text = body if isinstance(body, str) else None
return CapturedBody(kind="text" if text is not None else None, text=text)
form_minimized = line.get("form_minimized")
if isinstance(form_minimized, Mapping):
return _rebuild(form_minimized, need, what, form=True)
if "body_minimized" not in line:
return CapturedBody(kind=None)
minimized = line.get("body_minimized")
if minimized is None:
return CapturedBody(kind=None, minimized=True) # an empty body
if not isinstance(minimized, Mapping):
raise BodyUnreadable(f"the capture did not keep {_the(what)}'s body")
return _rebuild(minimized, need, what, form=minimized.get("format") == "form")


def response_body(
line: Mapping[str, Any],
*,
need: Union[None, str, Iterable[str]] = None,
what: str = "response",
) -> CapturedBody:
"""The response body of ``line``, rebuilt from a minimized capture.

As :func:`request_body`. A minimized HTML or text response is always
opaque, so it raises :class:`BodyUnreadable`.
"""
if "response_text" in line:
text = line.get("response_text")
return CapturedBody(
kind="text" if isinstance(text, str) else None,
text=text if isinstance(text, str) else None,
)
minimized = line.get("response_minimized")
if minimized is None:
return CapturedBody(kind=None, minimized="response_minimized" in line)
if not isinstance(minimized, Mapping):
raise BodyUnreadable(f"the capture did not keep {_the(what)}'s body")
return _rebuild(minimized, need, what, form=minimized.get("format") == "form")


def request_hidden(line: Mapping[str, Any], *, raw_capture: bool = False) -> bool:
"""Whether the capture minimized away a request body a raw capture keeps.

A raw capture keeps a readable body as ``body`` or ``form``. It also
writes an opaque ``body_minimized``, for a body that isn't UTF-8 or a
multipart body with a file (``body_omitted``); a raw capture has no more
of that one, so it is not hidden. A minimized form or JSON body always
is. An opaque body is hidden when a raw capture would have kept it as
text: a textual or unlabelled type, not a form (a readable form is always
``form_minimized``). ``raw_capture``: the capture header says raw, so
nothing is hidden.
"""
if raw_capture or "form" in line or "body" in line:
return False
if isinstance(line.get("form_minimized"), Mapping):
return True
minimized = line.get("body_minimized")
if not isinstance(minimized, Mapping):
return False
if minimized.get("format") != "opaque":
return True
if line.get("body_omitted"):
return False
ctype = _ctype(minimized.get("content_type") or line.get("request_type"))
if ctype.startswith("multipart/") or ctype == "application/x-www-form-urlencoded":
return False
return ctype == "" or bool(_TEXT_REQUEST.search(ctype))


def response_hidden(line: Mapping[str, Any], *, raw_capture: bool = False) -> bool:
"""Whether the capture minimized away a response a raw capture keeps as
text: a minimized JSON or form response, or an opaque one of a type a raw
capture writes as text (``network_capture._TEXT_MIME``: HTML, JSON, plain
text). Any other response (binary, ``text/xml``) is opaque in a raw
capture too, so it is not hidden."""
from openadapt_flow.network_capture import _TEXT_MIME

if raw_capture or "response_text" in line:
return False
minimized = line.get("response_minimized")
if not isinstance(minimized, Mapping):
return False
if minimized.get("format") != "opaque":
return True
ctype = _ctype(minimized.get("content_type") or line.get("response_type"))
return bool(_TEXT_MIME.search(ctype))


def _ctype(value: Any) -> str:
return str(value or "").split(";")[0].strip().lower()


def _the(what: str) -> str:
return what if what.startswith("the ") else f"the {what}"


def _rebuild(
minimized: Mapping[str, Any],
need: Union[None, str, Iterable[str]],
what: str,
*,
form: bool,
) -> CapturedBody:
from openadapt_flow.capture_privacy import restore_kept_json

if (
minimized.get("format") == "opaque"
or minimized.get("truncated")
or ("kept" not in minimized and "withheld" not in minimized)
):
raise BodyUnreadable(f"the capture did not keep {_the(what)}'s body")
kept = [
[str(item[0]), item[1]]
for item in minimized.get("kept") or []
if isinstance(item, list) and len(item) == 2
]
withheld_paths = [
str(item[0])
for item in minimized.get("withheld") or []
if isinstance(item, list) and item
]
secrets = tuple(w for w in withheld_paths if is_withheld_name(w))
withheld = tuple(w for w in withheld_paths if not is_withheld_name(w))
kept_paths = tuple(path for path, _ in kept)
if need is not None:
if isinstance(need, str):
if need != ALL:
raise ValueError(f"need must be ALL or field paths, not {need!r}")
missing = sorted(set(withheld))
else:
present = set(kept_paths)
missing = sorted({str(n) for n in need if str(n) not in present})
if missing or not kept:
names = ", ".join(missing) or "every field"
raise FieldsWithheld(
f"the capture withheld {_the(what)}'s {names}; {RECORD_HINT}",
missing,
)
if form:
return CapturedBody(
kind="form",
form=kept,
minimized=True,
kept=kept_paths,
withheld=withheld,
secrets=secrets,
)
text: Optional[str] = None
if kept:
restored = restore_kept_json(minimized)
if not restored:
# Kept paths that collide: rebuild nothing rather than guess.
raise BodyUnreadable(f"the capture did not keep {_the(what)}'s body")
text = restored.decode("utf-8")
return CapturedBody(
kind="json",
text=text,
minimized=True,
kept=kept_paths,
withheld=withheld,
secrets=secrets,
)


def json_document(body: CapturedBody) -> Any:
"""``body.text`` parsed as JSON, or None (no text, or not JSON)."""
if body.text is None or not body.text.strip():
return None
try:
return json.loads(body.text)
except ValueError:
return None
Loading
Loading