Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions packages/flow/docs/READINESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ a compiled program, is allowed to save anything: on the tasks your people
already do, how often would it have saved exactly what they saved?

1. A person does 20 to 50 real tasks with the browser recording's network
capture on (`record --backend web --capture-network`, see
[BROWSER_RECORDING.md](BROWSER_RECORDING.md) and
[NETWORK_CAPTURE.md](NETWORK_CAPTURE.md)).
capture on, declaring each field the save carries
(`record --backend web --capture-network --identifier patient_id --param type --param note`,
see [BROWSER_RECORDING.md](BROWSER_RECORDING.md) and
[NETWORK_CAPTURE.md](NETWORK_CAPTURE.md)). Captures keep only declared
values, so `readiness import` refuses a task whose compared fields were
withheld (`save_fields_withheld`) instead of comparing part of the save.
2. `readiness import` turns each recorded task into a reference episode.
3. `readiness run` gives the candidate the same tasks on a guarded browser
tab. It navigates and fills every field; the shadow hold stops it before
Expand Down
90 changes: 88 additions & 2 deletions packages/flow/openadapt_flow/readiness/reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,21 +269,53 @@ def _from_network(
return None
rows = network_capture.load(recording)
line = _save_line(rows, raw, app_origin)
body = line.get("body")
form_pairs = line.get("form")
secrets_withheld = 0
body_minimized = line.get("body_minimized")
form_minimized = line.get("form_minimized")
if body is None and form_pairs is None:
# A minimized capture (the default since captures keep only declared
# fields): rebuild the save from what it kept, or refuse.
from openadapt_flow.capture_privacy import restore_kept_json

if isinstance(form_minimized, Mapping):
form_pairs, secrets_withheld = _kept_fields(form_minimized, raw)
elif isinstance(body_minimized, Mapping):
_kept, secrets_withheld = _kept_fields(body_minimized, raw)
restored = restore_kept_json(body_minimized)
if not restored:
raise ReferenceRefused(
"save_unreadable", "the capture did not keep the save's body"
)
body = restored.decode("utf-8")
fields, withheld = parse_body_fields(
method=str(line.get("method")),
url=str(line.get("url")),
content_type=str(line.get("request_type") or ""),
body=line.get("body"),
body=body,
lens=lens,
form_pairs=line.get("form"),
form_pairs=form_pairs,
body_omitted=bool(line.get("body_omitted") or line.get("request_truncated")),
)
withheld += secrets_withheld
if any(f.name == "<body>" for f in fields):
raise ReferenceRefused(
"save_unreadable", "the capture did not keep the save's body"
)
wanted = raw.get("fields")
if isinstance(wanted, list) and wanted:
# JSON and form field names are case-sensitive: compare them exactly,
# the same way the filter below keeps them.
present = {f.name for f in fields}
absent = sorted(str(n) for n in wanted if str(n) not in present)
if absent:
# A compared field the save doesn't carry can't be compared.
raise ReferenceRefused(
"save_fields_withheld",
f"the save carries no {', '.join(absent)}; the comparison "
"needs every field the task names",
)
keep = set(map(str, wanted)) | set(raw["expected_record"])
fields = [f for f in fields if f.name in keep]
started = _events_start(recording)
Expand Down Expand Up @@ -324,6 +356,60 @@ def stamp(t: Optional[float]) -> Optional[str]:
}


def _kept_fields(
minimized: Mapping[str, Any], raw: Mapping[str, Any]
) -> tuple[list[list[Any]], int]:
"""The kept ``[path, value]`` pairs of a minimized save, checked for use.

Since captures keep only declared fields by default, a save recorded
without declaring its fields has every value withheld (hashed). The
comparison needs the person's values, so every field it compares must
have been kept: the task's ``fields`` when it names them, else every
field of the save. Paths are compared in full (``meta.note`` is not
``note``), the same names :func:`parse_body_fields` gives the fields. A
withheld one refuses the task, naming the field and the recording flag
that keeps it, instead of comparing part of the save. Session tokens and
secrets are never compared, so their being withheld is expected; they are
counted, as for a raw body. An opaque or truncated body kept nothing to
read and refuses as unreadable.
"""
from openadapt_flow.agent_guard.shadow_hold import is_withheld_name

