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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

<!-- version list -->

## Unreleased

- `openadapt quickstart --app openemr` writes its `quickstart-readback.json`
through the encrypted run folder's sealed set instead of in plaintext, so
the halted run can still be sealed. The MockMed quickstart fix for
encryption at rest is in openadapt-flow (see its changelog).

## v1.24.0 (2026-11-24)

### Requirements
Expand Down
9 changes: 7 additions & 2 deletions openadapt/quickstart/openemr.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,12 @@ def work() -> tuple[dict[str, Any], int, Optional[Path]]:
return facts, len(after - before), screenshot

facts, new_charts, screenshot = self._main.submit(work).result()
(run_dir / "quickstart-readback.json").write_text(
from openadapt_flow import sealed_set

# Through the run's sealed set: a plaintext file in an encrypted run
# makes sealing it refuse (and this one names a patient).
sealed_set.write_text(
run_dir / "quickstart-readback.json",
json.dumps(
{
"existing_chart": "Rosa Delgado, born 1958-03-27",
Expand All @@ -659,7 +664,7 @@ def work() -> tuple[dict[str, Any], int, Optional[Path]]:
},
indent=2,
)
+ "\n"
+ "\n",
)
return BreakFacts(
run_dir=run_dir,
Expand Down
11 changes: 11 additions & 0 deletions packages/flow/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@

### Fixes

- `openadapt quickstart` no longer exits 1 on a fresh machine with encryption
at rest on, the default since 4.0.0 (#2682). The tutorial wrote its run
summary (`run-summary.json`, `.md`, `.png`) in plaintext into the encrypted
run folder, outside the folder's sealed index, so sealing the run failed
with `report_unreadable` ("holds run-summary.json in plaintext, outside its
sealed index"). `write_receipt` now writes the summary through the run's
sealed set, and the run inventory names the three summary files as
allow-listed plaintext, as it already did for their pre-3.5 names
(`receipt.md`, `receipt.png`). Any other plaintext file in a sealed run
still makes it refuse. The OpenEMR quickstart driver's halted-run screenshot
is also written through the set.
- Native approval and structural field reads require exact UIA values to agree
with independent native extent/full reads under the same control identity.
Missing, sensitive, incomplete or disagreeing values refuse the observation;
Expand Down
6 changes: 5 additions & 1 deletion packages/flow/benchmark/openemr_local/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,8 +666,12 @@ def authorize(_verifier: Any, gate_kwargs: dict[str, Any]) -> Any:
}

def screenshot(self, path: Path) -> Optional[Path]:
from openadapt_flow import sealed_set

try:
self.backend.page.screenshot(path=str(path))
png = self.backend.page.screenshot()
# Through the run's sealed set, so an encrypted run stays sealable.
sealed_set.write_bytes(path, png)
except Exception: # noqa: BLE001 - the report still has the frame
return None
return path
Expand Down
11 changes: 7 additions & 4 deletions packages/flow/docs/phi_at_rest.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,9 +309,11 @@ recording's raw capture session.
## Receipts

The receipt (`seal.json`), its timestamp and log proofs, `receipt.json`,
`receipt.md`, `receipt.png` and the public card (`public-seal.json`) stay
plaintext beside an encrypted run. They hold signatures, outcomes, counts and
digests, never the report's contents.
`receipt.md`, `receipt.png`, the run summary (`run-summary.json`,
`run-summary.md`, `run-summary.png`) and the public card (`public-seal.json`)
stay plaintext beside an encrypted run. They hold signatures, outcomes, counts
and digests, never the report's contents. The run summary is written through
the run's sealed set, so the run's index names it.

**Every digest is over the plaintext.** The receipt's `subject_sha256` and
the card's `report_sha256` are the SHA-256 of the plaintext `report.json`
Expand Down Expand Up @@ -495,7 +497,8 @@ Every file is encrypted except these structural ones: `.durable_run.claim`
(nonce digests and times), `.attended_capability.key` (a random per-run
secret, no recorded data), and the receipt files (`seal.json`,
`seal.anchor.json`, `seal.tsa.json`, `seal.tsr`, `seal.publish.json`,
`public-seal.json`, `receipt.json`, `receipt.md`, `receipt.png`; see
`public-seal.json`, `receipt.json`, `receipt.md`, `receipt.png`,
`run-summary.json`, `run-summary.md`, `run-summary.png`; see
[Receipts](#receipts)). `seal.html`, the receipt page, is an export: it is
plaintext and logged. Undo's prior record values (`undo/prior/*`) are
encrypted with the run. The durable store's checkpoints, pauses and
Expand Down
15 changes: 12 additions & 3 deletions packages/flow/openadapt_flow/receipt.py
Original file line number Diff line number Diff line change
Expand Up @@ -1244,18 +1244,27 @@ def write_receipt(receipt: RunReceipt, out_dir: Path | str) -> dict[str, Path]:
"""Write the run summary: ``run-summary.json``, ``.md`` and ``.png``, locally.

Purely local: this function performs no network I/O and never uploads.
Inside an encrypted run directory the files go through the run's sealed
set, which keeps them as allow-listed plaintext and names them in its
index, so sealing the run afterwards does not refuse them.
"""

import io

from openadapt_flow import sealed_set

try:
receipt = RunReceipt.model_validate(receipt.model_dump(mode="json"))
except ValueError as exc:
raise ReceiptError(f"receipt failed integrity validation: {exc}") from exc
directory = Path(out_dir)
directory.mkdir(parents=True, exist_ok=True)
json_path = directory / f"{SUMMARY_STEM}.json"
json_path.write_bytes(receipt.canonical_json() + b"\n")
sealed_set.write_bytes(json_path, receipt.canonical_json() + b"\n")
md_path = directory / f"{SUMMARY_STEM}.md"
md_path.write_text(render_receipt_markdown(receipt), encoding="utf-8")
sealed_set.write_text(md_path, render_receipt_markdown(receipt))
png_path = directory / f"{SUMMARY_STEM}.png"
render_receipt_png(receipt).save(png_path, format="PNG")
png = io.BytesIO()
render_receipt_png(receipt).save(png, format="PNG")
sealed_set.write_bytes(png_path, png.getvalue())
return {"json": json_path, "markdown": md_path, "png": png_path}
8 changes: 8 additions & 0 deletions packages/flow/openadapt_flow/sealed_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,14 @@ class FileKind:
FileKind("receipt.json", "structural", "the allow-listed run receipt"),
FileKind("receipt.md", "structural", "the allow-listed run receipt as text"),
FileKind("receipt.png", "structural", "the allow-listed run receipt as an image"),
# The run summary is the allow-listed receipt under its Flow 3.5 name
# (receipt.json now holds the signed receipt): outcomes, counts and
# digests, no record text. receipt.write_receipt writes it through the set.
FileKind("run-summary.json", "structural", "the allow-listed run summary"),
FileKind("run-summary.md", "structural", "the allow-listed run summary as text"),
FileKind(
"run-summary.png", "structural", "the allow-listed run summary as an image"
),
FileKind(
"seal.html",
"export",
Expand Down
122 changes: 122 additions & 0 deletions packages/flow/tests/test_quickstart_encrypted.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
"""``openadapt quickstart`` on a fresh machine, with encryption at rest on.

The launcher's quickstart tests run against a fake engine, and the Flow suite
opts out of encryption unless ``OPENADAPT_TEST_DEFAULT_AT_REST=1``. So nothing
in CI ran the real quickstart under the default (encrypted) mode, and on
Flow 4.0.0 it exited 1 after "Saved and checked": the tutorial's run summary
was written in plaintext into the encrypted run folder, and sealing the run
refused it.

This test drives the real quickstart in a hidden browser, with encryption on
whatever lane it runs in and an empty ``HOME`` (no key, no seal home), then
opens every sealed folder it wrote and checks that each file on disk is in
that folder's index.
"""

from __future__ import annotations

import io
import os
import sys
from pathlib import Path

import pytest

from openadapt_flow import at_rest, crypto, sealed_set

pytest.importorskip("openadapt.quickstart", reason="needs the in-tree launcher")
pytest.importorskip("playwright.sync_api", reason="needs Playwright")


def _browsers_path() -> str:
"""Playwright's browser cache under the real home, before HOME changes."""
explicit = os.environ.get("PLAYWRIGHT_BROWSERS_PATH")
if explicit:
return explicit
home = Path.home()
if sys.platform == "darwin":
return str(home / "Library" / "Caches" / "ms-playwright")
if sys.platform.startswith("win"):
return str(Path(os.environ.get("LOCALAPPDATA", home)) / "ms-playwright")
return str(home / ".cache" / "ms-playwright")


@pytest.fixture
def fresh_machine(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
browsers = _browsers_path()
home = tmp_path / "home"
home.mkdir()
for name in (
at_rest.OPT_OUT_ENV,
at_rest.MODE_ENV,
at_rest.ENCRYPT_ENV,
at_rest.HOME_ENV,
crypto.ENV_KEY,
sealed_set.RECORDING_ENV_KEY,
"OPENADAPT_BUNDLE_KEY",
"OPENADAPT_POLICY",
"OPENADAPT_SEAL_HOME",
):
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("HOME", str(home))
monkeypatch.setenv("USERPROFILE", str(home))
monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", browsers)
# The device key goes to a file under the empty home, never a keychain.
monkeypatch.setenv("OPENADAPT_FLOW_KEY_STORE", "file")
if sys.platform == "darwin":
# Playwright's headless shell, never an installed Chrome on a Mac.
monkeypatch.setenv("OPENADAPT_FLOW_BROWSER", "bundled")
monkeypatch.chdir(tmp_path)
at_rest._reset_for_tests()
yield home
at_rest._reset_for_tests()


def _unindexed(root: Path) -> list[str]:
opened = sealed_set.open_set(root)
opened.verify_all()
indexed = {
sealed_set._physical(rel, entry["codec"])
for rel, entry in opened._files.items()
}
return sorted(set(sealed_set._disk_files(root)) - indexed)


def test_quickstart_on_a_fresh_machine_seals_every_run(
fresh_machine: Path, tmp_path: Path
) -> None:
from openadapt.quickstart import next_steps, run_quickstart
from openadapt.quickstart.engine import FlowEngine

root = tmp_path / "openadapt-quickstart"
stream = io.StringIO()
outcome = run_quickstart(
root,
visible=False,
break_it=True,
verbose=False,
steps=next_steps(lambda command: command, str, True),
stream=stream,
interactive=False,
)
output = stream.getvalue()
runs = len(FlowEngine.inputs)
assert outcome.checked == runs, output
assert outcome.broken is not None and outcome.broken.stopped, output
# Encryption really was on: a key was made under the empty home.
assert "Created a local encryption key" in output
assert (fresh_machine / ".openadapt" / "keys").is_dir()

sealed = sorted(p.parent for p in root.rglob(sealed_set.HEADER))
names = {p.name for p in sealed}
assert {"recording", "bundle", "run-1", "run-broken"} <= names, names
for folder in sealed:
assert _unindexed(folder) == [], folder

for index in range(1, runs + 1):
run_dir = root / f"run-{index}"
report = sealed_set.read_bytes(run_dir / "report.json")
assert b'"execution_outcome":"VERIFIED"' in report.replace(b" ", b"")
# The run sealed: this is the step that failed on Flow 4.0.0.
assert (run_dir / "seal.json").is_file()
assert sealed_set.open_set(run_dir).is_file("run-summary.json")
84 changes: 84 additions & 0 deletions packages/flow/tests/test_run_summary_sealed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""The run summary inside an encrypted run directory joins the sealed set.

``write_receipt`` writes ``run-summary.{json,md,png}`` beside the run after
it finished. Under the encryption-at-rest default the run directory is a
sealed set, and a file written there outside the set makes every later read
of the run refuse ("holds run-summary.json in plaintext, outside its sealed
index"): ``openadapt quickstart`` then failed to seal its first run. The
summary is the allow-listed receipt (outcomes, counts and digests, no record
text), so it stays plaintext on disk, like the receipt files beside it, but
it is now written through the set and named in its index.
"""

from __future__ import annotations

from pathlib import Path

import pytest

from openadapt_flow import at_rest, crypto, sealed_set
from openadapt_flow.receipt import build_receipt, read_run_summary, write_receipt
from tests.test_run_receipt import _report


@pytest.fixture
def sealed_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""A finalized sealed run directory under the default at-rest mode."""
for name in (
at_rest.OPT_OUT_ENV,
at_rest.MODE_ENV,
at_rest.ENCRYPT_ENV,
crypto.ENV_KEY,
sealed_set.RECORDING_ENV_KEY,
"OPENADAPT_POLICY",
):
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv(at_rest.HOME_ENV, str(tmp_path / "at-rest-home"))
at_rest._reset_for_tests()
run_dir = tmp_path / "run"
with sealed_set.writing(run_dir, "run", crypto.resolve_key(None)):
sealed_set.write_text(run_dir / "report.json", "{}")
assert sealed_set.is_sealed(run_dir)
yield run_dir
at_rest._reset_for_tests()


def test_the_summary_in_a_sealed_run_is_indexed_and_the_run_still_opens(
sealed_run: Path,
) -> None:
receipt = build_receipt(_report())
paths = write_receipt(receipt, sealed_run)

# The exact read seal_run makes first: it refused before the fix.
opened = sealed_set.open_set(sealed_run)
opened.verify_all()
for name in ("run-summary.json", "run-summary.md", "run-summary.png"):
assert opened.is_file(name), name
# Nothing on disk is outside the index.
indexed = {
sealed_set._physical(rel, entry["codec"])
for rel, entry in opened._files.items()
}
assert set(sealed_set._disk_files(sealed_run)) <= indexed

# Allow-listed plaintext: readable without the key, at the printed paths.
assert paths["png"].read_bytes().startswith(b"\x89PNG")
summary = read_run_summary(sealed_run)
assert summary is not None
assert summary["receipt_digest"] == receipt.receipt_digest
assert sealed_set.read_bytes(paths["json"]) == paths["json"].read_bytes()


def test_a_later_write_to_the_run_still_works(sealed_run: Path) -> None:
write_receipt(build_receipt(_report()), sealed_run)
sealed_set.write_text(sealed_run / "report.json", '{"ok": true}')
assert sealed_set.read_text(sealed_run / "report.json") == '{"ok": true}'


def test_any_other_plaintext_file_still_makes_the_run_refuse(
sealed_run: Path,
) -> None:
"""Fail-closed is unchanged: only the named summary files are allow-listed."""
(sealed_run / "run-summary.txt").write_text("not on the allow-list")
with pytest.raises(sealed_set.SealedSetError, match="in plaintext"):
sealed_set.open_set(sealed_run)
10 changes: 9 additions & 1 deletion tests/test_quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -1212,7 +1212,7 @@ def test_real_quickstart(tmp_path, monkeypatch, capfd):
# Only ciphertext screenshots, frames and typed values on disk. The
# receipt files are plaintext by design; the receipt pages embed the
# report (logged); the summary page leaves the screenshots out.
plain_ok = {"seal.html", "receipt.png"}
plain_ok = {"seal.html", "receipt.png", "run-summary.png"}
for path in root.rglob("*"):
if not path.is_file():
continue
Expand All @@ -1225,6 +1225,14 @@ def test_real_quickstart(tmp_path, monkeypatch, capfd):
assert note not in data, path
for folder in ("recording", "bundle", "run-1", "run-broken"):
assert sealed_set.is_sealed(root / folder), folder
# Every file on disk is in the folder's index: a plaintext file
# outside it makes the next read of the folder refuse.
opened = sealed_set.open_set(root / folder)
indexed = {
sealed_set._physical(rel, entry["codec"])
for rel, entry in opened._files.items()
}
assert set(sealed_set._disk_files(root / folder)) <= indexed, folder
assert "Created a local encryption key" in output
# Neither the key notice nor a plaintext notice reached the terminal.
err = capfd.readouterr().err
Expand Down
Loading