if minimized.get("format") == "opaque" or (
"kept" not in minimized and "withheld" not in minimized
):
raise ReferenceRefused(
"save_unreadable", "the capture did not keep the save's body"
)
kept = [
[str(item[0]), item[1]]
for item in minimized.get("kept") or []
if isinstance(item, list) and len(item) == 2
]
kept_paths = {path for path, _ in kept}
withheld_paths = [
str(item[0])
for item in minimized.get("withheld") or []
if isinstance(item, list) and item
]
secrets = [w for w in withheld_paths if is_withheld_name(w)]
withheld = [w for w in withheld_paths if not is_withheld_name(w)]
wanted = raw.get("fields")
if isinstance(wanted, list) and wanted:
missing = sorted(str(name) for name in wanted if str(name) not in kept_paths)
else:
missing = sorted(set(withheld))
if missing or not kept:
names = ", ".join(missing) or "every field"
raise ReferenceRefused(
"save_fields_withheld",
f"the capture withheld the save's {names}; record with each field "
"declared (--param or --identifier), or with "
"--capture-network-bodies raw on a sealed recording",
)
return kept, len(secrets)


def network_capture_path(url: str) -> str:
from urllib.parse import urlsplit

Expand Down
8 changes: 7 additions & 1 deletion packages/flow/tests/e2e/test_readiness_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ def write_sample(runs: Path, task_id: str, card_dir: Path, name: str) -> None:
)


# The fields the MockMed save carries (``POST /api/encounter``).
SAVE_FIELDS = ("patient_id", "type", "note")


def _episode(i: int) -> dict[str, Any]:
pid = list(PATIENTS)[i % 3]
return {
Expand Down Expand Up @@ -189,7 +193,9 @@ def _record_people(app_url: str, src: Path, n: int) -> None:
rec = folder / "recording"
rec.mkdir(parents=True)
context = browser.new_context(viewport={"width": 1280, "height": 800})
capture = NetworkCapture(context).start()
# Declare the save's fields, as `record --param` does: captures
# keep only declared values, and the comparison needs them.
capture = NetworkCapture(context, keep_fields=SAVE_FIELDS).start()
t0 = time.monotonic()
events: list[dict[str, Any]] = []
page = context.new_page()
Expand Down
146 changes: 146 additions & 0 deletions packages/flow/tests/test_readiness_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,149 @@ def test_readback_through_the_verify_config(tmp_path: Path) -> None:
]
finally:
app.stop()


def _minimized_save(kept: list[list[Any]], withheld: list[str]) -> dict[str, Any]:
"""A save as the default (minimized) network capture writes it."""
line = {k: v for k, v in _save().items() if k != "body"}
line["body_minimized"] = {
"schema": "openadapt.capture-minimized/1",
"format": "json",
"bytes": 90,
"hmac": "hmac-sha256:" + "0" * 64,
"kept": kept,
"withheld": [[name, "hmac-sha256:" + "1" * 64] for name in withheld],
}
return line


def test_import_reads_declared_fields_of_a_minimized_capture(tmp_path: Path) -> None:
folder = _task(tmp_path / "src" / "a")
_capture(
folder,
[
_minimized_save(
[["patient_id", "p1"], ["type", "Triage"], ["note", "Cough, 3 days"]],
["csrf_token"],
)
],
)
result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/")
assert result.imported == ["ref-task-0001"] and result.refused == []
ep = json.loads(
(tmp_path / "eps" / "ref-task-0001" / "reference_episode.json").read_text()
)
assert {f["name"]: f["value"] for f in ep["human_fields"]} == {
"patient_id": "p1",
"type": "Triage",
"note": "Cough, 3 days",
}
assert ep["withheld_fields"] == 1 # the session token, as with a raw body


def test_import_refuses_a_save_whose_fields_were_not_declared(tmp_path: Path) -> None:
folder = _task(tmp_path / "src" / "a")
_capture(
folder,
[_minimized_save([["patient_id", "p1"]], ["type", "note", "csrf_token"])],
)
result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/")
assert result.imported == []
[refusal] = result.refused
assert refusal["code"] == "save_fields_withheld"
assert "note, type" in refusal["why"] and "--param" in refusal["why"]


def test_import_of_a_minimized_capture_needs_only_the_named_fields(
tmp_path: Path,
) -> None:
folder = _task(tmp_path / "src" / "a", fields=["note"])
_capture(
folder,
[_minimized_save([["note", "Cough, 3 days"]], ["type", "csrf_token"])],
)
result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/")
# The task names the fields it compares; only those must have been kept.
assert result.refused == [] and result.imported == ["ref-task-0001"]


def _real_minimized(line: dict[str, Any], keep: list[str]) -> dict[str, Any]:
"""A save line as the default capture writes it, via the real minimizer."""
from openadapt_flow.capture_privacy import BodyMinimizer, minimize_line

return minimize_line(line, BodyMinimizer(keep_fields=keep))


def test_a_withheld_field_is_not_satisfied_by_a_kept_field_of_the_same_leaf(
tmp_path: Path,
) -> None:
# meta.note is kept and the top-level note is withheld: "note" must refuse.
line = _save()
line["body"] = json.dumps(
{"patient_id": "p1", "type": "Triage", "note": "Cough", "meta": {"note": "x"}}
)
folder = _task(tmp_path / "src" / "a", fields=["type", "note"])
_capture(folder, [_real_minimized(line, ["patient_id", "type", "meta.note"])])
result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/")
assert result.imported == []
[refusal] = result.refused
assert refusal["code"] == "save_fields_withheld" and "note" in refusal["why"]


def test_a_minimized_form_save_with_declared_fields_imports(tmp_path: Path) -> None:
line = {k: v for k, v in _save().items() if k != "body"}
line["request_type"] = "application/x-www-form-urlencoded"
line["form"] = [["patient_id", "p1"], ["type", "Triage"], ["note", "Cough, 3 days"]]
folder = _task(tmp_path / "src" / "a")
_capture(folder, [_real_minimized(line, ["patient_id", "type", "note"])])
result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/")
assert result.refused == [] and result.imported == ["ref-task-0001"]
ep = json.loads(
(tmp_path / "eps" / "ref-task-0001" / "reference_episode.json").read_text()
)
assert {f["name"]: f["value"] for f in ep["human_fields"]} == {
"patient_id": "p1",
"type": "Triage",
"note": "Cough, 3 days",
}


def test_a_minimized_form_save_with_undeclared_fields_refuses(tmp_path: Path) -> None:
line = {k: v for k, v in _save().items() if k != "body"}
line["request_type"] = "application/x-www-form-urlencoded"
line["form"] = [["patient_id", "p1"], ["type", "Triage"], ["note", "Cough"]]
folder = _task(tmp_path / "src" / "a")
_capture(folder, [_real_minimized(line, ["patient_id"])])
result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/")
[refusal] = result.refused
assert refusal["code"] == "save_fields_withheld"


def test_a_truncated_minimized_body_is_unreadable_not_undeclared(
tmp_path: Path,
) -> None:
line = _save()
line["request_truncated"] = True
folder = _task(tmp_path / "src" / "a")
minimized = _real_minimized(line, ["patient_id", "type", "note"])
_capture(folder, [minimized])
result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/")
[refusal] = result.refused
assert refusal["code"] == "save_unreadable", minimized.get("body_minimized")


@pytest.mark.parametrize("minimized", [False, True])
def test_a_task_field_named_in_another_case_refuses_instead_of_dropping(
tmp_path: Path, minimized: bool
) -> None:
# The save carries "note"; the task names "Note". Field names are
# case-sensitive, so "Note" is absent: refuse, never compare without it.
folder = _task(tmp_path / "src" / "a", fields=["type", "Note"])
line = _save()
if minimized:
line = _real_minimized(line, ["patient_id", "type", "note"])
_capture(folder, [line])
result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/")
assert result.imported == []
[refusal] = result.refused
assert refusal["code"] == "save_fields_withheld" and "Note" in refusal["why"]