From c09c5bc25c56a35a6b37281b501dae10839e886d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:05:21 -0500 Subject: [PATCH 01/37] flow: encrypt recordings, bundles and runs at rest by default (WIP) Envelope encryption: each sealed set has its own data key, wrapped with age (X25519, pyrage) for this computer's device key (OS keychain through keyring, 0600 file fallback with a warning), optional organization recipients and shares. Configured passphrase keys keep the v1 header. at-rest status, share and shred. Receipts read encrypted runs and stay over the plaintext report digest. --- CAPABILITIES.md | 4 +- openadapt/quickstart/engine.py | 35 +- openadapt/quickstart/images.py | 4 +- openadapt/quickstart/notices.py | 15 +- openadapt/seal_view/__init__.py | 41 +- packages/agent/tests/conftest.py | 2 + packages/desktop/tests/conftest.py | 2 + packages/flow/CHANGELOG.md | 27 + packages/flow/docs/LIMITS.md | 25 +- packages/flow/docs/PRIVACY.md | 25 +- .../commands/08-run-on-premises/at-rest.md | 0 packages/flow/docs/phi_at_rest.md | 223 ++++++-- packages/flow/openadapt_flow/__main__.py | 97 +++- packages/flow/openadapt_flow/at_rest.py | 518 ++++++++++++++++-- packages/flow/openadapt_flow/cli_at_rest.py | 129 +++++ packages/flow/openadapt_flow/demo_proof.py | 26 +- .../flow/openadapt_flow/desktop_record.py | 79 +++ packages/flow/openadapt_flow/envelope.py | 255 +++++++++ packages/flow/openadapt_flow/hosted.py | 26 +- packages/flow/openadapt_flow/offline_seal.py | 39 +- packages/flow/openadapt_flow/public_seal.py | 11 +- packages/flow/openadapt_flow/records/run.py | 9 +- .../runtime/durable/first_local_runtime.py | 26 +- packages/flow/openadapt_flow/sealed_set.py | 304 +++++++++- packages/flow/openadapt_flow/tutorial.py | 7 + packages/flow/pyproject.toml | 7 + packages/flow/tests/conftest.py | 7 + packages/flow/tests/test_envelope_at_rest.py | 350 ++++++++++++ packages/flow/uv.lock | 16 + tests/conftest.py | 7 + tests/test_quickstart.py | 30 +- 31 files changed, 2129 insertions(+), 217 deletions(-) create mode 100644 packages/flow/docs/commands/08-run-on-premises/at-rest.md create mode 100644 packages/flow/openadapt_flow/cli_at_rest.py create mode 100644 packages/flow/openadapt_flow/envelope.py create mode 100644 packages/flow/tests/test_envelope_at_rest.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 3214679ba6..9c30b43e75 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -346,8 +346,8 @@ improvising or retrying when something is off. | Each package installs on its own within a size budget, checked in CI (privacy without desktop, capture without plotting) | Released ([#1270](https://github.com/OpenAdaptAI/OpenAdapt/pull/1270), [#1271](https://github.com/OpenAdaptAI/OpenAdapt/pull/1271), [#1279](https://github.com/OpenAdaptAI/OpenAdapt/pull/1279)) | CI | `.github/workflows/packages.yml` | | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | -| Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | -| Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | +| Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | +| Encryption at rest by default, as envelope encryption: each recording, bundle and run has its own data key, wrapped with age (X25519) for this computer's device key (kept in the OS keychain, or a 0600 file with a warning where none works), optional organization recipients from the environment or a policy file, and shares added later; a configured `OPENADAPT_BUNDLE_KEY` stays a recipient. `at-rest shred` deletes the wrapped keys (crypto-shredding). Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line; strict mode also refuses what can't be encrypted yet | On this branch | Synthetic (device-key, fail-closed, recipient, share, shred, forged-header tests with an injected keychain); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.envelope`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#recipients) | | Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | diff --git a/openadapt/quickstart/engine.py b/openadapt/quickstart/engine.py index f332599042..76590439db 100644 --- a/openadapt/quickstart/engine.py +++ b/openadapt/quickstart/engine.py @@ -179,12 +179,15 @@ def _loop(self) -> None: self._drain() def _drain(self) -> None: + from openadapt_flow import sealed_set + + # The recording is encrypted as it is written; the recorder runs in + # this process, so this reads its event log in memory. try: - with self._events.open("r", encoding="utf-8") as handle: - handle.seek(self._offset) - text = handle.read() - except FileNotFoundError: + raw = sealed_set.read_bytes(self._events) + except (OSError, sealed_set.SealedSetError): return + text = raw[self._offset :].decode("utf-8", errors="replace") complete, _, _partial = text.rpartition("\n") if not complete and not text.endswith("\n"): return @@ -325,7 +328,7 @@ def __init__(self, path: Path) -> None: def _loop(self) -> None: while not self._stop.wait(_TICK_S): - if self._path.is_file(): + if _artifact_is_file(self._path): time.sleep(_TICK_S) # let the writer finish the file digest = _sha256(self._path) self._text = read_screen_text(self._path) @@ -345,12 +348,24 @@ def text_for(self, path: Path) -> Optional[str]: def _sha256(path: Path) -> Optional[str]: import hashlib + from openadapt_flow import sealed_set + try: - return hashlib.sha256(path.read_bytes()).hexdigest() - except OSError: + return hashlib.sha256(sealed_set.read_bytes(path)).hexdigest() + except (OSError, sealed_set.SealedSetError): return None +def _artifact_is_file(path: Path) -> bool: + """Whether a run file exists, encrypted or not.""" + from openadapt_flow import sealed_set + + try: + return sealed_set.is_file(path) + except sealed_set.SealedSetError: + return False + + class FlowEngine: """The bundled tutorial, one stage per call, inside one browser process.""" @@ -714,7 +729,7 @@ def write_page(self, first: RunFacts, broken: BreakFacts) -> Optional[Path]: receipts = { kind: first.run_dir / f"receipt.{kind}" for kind in ("json", "md", "png") - if (first.run_dir / f"receipt.{kind}").is_file() + if _artifact_is_file(first.run_dir / f"receipt.{kind}") } result = TutorialResult( recording_dir=self.recording_dir, @@ -781,8 +796,10 @@ def readback_fields( ) -> list[tuple[str, Optional[str], Optional[str]]]: """``(field, literal, param)`` for the first ``record_written`` check in a bundle.""" + from openadapt_flow import sealed_set + try: - workflow = json.loads(workflow_json.read_text(encoding="utf-8")) + workflow = json.loads(sealed_set.read_text(workflow_json)) except (OSError, ValueError): return [] for step in workflow.get("steps") or []: diff --git a/openadapt/quickstart/images.py b/openadapt/quickstart/images.py index c45c625f91..01b228094f 100644 --- a/openadapt/quickstart/images.py +++ b/openadapt/quickstart/images.py @@ -55,9 +55,11 @@ def detect_image_protocol( def crop_png(path: Path, box: tuple[int, int, int, int]) -> bytes: """Return the ``(left, top, right, bottom)`` part of a PNG, as PNG bytes.""" + from openadapt_flow import sealed_set from PIL import Image - with Image.open(path) as image: + # A run's screenshots are encrypted on disk: decrypt in memory only. + with Image.open(io.BytesIO(sealed_set.read_bytes(path))) as image: width, height = image.size left, top, right, bottom = box cropped = image.crop((left, top, min(right, width), min(bottom, height))) diff --git a/openadapt/quickstart/notices.py b/openadapt/quickstart/notices.py index 7d66fca612..a2c7f6dc33 100644 --- a/openadapt/quickstart/notices.py +++ b/openadapt/quickstart/notices.py @@ -29,7 +29,10 @@ _PLAINTEXT = re.compile(r"^WARNING: writing (.+?) in plaintext at (rest \(|.+?: )") #: Flow's line when it creates this machine's at-rest key on first use. -_KEY_CREATED = re.compile(r"^Created a local encryption key .* at (.+?)\. Back it up") +_KEY_CREATED = re.compile( + r"^Created a local encryption key .* at (.+?)\. Back it up" + r"|^WARNING: no OS keychain is available .*device key in (.+?), readable" +) class Notices(io.TextIOBase): @@ -53,9 +56,9 @@ def write(self, text: str) -> int: match = _PLAINTEXT.match(line) created = _KEY_CREATED.match(line) if match: - self.paths.append(match.group(2)) + self.paths.append(match.group(1) + "\0" + match.group(2)) elif created: - self.key_created = created.group(1) + self.key_created = created.group(1) or created.group(2) else: self.target.write(line + "\n") return len(text) @@ -119,6 +122,12 @@ def plaintext_line(paths: Sequence[str], where: object) -> Optional[str]: if not paths: return None + if all(item.startswith("a receipt page") for item in paths): + # Everything else is encrypted; the receipt pages embed the report. + return ( + f"The receipt pages in {where} are unencrypted: each embeds its " + "run's report (synthetic data only)" + ) return ( f"The recording, program and run reports in {where} are unencrypted " "(synthetic data only); OPENADAPT_FLOW_AT_REST=strict refuses that" diff --git a/openadapt/seal_view/__init__.py b/openadapt/seal_view/__init__.py index 25153e478e..2d4c0a31e1 100644 --- a/openadapt/seal_view/__init__.py +++ b/openadapt/seal_view/__init__.py @@ -62,6 +62,40 @@ def _text(path: Path) -> Optional[str]: return None +def _artifact_is_file(path: Path) -> bool: + """Whether ``path`` exists, inside an encrypted folder too.""" + from openadapt_flow import sealed_set + + try: + return sealed_set.is_file(path) + except sealed_set.SealedSetError: + return False + + +def _report_bytes(path: Path) -> bytes: + """The run report's plaintext bytes: decrypted in memory when the run + folder is encrypted. The receipt is over these bytes.""" + from openadapt_flow import sealed_set + + try: + return sealed_set.read_bytes(path) + except sealed_set.SealedSetError as exc: + raise OSError(str(exc)) from exc + + +def _note_plaintext_page(run_dir: Path, target: Path) -> None: + """The page embeds report.json. Beside an encrypted run it is a plaintext + copy of the run's inputs: say so and record it (strict mode refuses).""" + from openadapt_flow import at_rest, sealed_set + + if not sealed_set.is_sealed_path(run_dir): + return + try: + at_rest.unsealed_write("a receipt page (it embeds the run report)", target) + except at_rest.AtRestRefused as exc: + raise SealViewError(str(exc)) from exc + + def _b64(path: Path) -> Optional[str]: try: return base64.b64encode(path.read_bytes()).decode("ascii") @@ -121,7 +155,7 @@ def find_program( digest = report.get("bundle_content_digest") candidates = [Path(bundle_dir)] if bundle_dir else _bundle_candidates(run_dir) for candidate in candidates: - if not (candidate / "workflow.json").is_file(): + if not _artifact_is_file(candidate / "workflow.json"): continue try: spec = bundle_graph(candidate) @@ -206,7 +240,7 @@ def page_data( """What the viewer reads: the run's files exactly as they are on disk.""" run_dir = Path(run_dir) - report = (run_dir / "report.json").read_bytes() + report = _report_bytes(run_dir / "report.json") seal = _text(run_dir / "seal.json") if seal is None: raise SealViewError(f"{run_dir} has no seal.json") @@ -262,7 +296,7 @@ def write_seal_page( if not (run_dir / "seal.json").is_file(): raise SealViewError(f"{run_dir} is not a sealed run (no seal.json)") try: - report = json.loads(report_path.read_bytes()) + report = json.loads(_report_bytes(report_path)) except (OSError, ValueError) as exc: raise SealViewError(f"{report_path} can't be read") from exc if keys is None: @@ -283,6 +317,7 @@ def write_seal_page( commands=commands, ) target = Path(out) if out else run_dir / PAGE_NAME + _note_plaintext_page(run_dir, target) target.write_text(render_page(data), encoding="utf-8") return target diff --git a/packages/agent/tests/conftest.py b/packages/agent/tests/conftest.py index efa6bc99f7..efdc27fe74 100644 --- a/packages/agent/tests/conftest.py +++ b/packages/agent/tests/conftest.py @@ -198,3 +198,5 @@ def _isolated_flow_at_rest(tmp_path_factory, monkeypatch): ) monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data") monkeypatch.delenv("OPENADAPT_FLOW_AT_REST", raising=False) + # Never the OS keychain from tests: no dialog, no login-keychain write. + monkeypatch.setenv("OPENADAPT_FLOW_KEY_STORE", "file") diff --git a/packages/desktop/tests/conftest.py b/packages/desktop/tests/conftest.py index cdfb7ce65c..d272e50c21 100644 --- a/packages/desktop/tests/conftest.py +++ b/packages/desktop/tests/conftest.py @@ -151,6 +151,8 @@ def _isolated_flow_at_rest(tmp_path_factory, monkeypatch): monkeypatch.setenv("OPENADAPT_FLOW_AT_REST_HOME", str(tmp_path_factory.mktemp("at-rest-home"))) monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data") monkeypatch.delenv("OPENADAPT_FLOW_AT_REST", raising=False) + # Never the OS keychain from tests: no dialog, no login-keychain write. + monkeypatch.setenv("OPENADAPT_FLOW_KEY_STORE", "file") @pytest.fixture(autouse=True) diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index c488559fb3..6d5db95509 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -17,6 +17,33 @@ ## v3.4.0 (held until PyPI serves openadapt-privacy 1.1.4) +### Encryption at rest by default + +- Recordings (web, the quickstart and tutorial, and desktop once converted), + compiled bundles and every run directory (report, step screenshots, crops, + frames, evidence, `REPORT.md`) are now encrypted at rest by default, with + no setup. Each set has its own data key, wrapped with age (X25519, through + `pyrage`) for its recipients: this computer's device key, kept in the OS + keychain through `keyring` (macOS Keychain, Windows Credential Manager, + Linux Secret Service; a 0600 file with a warning where none works), and + optional organization recipients (`OPENADAPT_ORG_RECIPIENTS` or a policy + file). `openadapt-flow at-rest status|share|shred` shows the key and + recipients, wraps a set for more recipients, and crypto-shreds it. +- A configured `OPENADAPT_BUNDLE_KEY` or `OPENADAPT_RECORDING_KEY` still wins + and keeps the header Flow always wrote. A key file from an earlier version + (`~/.openadapt/keys/at-rest.key`) keeps working. Plaintext folders still + read. +- `OPENADAPT_ENCRYPT_AT_REST=0`, or `--no-encrypt` on `record`, `compile`, + `run` and `replay`, turns it off with a one-line warning and a ledger line. +- A missing, locked or replaced keychain entry fails closed with a clear + error; Flow never makes a new key over it. +- Receipts (`seal.json`, `receipt.*`, `public-seal.json`) stay plaintext and + are now written for encrypted runs too; their digests are over the + plaintext `report.json`. `seal verify`, `inspect report-run`, the receipt + page and the quickstart read encrypted runs. The receipt page embeds the + report, so beside an encrypted run it is logged as a plaintext copy. +- New core dependencies: `pyrage` and `keyring`. + ### Features - Dropdowns, searchable selects, type-aheads and native selects are recorded, diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index a75c5b0da3..721b121c3f 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -1003,6 +1003,13 @@ postconditions, model requests, effect queries, logs, and reports. Keep those observations inside the declared execution boundary and apply storage, retention, access, and egress controls there. +Encryption at rest is on by default: recordings, bundles and run +directories (screenshots, frames, typed values, reports) are ciphertext on +disk, each under its own data key wrapped for this computer's device key and +any organization recipients ([`phi_at_rest.md`](phi_at_rest.md)). It protects +files at rest, not a running session: anyone who can run commands as the +signed-in person can read them, as Flow does. + 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 @@ -1027,13 +1034,17 @@ host hardening, storage encryption, backups, retention, access control, monitoring, effect-verifier integration, update validation, and disaster recovery. -The repository supplies integrity manifests, optional encryption at rest for -bundles, web recordings and the run directories of sealed bundles, destination -policy, local egress checks, and audit primitives. Encryption at rest does not -cover data in process memory, the target application's own storage, file names -and sizes, desktop recordings, or commands outside the list in -[`phi_at_rest.md`](phi_at_rest.md), which refuse sealed input; the key is a -passphrase in the environment, not a KMS. A content digest +The repository supplies integrity manifests, encryption at rest by default +for recordings, bundles and run directories, destination policy, local egress +checks, and audit primitives. Encryption at rest does not cover data in +process memory, the target application's own storage, file names and sizes, a +desktop recording's raw capture session while it records, cross-window +(`record --surface`) recordings, the receipt page, the logged artifacts in +[`phi_at_rest.md`](phi_at_rest.md), or commands outside its list, which refuse +sealed input. By default only this computer's device key, kept in the OS +keychain (or a 0600 file where there is none), opens what it wrote: it is not a +hardware-bound key, a KMS or an escrow, and losing it loses the data unless an +organization recipient was configured. A content digest proves byte identity, not publisher identity. A local hash chain is tamper evident against ordinary changes, not tamper proof against an administrator who can rewrite it. Local approvals record provenance but are not enterprise-IdP diff --git a/packages/flow/docs/PRIVACY.md b/packages/flow/docs/PRIVACY.md index f479d8e1ab..688bbac235 100644 --- a/packages/flow/docs/PRIVACY.md +++ b/packages/flow/docs/PRIVACY.md @@ -53,10 +53,12 @@ Paths this rule does not cover yet are listed under ## Local posture -Scrubbing and encryption are separate controls. Durable checkpoints are -encrypted by default, under a configured key or a locally generated one, and -`OPENADAPT_FLOW_AT_REST=strict` encrypts every recording, bundle and run -directory ([phi_at_rest.md](phi_at_rest.md#default-opt-out-and-strict-mode)). +Scrubbing and encryption are separate controls. Recordings, bundles, run +directories and durable checkpoints are encrypted by default, with no setup: +each set under its own data key, wrapped for this computer's device key (in +the OS keychain) and any organization recipients, or for a configured key. +`OPENADAPT_FLOW_AT_REST=strict` also refuses the outputs that can't be +encrypted yet ([phi_at_rest.md](phi_at_rest.md#default-opt-out-and-strict-mode)). Two environment variables control scrubbing of what is written locally. The default is **predictable, not maximally private**: `auto` writes unscrubbed @@ -102,9 +104,9 @@ what protects it. | # | Where (file:symbol) | PHI written | Control | |---|---|---|---| -| 1 | `recorder.py` recording dir | `frames/*.png` (full screenshots), `events.jsonl` (literal typed `text` incl. param values, `structured_identity` DOM text), `meta.json` (`params` example values), `network.jsonl` | **Encrypted at rest with a key** — with `OPENADAPT_RECORDING_KEY` (or `OPENADAPT_BUNDLE_KEY`) the web recorder writes only AES-256-GCM ciphertext from the first frame ([phi_at_rest.md](phi_at_rest.md)). Not scrubbed (the recording is the compile input; scrubbing it would corrupt the demo). Without a key, and for desktop recordings: filesystem controls + retention policy. | -| 2 | `compiler/compile.py` → `ir.Workflow.save` → `workflow.json` | `anchor.ocr_text`, `anchor.context_text`, `anchor.structured_identity` (identity band = name/DOB/MRN), `step.text` (literal TYPE), `params`, `step.intent`; plus `templates/*.png` and `identifier_crop` PNGs (rendered PHI) and the compiler sidecars | **Encrypted at rest when sealed** — `seal`, or `compile` of an encrypted recording, encrypts every bundle file that can hold patient data under one sealed index ([phi_at_rest.md](phi_at_rest.md)). Not scrubbed: the bundle *must* carry the recorded identity evidence to verify identity on replay. An unsealed bundle: filesystem controls + retention policy. | -| 3 | `runtime/replayer.py` → `RunReport.save` → `report.json` | `params`, `workflow_name`, per-step `intent`, `error`, `IdentityCheck.expected`/`observed` (recorded vs live band text — raw PHI), `UnarmedStep.*` | Session tokens, CSRF tokens, OAuth grants and credential headers in its URLs and strings are **redacted when it is written** and listed in `redactions` ([REPORT_REDACTION.md](REPORT_REDACTION.md)); a Seal refuses a report that still holds one. **Encrypted at rest for a sealed bundle** — the run directory of a sealed bundle is itself sealed: report, frames, crops, checkpoints and approvals. Otherwise a documented boundary: the machine artifact and identity audit trail, under filesystem controls + retention policy. The shareable derivative (`REPORT.md`) IS scrubbed — see below. | +| 1 | `recorder.py` recording dir | `frames/*.png` (full screenshots), `events.jsonl` (literal typed `text` incl. param values, `structured_identity` DOM text), `meta.json` (`params` example values), `network.jsonl` | **Encrypted at rest by default** — the web recorder writes only AES-256-GCM ciphertext from the first frame, under a per-recording data key wrapped for this computer's device key (kept in the OS keychain) and any organization recipients, or under `OPENADAPT_RECORDING_KEY` / `OPENADAPT_BUNDLE_KEY` when set ([phi_at_rest.md](phi_at_rest.md)). A desktop recording is encrypted when it is converted; its raw capture session is plaintext while it records, then deleted. Not scrubbed (the recording is the compile input; scrubbing it would corrupt the demo). Under `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` (logged), and for cross-window `record --surface` recordings (logged): filesystem controls + retention policy. | +| 2 | `compiler/compile.py` → `ir.Workflow.save` → `workflow.json` | `anchor.ocr_text`, `anchor.context_text`, `anchor.structured_identity` (identity band = name/DOB/MRN), `step.text` (literal TYPE), `params`, `step.intent`; plus `templates/*.png` and `identifier_crop` PNGs (rendered PHI) and the compiler sidecars | **Encrypted at rest by default** — `compile` (and `seal`) encrypt every bundle file that can hold patient data under one sealed index ([phi_at_rest.md](phi_at_rest.md)). Not scrubbed: the bundle *must* carry the recorded identity evidence to verify identity on replay. An unsealed bundle: filesystem controls + retention policy. | +| 3 | `runtime/replayer.py` → `RunReport.save` → `report.json` | `params`, `workflow_name`, per-step `intent`, `error`, `IdentityCheck.expected`/`observed` (recorded vs live band text — raw PHI), `UnarmedStep.*` | Session tokens, CSRF tokens, OAuth grants and credential headers in its URLs and strings are **redacted when it is written** and listed in `redactions` ([REPORT_REDACTION.md](REPORT_REDACTION.md)); a Seal refuses a report that still holds one. **Encrypted at rest by default** — every run directory is sealed: report, frames, crops, checkpoints and approvals; the receipt files beside it stay plaintext and hold only digests over the plaintext report. Under the opt-out, or for a run feature that can't be sealed yet (logged), a documented boundary: the machine artifact and identity audit trail, under filesystem controls + retention policy. The shareable derivative (`REPORT.md`) IS scrubbed — see below. | | 4 | `runtime/replayer.py:_save_step_png` → `steps/*.png` | full before/after frames | **Scrubbed** — routed through `scrub_image_bytes`; redacted when `OPENADAPT_FLOW_SCRUB_IMAGES=1` (opt-in under `auto`) **or implied under `SCRUB=on`** (a pinned run redacts frames without the extra flag). | | 5 | `runtime/heal.py:persist_heal` → `heals//{template,screen}.png`, `heal.json` | heal crop, full frame, Anchor text | **Scrubbed** for the PNGs (same gate as #4); `heal.json` text is a documented boundary (audit trail, same as #3). | | 6 | `report.py:render_run_report` → **`REPORT.md`** | `workflow_name`, `params` values, per-step `intent`, `error`, `UnarmedStep.intent`/`reason` | **Scrubbed** — every free-text field passes through `_md_phi` (scrub → escape). This is the artifact that gets committed to repos / shared with stakeholders, so it is scrubbed by default (auto) whenever the capability is present; when it is **not** present, a one-time `PlaintextPHIWarning` fires (see above). Embedded frames follow #4. | @@ -162,11 +164,10 @@ through. The control is therefore a **data-flow boundary**, stated in full in - **Bundle / recording / `report.json` text is not scrubbed.** By design: the recorded identity evidence and the audit trail require the literal - identifiers. With a key they are encrypted at rest instead (sealed bundles, - encrypted web recordings, and the run directories of sealed bundles; see - [phi_at_rest.md](phi_at_rest.md) for what stays readable). Without one they - are protected only by filesystem controls and the operator's retention - policy. Do not commit real bundles or run dirs to a public repo. + identifiers. They are encrypted at rest instead, by default (see + [phi_at_rest.md](phi_at_rest.md) for what stays readable). Under the + opt-out they are protected only by filesystem controls and the operator's + retention policy. Do not commit real bundles or run dirs to a public repo. - **Image redaction is best-effort.** Presidio image redaction is OCR+NER over the frame; it can miss non-textual PHI or unusual layouts. It is opt-in under `auto` (off by default) and implied under `SCRUB=on`. Treat persisted frames diff --git a/packages/flow/docs/commands/08-run-on-premises/at-rest.md b/packages/flow/docs/commands/08-run-on-premises/at-rest.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index cc1ae318d1..3db7b32224 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -13,35 +13,43 @@ machine), [phi_in_transit.md](phi_in_transit.md) (PHI on the wire) and ## Default, opt-out and strict mode -Flow encrypts with a configured key (`OPENADAPT_BUNDLE_KEY`, or -`OPENADAPT_RECORDING_KEY` for recordings) or, when none is set, with a key it -creates on first use at `~/.openadapt/keys/at-rest.key` (`$OPENADAPT_HOME`, -or `$OPENADAPT_FLOW_AT_REST_HOME`, moves it). The local key is mode 0600 in a -0700 directory, and Flow checks that only its owner can read it. Back it up -with your other secrets. +Flow encrypts recordings, bundles and run directories by default, with no +setup. Each one gets its own random data key, and that key is wrapped for +its recipients (see [Recipients](#recipients)). By default the only recipient +is this computer's device key. | | Default | `OPENADAPT_FLOW_AT_REST=strict` | | --- | --- | --- | | Durable checkpoints and attended state | Encrypted | Encrypted | -| Web recordings | Encrypted with a configured key; otherwise logged | Encrypted | -| Bundles from `compile`, `induce`, `admit` | Encrypted from encrypted input; otherwise logged | Encrypted | -| Run directories | Encrypted for a sealed bundle; otherwise logged | Encrypted | +| Web recordings (`record`, the quickstart and tutorial) | Encrypted | Encrypted | +| Desktop recordings (`record --backend windows\|macos\|linux\|rdp\|citrix`) | Raw capture plaintext while recording; see [Desktop recordings](#desktop-recordings) | Held back before the command runs | +| Cross-window recordings (`record --surface`) | Logged | Held back before the command runs | +| Bundles from `compile`, `induce`, `admit` | Encrypted | Encrypted | +| Run directories (report, step screenshots, crops, frames, evidence) | Encrypted | Encrypted | +| A run with an approval gate, an attended draft, a business-decision state or `--save-healed-to` | Logged, under this computer's key; refused with a configured key | Refused before it runs | | The bundle, skill library and compiled fix of `teach` | Encrypted from encrypted input; otherwise logged | Encrypted | | The sanitized review copy and approved archive of `push` | Encrypted from encrypted input; otherwise logged | Encrypted | -| Desktop recordings, approval requests, `--record-video`, and the output of `visualize`, `explain`, `emit-skill`, `compose`, `process`, `variants`, `route`, `for-each`, `shadow`, `compile-agent`, `guard`, `bench`, `sanitize`, `redact-report`, `jit`, `--save-healed-to`, `--workers` and `induce --report` | Logged | Held back before the command runs | +| The receipt page (`seal.html`) beside an encrypted run | Logged: it embeds the run report | Not written | +| Approval requests, `--record-video`, and the output of `visualize`, `explain`, `emit-skill`, `compose`, `process`, `variants`, `route`, `for-each`, `shadow`, `compile-agent`, `guard`, `bench`, `sanitize`, `redact-report`, `jit`, `--workers` and `induce --report` | Logged | Held back before the command runs | **Logged** means stderr names the path and one line goes to `~/.openadapt/plaintext-at-rest.jsonl`; when that line can't be written, the -write stops. OpenAdapt Desktop shows a notice in -its window from the same ledger. Issue -[#1751](https://github.com/OpenAdaptAI/OpenAdapt/issues/1751) tracks moving -each logged artifact to encrypted by default. +write stops. OpenAdapt Desktop shows a notice in its window from the same +ledger. Issue [#1751](https://github.com/OpenAdaptAI/OpenAdapt/issues/1751) +tracks the logged artifacts that remain. A sealed bundle always runs into a sealed run directory, in every mode. +**Turning it off.** `OPENADAPT_ENCRYPT_AT_REST=0`, or `--no-encrypt` on +`record`, `compile`, `run` and `replay`, writes plaintext. So does +`OPENADAPT_FLOW_PLAINTEXT_AT_REST=''`, which records the reason. Each +process prints a one-line warning and adds a ledger line. Strict mode ignores +all of them. Files encrypted earlier still read under the opt-out, with the +key that encrypted them. + **Healthcare and other regulated deployments:** set -`OPENADAPT_FLOW_AT_REST=strict` and a key from your secret manager. Strict -mode runs: +`OPENADAPT_FLOW_AT_REST=strict`, and an organization recipient or a key from +your secret manager. Strict mode runs: - `record`, `compile`, `induce`, `admit run`, `run`, `replay` and `resume`, which encrypt what they write, plaintext input included; @@ -49,9 +57,10 @@ mode runs: [Commands on sealed input](#commands-on-sealed-input), on encrypted input (every directory they are given must be encrypted); - the commands that write no recorded data: service health and control, the - no-outbound allow list, key and Seal verification. `service run` runs the - queue script it is given; the Flow commands the script starts inherit - strict mode, and the script's other actions are the operator's. + no-outbound allow list, `at-rest status`, key and receipt verification. + `service run` runs the queue script it is given; the Flow commands the + script starts inherit strict mode, and the script's other actions are the + operator's. Every other command, and qualification trials (`qualify campaign`, `qualify run-case`, `qualify drills`), is held back before it starts. @@ -61,31 +70,29 @@ and a directory holding a plaintext `workflow.json`, `events.jsonl` or `report.json` counts as plaintext wherever it sits. Every entry under an encrypted input is checked when the command starts: a symlink or a directory that can't be read below it refuses the run, and with a key the set is opened again rather than taken from an earlier read. `qualify run` and `qualify certify` take `--evidence-root`, which is usually a plaintext parent of sealed runs, so in strict mode run them on encrypted evidence or outside -strict mode. It encrypts every recording, bundle and run directory, and an -unknown value of `OPENADAPT_FLOW_AT_REST` stops the command. `seal` and -record checks on encrypted bundles use `OPENADAPT_BUNDLE_KEY` only. - -`OPENADAPT_FLOW_PLAINTEXT_AT_REST=''` is for development and -already de-identified data: it turns encryption off, and each process that -uses it prints a warning and adds a ledger line with the reason. `record ---no-encrypt` does the same for one web recording. Strict mode ignores both. +strict mode. An unknown value of `OPENADAPT_FLOW_AT_REST` or +`OPENADAPT_ENCRYPT_AT_REST` stops the command. `seal` and record checks on +encrypted bundles use `OPENADAPT_BUNDLE_KEY` only. OpenAdapt Desktop encrypts certified workflows with per-workflow keys in the -system keychain, and runs Flow with the opt-out recorded under its own +system keychain, and still runs Flow with the opt-out recorded under its own reason. ## Summary -With a key configured, these are ciphertext on disk: +By default, these are ciphertext on disk: -- every file of a sealed bundle that can hold patient data - (`openadapt-flow seal`, or `compile` of an encrypted recording); -- every file of a web recording, from the first frame (`record`); -- every file of the run directory of a sealed bundle: the report, step +- every file of a web recording that can hold patient data, from the first + frame: screenshots (`frames/`), typed text and DOM text (`events.jsonl`), + parameter examples (`meta.json`), network bodies; +- every such file of a compiled bundle: the program, its crops and sidecars; +- every file of a run directory: the report (with its inputs), step screenshots, identity and resolution crops, transition evidence, - checkpoints, pauses, approvals and undo records. + checkpoints, pauses, approvals, undo records and `REPORT.md`. -Flow reads them in memory. The test +Flow reads them in memory: `replay`, `run`, `resume`, `compile`, `inspect +report-run`, `seal verify`, the receipt page and the quickstart read +encrypted and plaintext folders alike. The test `tests/test_sealed_at_rest.py::test_record_compile_and_governed_run_write_no_plaintext` records a demonstration against the synthetic clinic app, compiles it, runs it to VERIFIED under the Standard profile and renders the report, while a process @@ -94,31 +101,131 @@ files included. It fails if any of them holds plaintext. What stays readable is listed under [What is not encrypted](#what-is-not-encrypted). +## Recipients + +Every encrypted recording, bundle and run directory (format version 3) has +its own random 256-bit data key. Its files are encrypted under that key with +AES-256-GCM. The header wraps the data key for each recipient with +[age](https://age-encryption.org) (X25519, through `pyrage`, MIT, which binds +the audited `rage` crate). Who can open the set is the list of recipients: + +| Recipient | Who holds the private key | Set by | +| --- | --- | --- | +| **The device** (default) | This computer: an age identity Flow creates on first use and keeps in the OS keychain (macOS Keychain, Windows Credential Manager with DPAPI, Linux Secret Service) | Nothing to set | +| **The organization** (optional) | Your reviewers and auditors, in your own KMS, HSM or age plugin | `OPENADAPT_ORG_RECIPIENTS=age1...` (comma-separated), or `{"recipients": ["age1..."]}` in the policy file (`OPENADAPT_POLICY_FILE`, default `~/.openadapt/policy.json`), which IT or MDM can place | +| **A share** | Whoever you give it to | `openadapt-flow at-rest share DIR --recipient age1...` | +| **A configured key** (legacy) | Your secret manager | `OPENADAPT_BUNDLE_KEY`, `OPENADAPT_RECORDING_KEY` | + +- With an organization recipient, a device writes evidence the organization + can read later, on another computer and after the person who recorded it + has left. A reviewer opens it with `OPENADAPT_AGE_IDENTITY_FILE` pointing + at an age identity file. A malformed organization recipient stops the + write: evidence is never written silently without it. +- `share` rewraps the same data key for more recipients; no file is + re-encrypted. Run it on the computer that wrote the set. +- A configured key still wins: with one set and no organization recipient, + Flow writes the version 1 header it always wrote, keyed by that passphrase + (scrypt N=2^15, r=8, p=1). With both, the passphrase and the organization + are recipients, and the device is not. +- age has no sender authentication, so a device-written header also carries + an HMAC under a key derived from the device identity. The device refuses a + header that names it but lacks a valid HMAC. +- OpenAdapt Cloud never holds a key, a wrapped key or recovery material. + +**Where the device key lives.** The device identity is stored with +`keyring` in the OS keychain, entry `openadapt-flow-at-rest`. Next to it, +`~/.openadapt/keys/device-key.store.json` records which entry holds it and a +check value; it holds no key material. If the entry is later missing, locked, +denied or different, Flow fails closed with a clear error and never makes a +new key over it. Where no keychain works (a headless Linux box without Secret +Service, for example), the identity goes to `~/.openadapt/keys/device.agekey`, +mode 0600 in a 0700 directory, with a warning. `OPENADAPT_FLOW_KEY_STORE` +picks the store: `auto` (default), `keychain` (fail without one) or `file`. +`OPENADAPT_FLOW_AT_REST_HOME` (or `OPENADAPT_HOME`) moves the marker and the +file. Back the device key up: what it alone encrypts can't be read without +it. A key file from an earlier version (`~/.openadapt/keys/at-rest.key`) +keeps being used as the local passphrase, so nothing it encrypted is +orphaned. + +The keychain item is readable by your login session; it is not a +non-exportable hardware key. A Secure Enclave or TPM provider (for example +through an age plugin) would slot in behind the same recipient interface +(`openadapt_flow.envelope`); it is not built yet. + +`openadapt-flow at-rest status` shows the mode, where the device key is kept, +its public recipient and the organization recipients. It prints no key +material. + +## Crypto-shredding + +`openadapt-flow at-rest shred DIR --yes` deletes every wrapped copy of a +set's data key (and the salt of an older set), and deletes the durable +checkpoints and other stores' ciphertext inside it. Nobody can open the set +afterwards, and there is no recovery copy anywhere. The library call is +`openadapt_flow.sealed_set.shred`, for a retention job. Copies you made +elsewhere (backups, shares already opened) are outside its reach. + +## 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. + +**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` +bytes, decrypted in memory. So a receipt is the same whether the run is +encrypted, rewrapped for a share, or was never encrypted, and checking it +needs a recipient's key to read the report. `seal verify` and the receipt +page decrypt the report to check it. + +The receipt page (`seal.html`) embeds the run report so it can check the +receipt in the browser. Beside an encrypted run it is therefore a plaintext +copy of the report (including the run's inputs): writing it is logged, and +strict mode refuses it. + +## Desktop recordings + +The desktop recorders capture through openadapt-capture, which writes its +raw session (input database and screen video) in plaintext under +`/.capture` while recording. When recording stops, Flow converts it into +an encrypted recording and deletes the raw session, so only ciphertext is +left. Until then, and if the process is killed before it converts, the raw +session is plaintext on disk. Record on an encrypted volume when that window +matters. + ## Keys | Variable | Used for | | --- | --- | -| `OPENADAPT_BUNDLE_KEY` | Sealed bundles and their run directories. Also turns on encrypted web recording by default. | -| `OPENADAPT_RECORDING_KEY` | Recordings. When it is unset, recordings use `OPENADAPT_BUNDLE_KEY`. | - -The key is a passphrase. Flow stretches it with scrypt (N=2^15, r=8, p=1) -over a random per-directory salt when it opens a reader or writer handle. -That explicit handle reuses its derived key to seal or open files with -AES-256-GCM, a fresh random 96-bit nonce for each write, and the file's path in -the associated data. Independent path-helper reads authenticate again; the -module retains no reader or passphrase cache. Caller inputs and derived keys -remain sensitive memory; releasing a handle does not promise erasure. Both -primitives come from the `cryptography` package. Key management (KMS, escrow, -rotation) is the operator's: Flow reads the passphrase from the environment -and never writes it. +| `OPENADAPT_BUNDLE_KEY` | A legacy passphrase recipient for bundles and their run directories. | +| `OPENADAPT_RECORDING_KEY` | The same for recordings. When it is unset, recordings use `OPENADAPT_BUNDLE_KEY`. | +| `OPENADAPT_ORG_RECIPIENTS` | Organization age recipients for every new set. | +| `OPENADAPT_AGE_IDENTITY_FILE` | age identities a reviewer reads sets with. | +| `OPENADAPT_FLOW_KEY_STORE` | Where the device key is kept: `auto`, `keychain` or `file`. | + +Each set is opened once per reader or writer handle. That handle reuses its +data key to seal or open files with AES-256-GCM, a fresh random 96-bit nonce +for each write, and the file's path in the associated data. Independent +path-helper reads authenticate again; the module retains no reader or +passphrase cache. Caller inputs and derived keys remain sensitive memory; +releasing a handle does not promise erasure. AES-256-GCM and scrypt come from +the `cryptography` package, and X25519 wrapping from `pyrage`. Durable +checkpoints and attended state keep their own containers, under the +configured key or a local passphrase derived from the device key (or the +earlier `at-rest.key`). + +Files are encrypted whole, in memory, not as a stream: a very large file +(a long screen video) needs its size in memory to read or write. ## Sealed sets A sealed bundle, an encrypted recording and an encrypted run directory share one format, the sealed set: -- `.openadapt-sealed.json` holds the salt, the scrypt parameters and an index - sealed with the derived key. The index lists every other file with the +- `.openadapt-sealed.json` holds the wrapped data key (version 3: one age + stanza per recipient; version 1: the salt and scrypt parameters) and an + index sealed with the data key. The index lists every other file with the SHA-256 of its bytes on disk. The header also repeats the index digest (`set_digest`) for an inventory that has no key; Flow trusts only the copy it recomputes from the authenticated index. @@ -373,17 +480,19 @@ marks as logged. Also: - Names and sizes. File names (`templates/step_003.png.enc`), file counts and ciphertext sizes show the number of steps and frames and roughly how large each image is. -- Structural files: `manifest.json`, the sealed-set headers, and the run - directory's claim, lock and lease files. -- Desktop recordings, as above. +- Structural files: `manifest.json`, the sealed-set headers (with the public + recipients), the run directory's claim, lock and lease files, and the + receipt files listed under [Receipts](#receipts). +- The receipt page (`seal.html`) and the quickstart's summary page + (`index.html`). The summary page leaves out an encrypted run's + screenshots; the receipt page embeds the report. +- A desktop recording's raw capture session while it records, as above. - The admission root's `admission-pending.json` and `admission-decision.json`. - Bundles encrypted with the older `Workflow.save(encrypt=True)` library call and no `seal`: only `workflow.json` and `templates/` are encrypted there. -- The offline Seal of a run (`local-seal`) is not written for an encrypted - run directory yet; the run says so on stderr. -- Commands outside the list above refuse sealed input rather than decrypt it - to disk. +- Commands outside the list above, `repair` among them, refuse sealed input + rather than decrypt it to disk. Each says so before it reads anything. ## The identity template is not encryption diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 931f0ee13a..93ae422877 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -526,17 +526,16 @@ def _recording_encryption_key(args: argparse.Namespace, backend: str) -> Optiona return None explicit = os.environ.get(sealed_set.RECORDING_ENV_KEY) or None if backend != "web": - if explicit: - raise SystemExit( - f"record: {sealed_set.RECORDING_ENV_KEY} is set, but the " - f"{backend} recorder writes its raw capture session " - "(database, video) through openadapt-capture, which Flow " - "cannot encrypt yet. Nothing was recorded. Record on an " - "encrypted volume and pass --no-encrypt, or use --backend web." - ) - if not at_rest.plaintext_allowed(f"a desktop recording at {out}"): - at_rest.unsealed_write(f"a {backend} recording", out) - return None + # The raw capture session (database, video) is plaintext while + # recording; Flow encrypts the converted recording and deletes the + # raw session (docs/phi_at_rest.md, "Desktop recordings"). Strict + # mode holds the raw window back. + if at_rest.strict(): + at_rest.unsealed_write(f"a {backend} raw capture session", out) + if at_rest.opt_out_reason() is not None: + at_rest.plaintext_allowed(f"a desktop recording at {out}") + return None + return explicit or sealed_set.recording_key() except at_rest.AtRestRefused as exc: raise SystemExit(f"record: {exc}") from exc if explicit or os.environ.get(crypto.ENV_KEY): @@ -1494,7 +1493,7 @@ def _cmd_record_capture(args: argparse.Namespace) -> int: "record: --browser-cdp-endpoint and --browser-page-url apply " "only to --backend web" ) - return _cmd_record_desktop(args, backend) + return _cmd_record_desktop(args, backend, recording_key) if ( getattr(args, "window", None) @@ -1792,10 +1791,19 @@ def _cmd_record_surfaces(args: argparse.Namespace) -> int: "--surface WINDOW). Nothing was recorded." ) # A capture session runs for every cross-window recording, and Flow - # cannot encrypt it yet: the desktop recording policy applies. - _recording_encryption_key( + # cannot encrypt a cross-window recording yet: it is written in + # plaintext, named on stderr and in the ledger (strict mode refuses). + if _recording_encryption_key( args, surfaces[0].kind if surfaces else host_surface_kind() - ) + ): + from openadapt_flow import at_rest + + try: + at_rest.unsealed_write( + "a cross-window recording (--surface)", args.out or "--out" + ) + except at_rest.AtRestRefused as exc: + raise SystemExit(f"record: {exc}") from exc desktop_params: dict[str, str] = {} web_params: list[str] = [] for entry in args.param or (): @@ -1871,7 +1879,9 @@ def _cmd_record_surfaces(args: argparse.Namespace) -> int: return 0 -def _cmd_record_desktop(args: argparse.Namespace, backend: str) -> int: +def _cmd_record_desktop( + args: argparse.Namespace, backend: str, recording_key: Optional[str] = None +) -> int: """Record a live desktop demonstration for a native/pixel desktop backend. Reuses the tested capture stack: an ``openadapt-capture`` session captures @@ -1943,6 +1953,7 @@ def _cmd_record_desktop(args: argparse.Namespace, backend: str) -> int: replay_window_title=getattr(args, "rdp_window_title", None), readiness_text=getattr(args, "rdp_readiness_text", None), stop=_record_until_stop(args), + encryption_key=recording_key, ) _stamp_recording_surface(out, backend) print(f"Recording written to {out}") @@ -8442,17 +8453,19 @@ def _emit_local_receipt(args: argparse.Namespace) -> int: ``openadapt_flow.receipt``; the rich local ``REPORT.md`` -- screenshots, typed values, OCR identity text, parameters -- is never the source. """ + from openadapt_flow import artifacts, sealed_set from openadapt_flow.ir import RunReport from openadapt_flow.receipt import ReceiptError, build_receipt, write_receipt run_dir = Path(args.run_dir) report_path = run_dir / "report.json" - if not report_path.is_file(): + if not artifacts.is_file(report_path): print(f"report-run failed: no report.json in {run_dir} — nothing to report.") return 1 try: - report = RunReport.model_validate_json(report_path.read_text(encoding="utf-8")) - except (OSError, ValueError): + # Decrypted in memory when the run directory is encrypted. + report = RunReport.model_validate_json(artifacts.read_text(report_path)) + except (OSError, ValueError, sealed_set.SealedSetError): print("report-run failed: report.json is unreadable or invalid") return 1 @@ -9786,6 +9799,16 @@ def build_parser() -> argparse.ArgumentParser: "an irreversible step on every run." ), ) + p.add_argument( + "--no-encrypt", + action="store_true", + help=( + "Write this command's output in plaintext (recorded in " + "~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is " + "encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. " + "Ignored under OPENADAPT_FLOW_AT_REST=strict" + ), + ) p.set_defaults(func=_cmd_compile) p = sub.add_parser( @@ -10303,6 +10326,16 @@ def build_parser() -> argparse.ArgumentParser: _add_browser_session_flags(p) _add_deployment_flags(p, worklist=True) _add_attest_flags(p) + p.add_argument( + "--no-encrypt", + action="store_true", + help=( + "Write this command's output in plaintext (recorded in " + "~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is " + "encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. " + "Ignored under OPENADAPT_FLOW_AT_REST=strict" + ), + ) p.set_defaults(func=_cmd_replay) p = sub.add_parser( @@ -10570,6 +10603,16 @@ def build_parser() -> argparse.ArgumentParser: ), ) _add_approval_flags(p) + p.add_argument( + "--no-encrypt", + action="store_true", + help=( + "Write this command's output in plaintext (recorded in " + "~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is " + "encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. " + "Ignored under OPENADAPT_FLOW_AT_REST=strict" + ), + ) p.set_defaults(func=_cmd_run) sa = sub.add_parser( @@ -10598,6 +10641,10 @@ def build_parser() -> argparse.ArgumentParser: _register_no_outbound(sub) + from openadapt_flow.cli_at_rest import register as _register_at_rest + + _register_at_rest(sub) + from openadapt_flow.cli_service import register as _register_service _register_service(sub) @@ -13684,6 +13731,10 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.cli_undo:_cmd_undo_list", "openadapt_flow.cli_undo:_cmd_undo_approve", "openadapt_flow.cli_undo:_cmd_undo_run", + # Rewrap or shred a set's header only; no file is decrypted to disk. + "openadapt_flow.__main__:_cmd_report_run", + "openadapt_flow.cli_at_rest:_cmd_share", + "openadapt_flow.cli_at_rest:_cmd_shred", } ) @@ -13730,6 +13781,7 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.cli_service:_cmd_pf_render", "openadapt_flow.cli_service:_cmd_restart", "openadapt_flow.cli_service:_cmd_run", + "openadapt_flow.cli_at_rest:_cmd_status", "openadapt_flow.cli_no_outbound:_cmd_add", "openadapt_flow.cli_no_outbound:_cmd_derive", "openadapt_flow.cli_no_outbound:_cmd_list", @@ -14278,6 +14330,13 @@ def main( return 2 from openadapt_flow import at_rest + if ( + getattr(args, "no_encrypt", False) + and getattr(args, "func", None) is not _cmd_record + ): + # `compile/run/replay --no-encrypt`: this process writes plaintext, + # with the one-line warning and the ledger line at the first write. + at_rest.opt_out_for_this_process("--no-encrypt") try: _unsealed_output_check(args) except (at_rest.AtRestRefused, ValueError) as exc: diff --git a/packages/flow/openadapt_flow/at_rest.py b/packages/flow/openadapt_flow/at_rest.py index fcd09f42a3..b43df2097a 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -2,30 +2,43 @@ Recordings, bundles, run directories (screenshots, reports, evidence) and durable checkpoints can hold patient data. Flow encrypts them with -:mod:`openadapt_flow.sealed_set` and :mod:`openadapt_flow.crypto`. +:mod:`openadapt_flow.sealed_set` and :mod:`openadapt_flow.crypto`, by default +and with no setup. * The key is ``OPENADAPT_BUNDLE_KEY`` (or ``OPENADAPT_RECORDING_KEY``) when - set. Otherwise it is a key Flow generates on this machine, - ``$OPENADAPT_HOME/keys/at-rest.key`` (default ``~/.openadapt``; - ``OPENADAPT_FLOW_AT_REST_HOME`` moves it), created on first use with mode - 0600 in a 0700 directory and refused if anyone but the owner can read it. - Back it up: what it encrypts can't be read without it. -* Durable checkpoints are encrypted under that key by - default. + set. Otherwise it is a per-user key Flow generates on first use and keeps in + the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret + Service, through ``keyring``). A small marker, + ``$OPENADAPT_HOME/keys/at-rest.key.store.json``, records which keychain + entry holds it and a check value; it holds no key material. Where no + keychain works (a headless Linux box without Secret Service, say), the key + goes to ``$OPENADAPT_HOME/keys/at-rest.key`` with mode 0600 in a 0700 + directory, with a warning. ``OPENADAPT_FLOW_KEY_STORE`` picks the store + (``auto``, the default; ``keychain``; ``file``). A key file made by an + earlier version keeps being used, so nothing it encrypted is orphaned. + ``OPENADAPT_FLOW_AT_REST_HOME`` moves the marker, the file and the ledger + (default ``$OPENADAPT_HOME``, else ``~/.openadapt``). Back the key up: what + it encrypts can't be read without it. +* Recordings, bundles, run directories and durable checkpoints are encrypted + under that key by default (:data:`DEFAULT_SEALS_ARTIFACTS`). * ``OPENADAPT_FLOW_AT_REST=strict``, the setting for healthcare and regulated - deployments, also encrypts every recording, bundle and run directory, and - refuses the outputs that aren't encrypted yet (:func:`unsealed_write`). -* In the default mode, each recording, bundle, run directory or other output - written in plaintext goes through :func:`unsealed_write` or :func:`seal_new`: - stderr names the path and a ledger line (``plaintext-at-rest.jsonl``) - records it, and Desktop shows the ledger as a notice. Once every consumer - reads encrypted artifacts (#1751), the default encrypts them too - (:data:`DEFAULT_SEALS_ARTIFACTS`). -* ``OPENADAPT_FLOW_PLAINTEXT_AT_REST=''`` turns encryption off for - development or de-identified data, with a warning and a ledger line. Strict - mode ignores it. - -Stdlib only, so :mod:`openadapt_flow.crypto` can import it on every load. + deployments, also refuses the outputs that aren't encrypted yet + (:func:`unsealed_write`). +* In the default mode, each output that still can't be encrypted goes through + :func:`unsealed_write`: stderr names the path and a ledger line + (``plaintext-at-rest.jsonl``) records it, and Desktop shows the ledger as a + notice. +* ``OPENADAPT_ENCRYPT_AT_REST=0`` (or ``record --no-encrypt``, ``compile + --no-encrypt``, ``run --no-encrypt``) turns encryption off, and + ``OPENADAPT_FLOW_PLAINTEXT_AT_REST=''`` does the same with a reason. + Each prints a one-line warning and adds a ledger line. Strict mode ignores + both. Files encrypted earlier still read. + +A keychain marker whose entry is gone, locked or different fails closed with +:class:`LocalKeyError`; Flow never mints a second key over it. + +Stdlib only (``keyring`` is imported lazily), so :mod:`openadapt_flow.crypto` +can import it on every load. """ from __future__ import annotations @@ -45,8 +58,23 @@ OPT_OUT_ENV: Final[str] = "OPENADAPT_FLOW_PLAINTEXT_AT_REST" MODE_ENV: Final[str] = "OPENADAPT_FLOW_AT_REST" +#: ``0`` turns encryption at rest off (with a warning and a ledger line). +ENCRYPT_ENV: Final[str] = "OPENADAPT_ENCRYPT_AT_REST" +#: Where a new local key is kept: ``auto`` (the OS keychain, else a file), +#: ``keychain`` (the keychain or an error) or ``file``. +KEY_STORE_ENV: Final[str] = "OPENADAPT_FLOW_KEY_STORE" LEDGER_NAME: Final[str] = "plaintext-at-rest.jsonl" KEY_NAME: Final[str] = "at-rest.key" +MARKER_NAME: Final[str] = "device-key.store.json" +DEVICE_KEY_NAME: Final[str] = "device.agekey" +KEYCHAIN_SERVICE: Final[str] = "openadapt-flow-at-rest" +_MARKER_SCHEMA: Final[str] = "openadapt.flow.at-rest-key-store/v1" +_CHECK_LABEL: Final[bytes] = b"openadapt-flow/device-key-check/v1" +_PASSPHRASE_LABEL: Final[bytes] = b"openadapt-flow/local-passphrase/v1" +#: How long a reader waits for another process that is creating the key. +_CREATE_WAIT_S: Final[float] = 5.0 +#: How long one keychain call may take before Flow gives up on it. +_KEYCHAIN_TIMEOUT_S: Final[float] = 30.0 _KEY_BYTES: Final[int] = 32 _lock = threading.Lock() @@ -72,6 +100,32 @@ def strict() -> bool: raise ValueError(f"{MODE_ENV} takes 'strict' or 'default', not {value!r}") +_OFF: Final[frozenset[str]] = frozenset({"0", "false", "no", "off"}) +_ON: Final[frozenset[str]] = frozenset({"", "1", "true", "yes", "on"}) + + +def encrypt_setting() -> bool: + """``OPENADAPT_ENCRYPT_AT_REST``: True (the default) unless set to ``0``, + ``false``, ``no`` or ``off``. Any other value raises, so a mistyped + setting never turns encryption off.""" + value = (os.environ.get(ENCRYPT_ENV) or "").strip().lower() + if value in _ON: + return True + if value in _OFF: + return False + raise ValueError(f"{ENCRYPT_ENV} takes 1 or 0, not {value!r}") + + +def opt_out_for_this_process(source: str) -> None: + """Turn encryption off for this process and its children (``--no-encrypt``). + + The one-line warning and the ledger line follow at the first write. + """ + os.environ[ENCRYPT_ENV] = "0" + if not (os.environ.get(OPT_OUT_ENV) or "").strip(): + os.environ[OPT_OUT_ENV] = source + + def explicit_key() -> bool: """Whether the deployment configured a key (rather than the local one).""" return bool( @@ -174,6 +228,8 @@ def opt_out_reason() -> Optional[str]: None in strict mode, which ignores the opt-out. """ reason = (os.environ.get(OPT_OUT_ENV) or "").strip() + if not encrypt_setting(): + reason = reason or f"{ENCRYPT_ENV}=0" if strict() and reason: with _lock: first = "strict-ignores-opt-out" not in _warned @@ -299,55 +355,392 @@ def _read(path: Path) -> str: return text -def local_key() -> str: - """Return this machine's at-rest key, creating it on first use.""" - path = local_key_path() +# -- the local key ------------------------------------------------------------- + + +class KeyStore: + """Where a generated key can live outside the file system: the interface + of the OS keychain store. Tests inject an in-memory one + (:func:`use_key_store`) so they never touch the user's real keychain.""" + + name = "keychain" + + def get(self, account: str) -> Optional[str]: # pragma: no cover - interface + raise NotImplementedError + + def set(self, account: str, value: str) -> None: # pragma: no cover + raise NotImplementedError + + +class KeychainStore(KeyStore): + """The OS keychain through ``keyring``: macOS Keychain, Windows Credential + Manager (DPAPI) and Linux Secret Service. Every call runs with a timeout, + so a keychain that waits on a prompt can't hang a headless run.""" + + def __init__(self, service: str = KEYCHAIN_SERVICE) -> None: + self.service = service + + def _call(self, what: str, fn: str, *args: str) -> Optional[str]: + try: + import keyring + except Exception as exc: # noqa: BLE001 - not installed, or broken + raise KeyStoreUnavailable(f"keyring is not importable ({exc})") from exc + result: dict[str, object] = {} + + def work() -> None: + try: + result["value"] = getattr(keyring, fn)(self.service, *args) + except BaseException as exc: # noqa: BLE001 - reported below + result["error"] = exc + + thread = threading.Thread(target=work, name="openadapt-keychain", daemon=True) + thread.start() + thread.join(_KEYCHAIN_TIMEOUT_S) + if thread.is_alive(): + raise KeyStoreUnavailable( + f"the OS keychain did not answer a {what} within " + f"{_KEYCHAIN_TIMEOUT_S:.0f} s" + ) + if "error" in result: + exc = result["error"] + raise KeyStoreUnavailable( + f"the OS keychain refused a {what} ({type(exc).__name__})" + ) from exc # type: ignore[misc] + value = result.get("value") + return value if isinstance(value, str) else None + + def get(self, account: str) -> Optional[str]: + return self._call("read", "get_password", account) + + def set(self, account: str, value: str) -> None: + self._call("write", "set_password", account, value) + + +class KeyStoreUnavailable(RuntimeError): + """The OS keychain can't be used: no backend, locked, denied or slow.""" + + +_injected_store: Optional[KeyStore] = None + + +def use_key_store(store: Optional[KeyStore]) -> None: + """Replace the OS keychain store (tests); ``None`` restores it.""" + global _injected_store + _injected_store = store + + +def _keychain() -> KeyStore: + return _injected_store if _injected_store is not None else KeychainStore() + + +def _store_choice() -> str: + configured = os.environ.get(KEY_STORE_ENV) + if ( + not configured + and _injected_store is None + and "PYTEST_CURRENT_TEST" in os.environ + ): + # A safety belt: a test that forgot to isolate the key store must + # never write to, or raise a dialog from, the person's real keychain. + return "file" + value = (configured or "auto").strip().lower() + if value not in ("auto", "keychain", "file"): + raise ValueError( + f"{KEY_STORE_ENV} takes 'auto', 'keychain' or 'file', not {value!r}" + ) + return value + + +def marker_path() -> Path: + """The non-secret record of which keychain entry holds the local key.""" + return _home() / "keys" / MARKER_NAME + + +def _account() -> str: + # One entry per Flow home, so a service or a test suite with its own + # OPENADAPT_FLOW_AT_REST_HOME never shares the person's key. + return f"device-key:{_home().expanduser().resolve()}" + + +def _valid_secret(text: Optional[str]) -> bool: + if not text or not text.startswith("AGE-SECRET-KEY-1"): + return False + try: + import pyrage + + pyrage.x25519.Identity.from_str(text) + except Exception: # noqa: BLE001 - not an identity + return False + return True + + +def _check(text: str) -> str: + import hashlib + import hmac + + return hmac.new(text.encode("ascii"), _CHECK_LABEL, hashlib.sha256).hexdigest() + + +def _read_secret(path: Path) -> str: + _check_mode(path) + text = path.read_text(encoding="ascii").strip() + if not _valid_secret(text): + raise LocalKeyError(f"{path} does not hold a Flow device key") + return text + + +def _read_marker(path: Path) -> Optional[dict[str, str]]: + if not path.exists(): + return None + _check_mode(path) + try: + marker = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise LocalKeyError( + f"{path} does not record where Flow's encryption key is. Nothing " + "was read or written." + ) from exc + if ( + not isinstance(marker, dict) + or marker.get("schema") != _MARKER_SCHEMA + or marker.get("store") != "keychain" + or not isinstance(marker.get("account"), str) + or not isinstance(marker.get("service"), str) + or not isinstance(marker.get("check"), str) + ): + raise LocalKeyError( + f"{path} does not record where Flow's encryption key is. Nothing " + "was read or written." + ) + return marker + + +def _from_keychain(marker: dict[str, str], path: Path) -> Optional[str]: + """The key the marker names, or None while its creator is still writing + it. Raises when the keychain can't be read or holds another value.""" + store = _keychain() + if isinstance(store, KeychainStore): + store = KeychainStore(marker["service"]) + try: + text = store.get(marker["account"]) + except KeyStoreUnavailable as exc: + raise LocalKeyError( + f"Flow's encryption key is in the OS keychain ({path} says so), but " + f"{exc}. Unlock the keychain or allow access, or set " + "OPENADAPT_BUNDLE_KEY. Nothing was read or written." + ) from exc + if text is None: + return None + if not _valid_secret(text) or _check(text) != marker["check"]: + raise LocalKeyError( + f"The OS keychain entry {marker['service']}/{marker['account']} " + f"does not hold the key {path} names. Nothing was read or written; " + "restore the entry from your backup, or set OPENADAPT_BUNDLE_KEY." + ) + return text + + +def device_key_path() -> Path: + """Where the device key lives when no OS keychain holds it.""" + return _home() / "keys" / DEVICE_KEY_NAME + + +def device_secret(*, create: bool) -> Optional[str]: + """This computer's device identity (an age X25519 secret), from the OS + keychain or the 0600 key file; created on first use when ``create``.""" + path = device_key_path() try: - return _local_key(path) + with _lock: + found = _existing(path, wait=create) + if found is not None or not create: + return found + return _create_device(path) except OSError as exc: raise LocalKeyError( - f"Flow could not create or read its local encryption key at {path} " - f"({exc}). Set OPENADAPT_BUNDLE_KEY, or {HOME_ENV} to a writable " - "private directory. Nothing was written." + f"Flow could not create or read its device key ({exc}). Set " + f"OPENADAPT_BUNDLE_KEY, or {HOME_ENV} to a writable private " + "directory. Nothing was written." ) from exc -def _local_key(path: Path) -> str: - with _lock: +def _derived_passphrase(secret: str) -> str: + """The local passphrase for the stores that take one (durable + checkpoints, attended state), derived from the device identity.""" + import hashlib + import hmac + + raw = hmac.new(secret.encode("ascii"), _PASSPHRASE_LABEL, hashlib.sha256).digest() + return base64.urlsafe_b64encode(raw).decode("ascii") + + +def local_key() -> str: + """This computer's local passphrase, creating the device key on first use. + + A key file from an earlier version (``at-rest.key``) is used as it is, so + nothing encrypted under it is orphaned. + """ + path = local_key_path() + try: if path.exists(): return _read(path) - path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - if os.name == "posix": - os.chmod(path.parent, 0o700) - text = base64.urlsafe_b64encode(secrets.token_bytes(_KEY_BYTES)).decode() - # Write a private temporary file, then link it into place, which - # fails if another process got there first: no reader ever sees a - # half-written key, and no key is ever replaced. - tmp = path.with_name(f".{KEY_NAME}.{os.getpid()}.{secrets.token_hex(4)}") - fd = open_binary(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) - try: - os.write(fd, (text + "\n").encode("ascii")) - os.fsync(fd) - finally: - os.close(fd) - try: - os.link(tmp, path) - except FileExistsError: - return _read(path) - finally: - tmp.unlink() + except OSError as exc: + raise LocalKeyError(f"{path} can't be read ({exc}).") from exc + secret = device_secret(create=True) + assert secret is not None + return _derived_passphrase(secret) + + +def _existing(path: Path, *, wait: bool) -> Optional[str]: + """The device secret already kept for this home: the key file, else the + keychain entry the marker names. None when there is none yet.""" + deadline = time.monotonic() + (_CREATE_WAIT_S if wait else 0.0) + marker_file = path.with_name(MARKER_NAME) + while True: + if path.exists(): + return _read_secret(path) + marker = _read_marker(marker_file) + if marker is None: + return None + text = _from_keychain(marker, marker_file) + if text is not None: + return text + if time.monotonic() >= deadline: + raise LocalKeyError( + f"Flow's device key should be in the OS keychain ({marker_file} " + f"says so), but the entry {marker['service']}/{marker['account']} " + "is missing. Nothing was read or written; restore it from your " + "backup, or set OPENADAPT_BUNDLE_KEY. Flow does not make a new " + "key over it." + ) + time.sleep(0.05) # another process is between its marker and its write + + +def _private_dir(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True, mode=0o700) + if os.name == "posix": + os.chmod(directory, 0o700) + + +def _link_new(path: Path, data: bytes) -> bool: + """Create ``path`` holding ``data`` (mode 0600) only if it doesn't exist. + + A private temporary file is linked into place, which fails if another + process got there first, so no reader sees a half-written file. + """ + tmp = path.with_name(f".{path.name}.{os.getpid()}.{secrets.token_hex(4)}") + fd = open_binary(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + os.write(fd, data) + os.fsync(fd) + finally: + os.close(fd) + try: + os.link(tmp, path) + except FileExistsError: + return False + finally: + tmp.unlink() + return True + + +def _create_device(path: Path) -> str: + import pyrage + + _private_dir(path.parent) + text = str(pyrage.x25519.Identity.generate()) + choice = _store_choice() + why_not = "" + if choice != "file": + stored, why_not = _create_in_keychain(path, text) + if stored is not None: + return stored + if choice == "keychain": + raise LocalKeyError( + f"{KEY_STORE_ENV}=keychain, but {why_not}. Nothing was written." + ) + if not _link_new(path, (text + "\n").encode("ascii")): + return _read_secret(path) + if choice == "auto": + print( + f"WARNING: no OS keychain is available ({why_not}), so Flow keeps " + f"its device key in {path}, readable only by you. Back it up: what " + "it encrypts can't be read without it.", + file=sys.stderr, + ) + else: print( - f"Created a local encryption key for recordings, bundles and runs " + "Created a local encryption key for recordings, bundles and runs " f"at {path}. Back it up: what it encrypts can't be read without it.", file=sys.stderr, ) - return text + return text -#: Whether the default mode seals new recordings and bundles. Strict mode -#: always does. It turns on once every consumer reads sealed artifacts -#: (#1751); until then the default names and records each plaintext write. -DEFAULT_SEALS_ARTIFACTS: Final[bool] = False +def _create_in_keychain(path: Path, text: str) -> tuple[Optional[str], str]: + """Store a new key in the keychain. Returns ``(key, "")`` on success, or + ``(None, why)`` when the keychain can't hold it (nothing was claimed).""" + marker_file = path.with_name(MARKER_NAME) + store = _keychain() + account = _account() + service = store.service if isinstance(store, KeychainStore) else KEYCHAIN_SERVICE + try: + if store.get(account) is not None: + # An entry without a marker: left by a crash between the two, or + # by another tool. It may hold data's only key, so never replace it. + raise LocalKeyError( + f"The OS keychain already has an entry {service}/{account}, but " + f"{marker_file} is missing. Nothing was written. Restore the " + "marker from your backup, or remove the entry if nothing was " + "encrypted under it." + ) + except KeyStoreUnavailable as exc: + return None, str(exc) + marker = { + "schema": _MARKER_SCHEMA, + "store": "keychain", + "service": service, + "account": account, + "check": _check(text), + "created_at": time.time(), + } + body = (json.dumps(marker, indent=2, sort_keys=True) + "\n").encode("utf-8") + # The marker is claimed first: a second process waits for this key + # instead of writing its own over it. + if not _link_new(marker_file, body): + return _existing(path, wait=True), "" + try: + store.set(account, text) + back = store.get(account) + except KeyStoreUnavailable as exc: + marker_file.unlink(missing_ok=True) + return None, str(exc) + if back != text: + marker_file.unlink(missing_ok=True) + return None, "the OS keychain did not keep the key" + print( + "Created a local encryption key for recordings, bundles and runs at " + f"the OS keychain entry {service}. Back it up: what it encrypts can't " + "be read without it.", + file=sys.stderr, + ) + return text, "" + + +def key_location() -> Optional[str]: + """Where this home's key is kept, for messages: ``keychain``, a file path, + or None when there is no key yet. Reads no key material.""" + for path in (local_key_path(), device_key_path()): + if path.exists(): + return str(path) + if device_key_path().with_name(MARKER_NAME).exists(): + return "keychain" + return None + + +#: Whether the default mode seals new recordings, bundles and run +#: directories. Strict mode always does; ``OPENADAPT_ENCRYPT_AT_REST=0`` and +#: ``OPENADAPT_FLOW_PLAINTEXT_AT_REST`` turn it off, recorded. +DEFAULT_SEALS_ARTIFACTS: Final[bool] = True def seal_new(artifact: str, path: Path | str) -> bool: @@ -367,16 +760,23 @@ def seal_new(artifact: str, path: Path | str) -> bool: return False +def seals_by_default() -> bool: + """Whether new artifacts are sealed now, without recording anything: + strict mode, or the default mode without the opt-out.""" + return strict() or (DEFAULT_SEALS_ARTIFACTS and opt_out_reason() is None) + + def existing_key() -> Optional[str]: """The local key if it already exists, for read paths: creates nothing and records nothing. None when there is no local key yet.""" path = local_key_path() try: - if not path.exists(): - return None - return _read(path) + if path.exists(): + return _read(path) except OSError as exc: raise LocalKeyError(f"{path} can't be read ({exc}).") from exc + secret = device_secret(create=False) + return _derived_passphrase(secret) if secret is not None else None def default_key() -> Optional[str]: diff --git a/packages/flow/openadapt_flow/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py new file mode 100644 index 0000000000..a0273ad524 --- /dev/null +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -0,0 +1,129 @@ +"""``openadapt-flow at-rest``: who can open encrypted runs, and shredding them. + +- ``status`` prints where this computer's device key is kept, its public + recipient, the organization recipients new sets are wrapped for, and the + encryption mode. It prints no key material. +- ``share DIR --recipient age1...`` wraps an encrypted recording, bundle or + run for more recipients. No file is re-encrypted. +- ``shred DIR --yes`` deletes every wrapped key of an encrypted set, which + makes it unreadable by anyone. It can't be undone. + +See docs/phi_at_rest.md. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + + +def _cmd_status(args: argparse.Namespace) -> int: + from openadapt_flow import at_rest, envelope + + try: + org = envelope.org_recipients() + device = envelope.device_identity(create=False) + mode = ( + "strict" + if at_rest.strict() + else ("off" if at_rest.opt_out_reason() is not None else "on") + ) + except (envelope.EnvelopeError, at_rest.LocalKeyError, ValueError) as exc: + print(f"at-rest: {exc}", file=sys.stderr) + return 2 + status = { + "encryption": mode, + "configured_key": at_rest.explicit_key(), + "device_key": at_rest.key_location(), + "device_recipient": envelope.device_recipient(device) if device else None, + "org_recipients": org, + "policy_file": str(envelope.policy_path()), + } + if args.json: + print(json.dumps(status, indent=2, sort_keys=True)) + return 0 + print(f"Encryption at rest: {mode}") + print(f"Device key: {status['device_key'] or 'not created yet'}") + if status["device_recipient"]: + print(f"Device recipient: {status['device_recipient']}") + print("Organization recipients: " + (", ".join(org) if org else "none")) + if status["configured_key"]: + print("A configured key (OPENADAPT_BUNDLE_KEY) is also a recipient.") + return 0 + + +def _cmd_share(args: argparse.Namespace) -> int: + from openadapt_flow import envelope, sealed_set + + try: + recipients = sealed_set.add_recipients(Path(args.dir), list(args.recipient)) + except (sealed_set.SealedSetError, envelope.EnvelopeError) as exc: + print(f"at-rest share: {exc}", file=sys.stderr) + return 2 + print(f"{args.dir} is now wrapped for {len(recipients)} recipient(s):") + for item in recipients: + print(f" {item}") + return 0 + + +def _cmd_shred(args: argparse.Namespace) -> int: + from openadapt_flow import sealed_set + + root = Path(args.dir) + if not sealed_set.is_sealed(root): + print(f"at-rest shred: {root} is not an encrypted set", file=sys.stderr) + return 2 + if not args.yes: + print( + f"at-rest shred: this makes {root} unreadable for everyone, and it " + "can't be undone. Pass --yes to do it.", + file=sys.stderr, + ) + return 2 + try: + removed = sealed_set.shred(root) + except sealed_set.SealedSetError as exc: + print(f"at-rest shred: {exc}", file=sys.stderr) + return 2 + print( + f"Shredded {root}: its wrapped keys are deleted, so nobody can open it" + + (f"; also deleted {len(removed)} checkpoint file(s)." if removed else ".") + ) + return 0 + + +def register(sub: argparse._SubParsersAction) -> None: + p = sub.add_parser( + "at-rest", + help=( + "Encryption at rest: show this computer's device key and recipients, " + "share an encrypted run with another recipient, or crypto-shred it" + ), + allow_abbrev=False, + ) + rsub = p.add_subparsers(dest="at_rest_cmd", required=True) + s = rsub.add_parser( + "status", help="Where the key is kept and who can read new runs" + ) + s.add_argument("--json", action="store_true") + s.set_defaults(func=_cmd_status) + s = rsub.add_parser( + "share", help="Wrap an encrypted recording, bundle or run for more recipients" + ) + s.add_argument("dir", help="The encrypted directory") + s.add_argument( + "--recipient", + action="append", + required=True, + metavar="AGE1...", + help="An age X25519 recipient (repeat for more)", + ) + s.set_defaults(func=_cmd_share) + s = rsub.add_parser( + "shred", help="Delete an encrypted set's wrapped keys; nobody can open it after" + ) + s.add_argument("dir", help="The encrypted directory") + s.add_argument("--yes", action="store_true", help="Confirm; this can't be undone") + s.set_defaults(func=_cmd_shred) diff --git a/packages/flow/openadapt_flow/demo_proof.py b/packages/flow/openadapt_flow/demo_proof.py index b76c802e44..390d40d0b5 100644 --- a/packages/flow/openadapt_flow/demo_proof.py +++ b/packages/flow/openadapt_flow/demo_proof.py @@ -222,7 +222,9 @@ def showed_the_difference(self) -> bool: def _sha256(path: Path) -> str: - return hashlib.sha256(path.read_bytes()).hexdigest() + from openadapt_flow import sealed_set + + return hashlib.sha256(sealed_set.read_bytes(path)).hexdigest() def png_size(path: Optional[Path]) -> Optional[tuple[int, int]]: @@ -245,13 +247,14 @@ def png_size(path: Optional[Path]) -> Optional[tuple[int, int]]: def _load_report(run_dir: Path) -> Any: + from openadapt_flow import sealed_set from openadapt_flow.ir import RunReport path = run_dir / "report.json" - if not path.is_file(): - return None try: - return RunReport.model_validate_json(path.read_text(encoding="utf-8")) + if not sealed_set.is_file(path): + return None + return RunReport.model_validate_json(sealed_set.read_text(path)) except (OSError, ValueError): return None @@ -265,6 +268,11 @@ def _safe_child(run_dir: Path, relative: Optional[str]) -> Optional[Path]: if rel.is_absolute() or ".." in rel.parts: return None candidate = run_dir / rel + from openadapt_flow import sealed_set + + if sealed_set.is_sealed_path(run_dir): + # Encrypted run: the frame is a file of the verified set. + return candidate if sealed_set.is_file(candidate) else None return candidate if candidate.is_file() and not candidate.is_symlink() else None @@ -771,6 +779,16 @@ def _frame_figure(run: RunEvidence, alt: str, root: Path) -> str: same pixels the identical-screens check hashed. """ + from openadapt_flow import sealed_set + + if run.final_screenshot is not None and sealed_set.is_sealed_path( + run.final_screenshot + ): + # The page is plaintext; the run's screenshots stay encrypted. + return ( + '
The final screen is encrypted on ' + "disk with this run.
" + ) image = _data_uri(run.final_screenshot) if image is None: return ( diff --git a/packages/flow/openadapt_flow/desktop_record.py b/packages/flow/openadapt_flow/desktop_record.py index e2f6191c81..1f4cd06352 100644 --- a/packages/flow/openadapt_flow/desktop_record.py +++ b/packages/flow/openadapt_flow/desktop_record.py @@ -260,6 +260,7 @@ def record_desktop_capture( recorder_factory: Optional[RecorderFactory] = None, convert: Optional[ConvertFn] = None, stop: Optional[Callable[[], bool]] = None, + encryption_key: Optional[str] = None, announce: bool = True, ) -> Path: """Record a live desktop demonstration and convert it to a recording. @@ -339,8 +340,86 @@ def record_desktop_capture( out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) + final_dir = out_dir + staging: Optional[Path] = None + if encryption_key: + # The converted recording is sealed into out_dir; the raw session and + # the converter's plaintext output live beside it, privately, only + # until they are sealed and deleted. + import secrets + + staging = out_dir.parent / f".{out_dir.name}.plain-{secrets.token_hex(4)}" + staging.mkdir(mode=0o700) + out_dir = staging / "recording" + out_dir.mkdir() + if capture_dir is None: + capture_dir = staging / "capture" cap_dir = Path(capture_dir) if capture_dir is not None else out_dir / ".capture" cap_dir.mkdir(parents=True, exist_ok=True) + try: + recording = _capture_and_convert( + recorder_factory=recorder_factory, + convert=convert, + announce=announce, + task_description=task_description, + stop=stop, + cap_dir=cap_dir, + out_dir=out_dir, + params=params, + ready_timeout_s=ready_timeout_s, + backend_kind=backend_kind, + identifier_region=identifier_region, + replay_window=replay_window, + replay_window_title=replay_window_title, + readiness_text=readiness_text, + window=window, + ) + if staging is None: + return recording + _seal_recording(Path(recording), final_dir, encryption_key) # type: ignore[arg-type] + return final_dir + finally: + if staging is not None: + import shutil + + shutil.rmtree(staging, ignore_errors=True) + + +def _seal_recording(plain: Path, dest: Path, key: str) -> None: + """Encrypt a converted recording into ``dest`` (a sealed set).""" + from openadapt_flow import sealed_set + + if dest.exists() and any(dest.iterdir()): + raise sealed_set.SealedSetError( + f"{dest} is not empty; record into a new directory" + ) + with sealed_set.writing(dest, "recording", key) as writer: + for path in sorted(p for p in plain.rglob("*") if p.is_file()): + rel = path.relative_to(plain).as_posix() + if rel.startswith(".capture/"): + continue + writer.write(rel, path.read_bytes()) + + +def _capture_and_convert( + *, + recorder_factory: Optional[RecorderFactory], + convert: Optional[ConvertFn], + announce: bool, + task_description: str, + stop: Optional[Callable[[], bool]], + cap_dir: Path, + out_dir: Path, + params: Optional[dict[str, str]], + ready_timeout_s: float, + backend_kind: Optional[str], + identifier_region: Optional[tuple[int, int, int, int]], + replay_window: Optional[str], + replay_window_title: Optional[str], + readiness_text: Optional[str], + window: Optional[dict[str, Optional[str]]], +) -> Any: + """Run the capture session, then convert it into ``out_dir``.""" # Injected factories keep the tested 2-arg ``(task, capture_dir)`` shape; # the DEFAULT factory carries the window spec through to the capture diff --git a/packages/flow/openadapt_flow/envelope.py b/packages/flow/openadapt_flow/envelope.py new file mode 100644 index 0000000000..7c86d2a3f0 --- /dev/null +++ b/packages/flow/openadapt_flow/envelope.py @@ -0,0 +1,255 @@ +"""Who can open an encrypted recording, bundle or run: its recipients. + +Every sealed set (:mod:`openadapt_flow.sealed_set`) has its own random data +key (DEK). The files are encrypted under the DEK, and the DEK is *wrapped* +for each recipient in the set's header. Format version 3 wraps it with age +(https://age-encryption.org, through ``pyrage``, X25519 recipients): + +* **The device recipient** (the default). An age identity Flow creates on + this computer on first use and keeps in the OS keychain (macOS Keychain, + Windows Credential Manager with DPAPI, Linux Secret Service), or in a 0600 + file with a warning where no keychain works (:mod:`openadapt_flow.at_rest`). + It lets the computer that recorded a run replay and view it. +* **Organization recipients** (optional). Public age recipients (``age1...``) + from ``OPENADAPT_ORG_RECIPIENTS`` or a policy file + (``OPENADAPT_POLICY_FILE``, default ``$OPENADAPT_HOME/policy.json``, key + ``"recipients"``) that IT or MDM can place. The organization's reviewers + hold the private key in their own KMS, HSM or age plugin; Flow never sees + it. A reviewer opens a set with ``OPENADAPT_AGE_IDENTITY_FILE``. +* **Share recipients**, added later by :func:`add_recipients`, which rewraps + the same DEK without re-encrypting any file. + +A configured passphrase (``OPENADAPT_BUNDLE_KEY`` or +``OPENADAPT_RECORDING_KEY``) is a legacy recipient: with it, and no +organization recipient, Flow writes the version 2 header it always wrote. + +:func:`shred` deletes a set's wrapped keys (and the durable checkpoints that +another store encrypted inside it). With them gone the ciphertext can't be +opened by anyone: this is the crypto-shredding retention primitive. + +OpenAdapt Cloud never holds a key, a wrapped key or recovery material. + +A device-written header also carries ``device_mac``, an HMAC under a key +derived from the device identity, over the whole header. age has no sender +authentication, so without it anyone who knows the public device recipient +could write a set this computer would open. The device refuses a header that +names it but lacks a valid MAC. + +The provider layer is deliberately thin: :func:`device_identity` and +:func:`org_recipients` are the only places that decide who the recipients +are. +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import os +from pathlib import Path +from typing import Any, Final, Optional, Sequence + +ORG_RECIPIENTS_ENV: Final[str] = "OPENADAPT_ORG_RECIPIENTS" +POLICY_FILE_ENV: Final[str] = "OPENADAPT_POLICY_FILE" +IDENTITY_FILE_ENV: Final[str] = "OPENADAPT_AGE_IDENTITY_FILE" +_WRAP_SCHEMA: Final[str] = "openadapt.flow.wrapped-dek/v3" +_MAC_LABEL: Final[bytes] = b"openadapt-flow/sealed-set/device-mac/v3" + + +class EnvelopeError(ValueError): + """A recipient is malformed, or no recipient this computer holds opens a set.""" + + +def _pyrage() -> Any: + try: + import pyrage + except ImportError as exc: # pragma: no cover - a core dependency + raise EnvelopeError( + "pyrage is not installed, so Flow can't open or write version 3 " + "encrypted sets. Reinstall openadapt-flow." + ) from exc + return pyrage + + +# -- recipients ---------------------------------------------------------------- + + +def parse_recipient(text: str) -> Any: + """An age X25519 recipient, or :class:`EnvelopeError`.""" + pyrage = _pyrage() + try: + return pyrage.x25519.Recipient.from_str(text.strip()) + except Exception as exc: # noqa: BLE001 - pyrage raises several types + raise EnvelopeError( + f"{text.strip()[:12]}... is not an age recipient (age1...)" + ) from exc + + +def _home() -> Path: + root = os.environ.get("OPENADAPT_HOME") + return Path(root) if root else Path.home() / ".openadapt" + + +def policy_path() -> Path: + configured = os.environ.get(POLICY_FILE_ENV) + return Path(configured) if configured else _home() / "policy.json" + + +def org_recipients() -> list[str]: + """The organization's public recipients, from the environment and the + policy file. A malformed entry raises: an org recipient that is silently + skipped is evidence the organization can't read later.""" + found: list[str] = [] + raw = os.environ.get(ORG_RECIPIENTS_ENV) or "" + found += [item for item in raw.replace(",", " ").split() if item] + path = policy_path() + if path.is_file(): + try: + policy = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise EnvelopeError(f"{path} is not a readable policy file") from exc + listed = policy.get("recipients", []) if isinstance(policy, dict) else None + if not isinstance(listed, list) or not all(isinstance(r, str) for r in listed): + raise EnvelopeError(f"{path}: 'recipients' must be a list of age1... keys") + found += listed + out: list[str] = [] + for item in found: + text = str(parse_recipient(item)) + if text not in out: + out.append(text) + return out + + +# -- identities ---------------------------------------------------------------- + + +def device_identity(*, create: bool) -> Optional[str]: + """This computer's age identity (``AGE-SECRET-KEY-1...``), created on first + use when ``create``. None when there is none and ``create`` is False.""" + from openadapt_flow import at_rest + + return at_rest.device_secret(create=create) + + +def device_recipient(identity: str) -> str: + return str(_pyrage().x25519.Identity.from_str(identity).to_public()) + + +def _extra_identities() -> list[Any]: + """Identities a reviewer configured (``OPENADAPT_AGE_IDENTITY_FILE``).""" + path = os.environ.get(IDENTITY_FILE_ENV) + if not path: + return [] + pyrage = _pyrage() + try: + lines = Path(path).read_text(encoding="utf-8").splitlines() + except OSError as exc: + raise EnvelopeError(f"{IDENTITY_FILE_ENV}: {path} can't be read") from exc + out = [] + for line in lines: + line = line.strip() + if line and not line.startswith("#"): + try: + out.append(pyrage.x25519.Identity.from_str(line)) + except Exception as exc: # noqa: BLE001 + raise EnvelopeError( + f"{IDENTITY_FILE_ENV}: {path} holds a line that is not an age " + "identity" + ) from exc + return out + + +# -- wrapping ------------------------------------------------------------------ + + +def _binding(header: dict[str, Any]) -> dict[str, Any]: + return { + "schema": _WRAP_SCHEMA, + "kind": header["kind"], + "data_key_id": header["data_key_id"], + } + + +def wrap(dek: bytes, header: dict[str, Any], recipients: Sequence[str]) -> str: + """The DEK sealed by age to ``recipients``, bound to the set's identity.""" + pyrage = _pyrage() + payload = json.dumps( + {**_binding(header), "dek": base64.b64encode(dek).decode("ascii")}, + sort_keys=True, + ).encode("utf-8") + parsed = [parse_recipient(r) for r in recipients] + return base64.b64encode(pyrage.encrypt(payload, parsed)).decode("ascii") + + +def unwrap(header: dict[str, Any]) -> Optional[bytes]: + """The DEK, through the device identity or a configured reviewer identity. + None when no identity this computer holds is a recipient.""" + wrapped = header.get("age") + if not isinstance(wrapped, str): + return None + identities = _extra_identities() + device = device_identity(create=False) + device_rcpt: Optional[str] = None + pyrage = _pyrage() + if device is not None: + device_rcpt = device_recipient(device) + if device_rcpt in (header.get("recipients") or []): + check_device_mac(header, device) + identities.insert(0, pyrage.x25519.Identity.from_str(device)) + if not identities: + return None + try: + payload = pyrage.decrypt(base64.b64decode(wrapped, validate=True), identities) + except Exception: # noqa: BLE001 - not a recipient, or damaged + return None + try: + body = json.loads(payload) + dek = base64.b64decode(body["dek"], validate=True) + except (ValueError, KeyError, TypeError) as exc: + raise EnvelopeError("the wrapped data key is malformed") from exc + if {k: body.get(k) for k in _binding(header)} != _binding(header) or len(dek) != 32: + raise EnvelopeError("the wrapped data key belongs to another set") + return dek + + +# -- the device MAC ------------------------------------------------------------ + + +def _mac_key(identity: str) -> bytes: + return hmac.new(identity.encode("ascii"), _MAC_LABEL, hashlib.sha256).digest() + + +def _mac_body(header: dict[str, Any]) -> bytes: + body = {k: v for k, v in header.items() if k not in ("device_mac", "set_digest")} + return json.dumps(body, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def device_mac(header: dict[str, Any], identity: str) -> str: + return hmac.new(_mac_key(identity), _mac_body(header), hashlib.sha256).hexdigest() + + +def check_device_mac(header: dict[str, Any], identity: str) -> None: + """Refuse a header that names this device but that it did not write.""" + got = header.get("device_mac") + if not isinstance(got, str) or not hmac.compare_digest( + got, device_mac(header, identity) + ): + raise EnvelopeError( + "this encrypted set names this computer as a recipient, but its " + "header was not written here (device MAC missing or wrong)" + ) + + +__all__ = [ + "EnvelopeError", + "check_device_mac", + "device_identity", + "device_mac", + "device_recipient", + "org_recipients", + "parse_recipient", + "policy_path", + "unwrap", + "wrap", +] diff --git a/packages/flow/openadapt_flow/hosted.py b/packages/flow/openadapt_flow/hosted.py index 4acdd590ba..1d7e60696c 100644 --- a/packages/flow/openadapt_flow/hosted.py +++ b/packages/flow/openadapt_flow/hosted.py @@ -1765,19 +1765,23 @@ def report_break( from openadapt_flow.ir import RunReport run_path = Path(run_dir) + from openadapt_flow import sealed_set + report_path = run_path / "report.json" - if not report_path.is_file(): - raise HostedError(f"No report.json in {run_path} — nothing to report.") try: - report_size = report_path.stat().st_size - except OSError as exc: + # An encrypted run directory is read in memory (docs/phi_at_rest.md). + if not sealed_set.is_file(report_path): + raise HostedError(f"No report.json in {run_path} — nothing to report.") + report_bytes = sealed_set.read_bytes(report_path) + except (OSError, sealed_set.SealedSetError) as exc: raise HostedError("Could not inspect report.json") from exc + report_size = len(report_bytes) if report_size > _MAX_RUN_REPORT_BYTES: raise HostedError( f"report.json exceeds the {_MAX_RUN_REPORT_BYTES}-byte reporting limit" ) try: - report = RunReport.model_validate_json(report_path.read_text(encoding="utf-8")) + report = RunReport.model_validate_json(report_bytes.decode("utf-8")) except (OSError, ValueError) as exc: raise HostedError("report.json is unreadable or invalid") from exc @@ -2425,13 +2429,17 @@ def report_run( from openadapt_flow.ir import RunReport run_path = Path(run_dir) + from openadapt_flow import sealed_set + report_path = run_path / "report.json" - if not report_path.is_file(): - raise HostedError(f"No report.json in {run_path} — nothing to report.") try: - report_size = report_path.stat().st_size - except OSError as exc: + # An encrypted run directory is read in memory (docs/phi_at_rest.md). + if not sealed_set.is_file(report_path): + raise HostedError(f"No report.json in {run_path} — nothing to report.") + report_bytes = sealed_set.read_bytes(report_path) + except (OSError, sealed_set.SealedSetError) as exc: raise HostedError("Could not inspect report.json") from exc + report_size = len(report_bytes) if report_size > _MAX_RUN_REPORT_BYTES: raise HostedError( f"report.json exceeds the {_MAX_RUN_REPORT_BYTES}-byte reporting limit" diff --git a/packages/flow/openadapt_flow/offline_seal.py b/packages/flow/openadapt_flow/offline_seal.py index 7d03054e9d..0210f90713 100644 --- a/packages/flow/openadapt_flow/offline_seal.py +++ b/packages/flow/openadapt_flow/offline_seal.py @@ -403,10 +403,14 @@ def seal_run( credential (:mod:`openadapt_flow.report_redaction`), unless ``allow_unredacted``: a Seal makes a report shareable. """ + from openadapt_flow import sealed_set + run_dir = Path(run_dir) report_path = run_dir / "report.json" try: - raw = report_path.read_bytes() + # The receipt covers the plaintext report bytes, in an encrypted run + # directory too (docs/phi_at_rest.md, "Receipts"). + raw = sealed_set.read_bytes(report_path) report = loads_strict(raw.decode("utf-8")) except (OSError, UnicodeDecodeError, ValueError) as exc: raise LocalSealError("report_unreadable", str(report_path)) from exc @@ -473,11 +477,7 @@ def seal_after_run( return None from openadapt_flow import sealed_set - if sealed_set.is_sealed(Path(run_dir)): - # The offline Seal rewrites report.json in place; that is not built - # for an encrypted run directory yet, so say so instead of skipping. - return "offline seal not written: the run directory is encrypted at rest" - if not (Path(run_dir) / "report.json").is_file(): + if not sealed_set.is_file(Path(run_dir) / "report.json"): return None try: home = seal_home(env) @@ -611,7 +611,8 @@ def _check_authorization( from openadapt_flow.run_authorization import check_run try: - report = loads_strict(report_path.read_bytes()) # the bytes the Seal covers + # The bytes the receipt covers: the plaintext, decrypted in memory. + report = loads_strict(_report_bytes(report_path)) except (OSError, ValueError): return dataclasses.replace(found, ok=False, reason="malformed") problem = check_run(LocalSealV1.model_validate(seal).wire(), report, auth) @@ -642,6 +643,26 @@ def _started_epoch(value: Any) -> Optional[int]: return int(when.timestamp()) +def _report_bytes(path: Path) -> bytes: + """A run report's plaintext bytes, decrypted in memory when the run + directory is encrypted.""" + from openadapt_flow import sealed_set + + try: + return sealed_set.read_bytes(path) + except sealed_set.SealedSetError as exc: + raise OSError(str(exc)) from exc + + +def _report_is_file(path: Path) -> bool: + from openadapt_flow import sealed_set + + try: + return sealed_set.is_file(path) + except sealed_set.SealedSetError: + return path.is_file() + + def verify_run( run_dir: Path, registry: Sequence[SealPublicKey], @@ -678,9 +699,9 @@ def verify_run( strict = strict or require_anchor for name in ("report.json",) if strict else ("report.json", "report.pre-seal.json"): path = run_dir / name - if not path.is_file(): + if not _report_is_file(path): continue - digest = hashlib.sha256(path.read_bytes()).hexdigest() + digest = hashlib.sha256(_report_bytes(path)).hexdigest() result = verify_local_seal(seal, digest, registry) if result.reason == "subject_mismatch": continue diff --git a/packages/flow/openadapt_flow/public_seal.py b/packages/flow/openadapt_flow/public_seal.py index 66d0422536..bdb00207dc 100644 --- a/packages/flow/openadapt_flow/public_seal.py +++ b/packages/flow/openadapt_flow/public_seal.py @@ -284,9 +284,16 @@ def _verified_private_seal(run_dir: Path) -> tuple[LocalSealV1, dict[str, Any]]: _check_signature(seal) for name in ("report.json", "report.pre-seal.json"): path = run_dir / name - if not path.is_file(): + from openadapt_flow.offline_seal import _report_bytes, _report_is_file + + if not _report_is_file(path): continue - raw = path.read_bytes() + # The card's report_sha256 is the receipt's subject: the digest of the + # plaintext report, decrypted in memory when the run is encrypted. + try: + raw = _report_bytes(path) + except OSError as exc: + raise PublicSealError("report_unreadable", str(path)) from exc if hashlib.sha256(raw).hexdigest() != seal.subject_sha256: continue try: diff --git a/packages/flow/openadapt_flow/records/run.py b/packages/flow/openadapt_flow/records/run.py index 64b714eb81..0272f18118 100644 --- a/packages/flow/openadapt_flow/records/run.py +++ b/packages/flow/openadapt_flow/records/run.py @@ -109,8 +109,11 @@ def write_sealed_reads(report: Any, receipt_json: Path | str) -> Optional[Path]: out = Path(receipt_json).parent / "records.json" import json - out.write_text( - json.dumps([r.model_dump(mode="json") for r in sealed], indent=2) + "\n", - encoding="utf-8", + from openadapt_flow import sealed_set + + # The values read are record data: encrypted when written beside an + # encrypted run (a "*" run file), plaintext otherwise. + sealed_set.write_text( + out, json.dumps([r.model_dump(mode="json") for r in sealed], indent=2) + "\n" ) return out diff --git a/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py b/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py index 90ada7c526..d2262a409f 100644 --- a/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py +++ b/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py @@ -172,7 +172,21 @@ def run_with_output( # Strict mode seals the run of a plaintext bundle too. Otherwise the # plaintext run directory is named on stderr and in the ledger # (docs/phi_at_rest.md). - seal_run = at_rest.strict() or bundle_sealed + # By default (docs/phi_at_rest.md) every run directory is sealed too. + seal_run = at_rest.strict() or bundle_sealed or at_rest.seals_by_default() + downgraded = False + if seal_run and not at_rest.strict() and not at_rest.explicit_key(): + # Under this computer's own key, a run feature whose state can't be + # sealed yet runs in plaintext, named on stderr and in the ledger, + # rather than being refused. Strict mode and a configured key refuse. + held = ( + "a healed bundle (--save-healed-to)" + if save_healed_to is not None + else replayer._sealed_run_unsupported(workflow) + ) + if held is not None: + at_rest.unsealed_write(f"a run directory with {held}", run_dir) + seal_run, downgraded = False, True if save_healed_to is not None and seal_run: # The healed copy is written as a plaintext bundle: hold it back # before anything runs rather than decrypt a sealed bundle to disk. @@ -183,7 +197,13 @@ def run_with_output( run_path = Path(run_dir) passphrase = None if seal_run and _sealed.active_writer(run_path) is None: - passphrase = _sealed.passphrase_for("bundle") + from openadapt_flow import crypto as _crypto_keys + + # Under the opt-out an existing key still seals the run of a sealed + # bundle: encrypted input never yields plaintext output. + passphrase = _sealed.passphrase_for("bundle") or _crypto_keys.resolve_read_key( + None + ) if not passphrase: raise _sealed.SealedSetKeyError( _sealed.missing_key_message(bundle_path, "bundle") @@ -218,7 +238,7 @@ def run_with_output( if first_local_delivery: ownership.enter_context(local_delivery_owner(run_path)) if passphrase is None: - if _sealed.active_writer(run_path) is None: + if _sealed.active_writer(run_path) is None and not downgraded: if not at_rest.plaintext_allowed("a run directory"): at_rest.unsealed_write("a run directory", run_dir) if replayer.checkpoint_key is None: diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index 9416f65096..c7320f1e91 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -64,13 +64,18 @@ FORMAT: Final[str] = "openadapt-flow-sealed-set" FORMAT_VERSION: Final[int] = 1 SEALED_SUFFIX: Final[str] = ".enc" +#: Format version 3: a random data key wrapped for recipients +#: (:mod:`openadapt_flow.envelope`). +ENVELOPE_VERSION: Final[int] = 3 _LEGACY_DERIVATION_FIELDS: Final[frozenset[str]] = frozenset( {"salt", "kdf", "kdf_n", "kdf_r", "kdf_p"} ) Kind = Literal["bundle", "recording", "run", "library", "sanitized"] Codec = Literal["set", "plain", "external"] -Classification = Literal["phi", "structural"] +#: ``export`` is a plaintext file a person asked for (the receipt page), +#: kept beside an encrypted run and recorded in the plaintext ledger. +Classification = Literal["phi", "structural", "export"] _INDEX_AAD: Final[bytes] = b"openadapt-flow/sealed-set/index/" _FILE_AAD: Final[bytes] = b"openadapt-flow/sealed-set/file/" @@ -264,6 +269,24 @@ class FileKind: ), FileKind(".attended_action.lease", "structural", "an action lease marker"), FileKind("*.lock", "structural", "a lock file"), + # The receipt files stay readable without the key: they hold signatures, + # outcomes, counts and SHA-256 digests over the plaintext report.json, + # never its contents (docs/phi_at_rest.md, "Receipts"). + FileKind("seal.json", "structural", "the signed run receipt over report.json"), + FileKind("seal.anchor.json", "structural", "the receipt's transparency-log proof"), + FileKind("seal.tsa.json", "structural", "the receipt's timestamp record"), + FileKind("seal.tsr", "structural", "the receipt's RFC 3161 timestamp token"), + FileKind("seal.publish.json", "structural", "where the public receipt was posted"), + FileKind("public-seal.json", "structural", "the allow-listed public card"), + 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"), + FileKind( + "seal.html", + "export", + "the receipt page a person opens; it embeds report.json, so it is a " + "plaintext copy of the run's inputs, named on stderr and in the ledger", + ), FileKind("checkpoints/*", "phi", "durable checkpoints (already encrypted)"), FileKind( "*", @@ -365,11 +388,19 @@ def missing_key_message(root: Path | str, kind: str) -> str: ) -def _require_passphrase(root: Path, kind: str, key: Optional[str]) -> str: - resolved = passphrase_for(kind, key) - if not resolved: - raise SealedSetKeyError(missing_key_message(root, kind)) - return resolved +def _require_passphrase(root: Path, kind: str, key: Optional[str]) -> Optional[str]: + """The passphrase to open ``root`` with. A version 3 set needs none (its + recipients may be this computer's device identity), so None is allowed + there; an older set without a passphrase refuses here.""" + resolved = passphrase_for(kind, key) or crypto.resolve_read_key(None) + if resolved: + return resolved + try: + if read_header(root).get("version") == ENVELOPE_VERSION: + return None + except SealedSetError: + pass + raise SealedSetKeyError(missing_key_message(root, kind)) def _file_aad(kind: str, rel: str) -> bytes: @@ -461,7 +492,7 @@ def read_header(root: Path | str) -> dict[str, object]: raise SealedSetError(f"unreadable sealed-set header: {exc}") from exc if not isinstance(header, dict) or header.get("format") != FORMAT: raise SealedSetError("not an openadapt-flow sealed set") - if header.get("version") not in (FORMAT_VERSION, 2): + if header.get("version") not in (FORMAT_VERSION, 2, ENVELOPE_VERSION): raise SealedSetError( f"sealed-set format version {header.get('version')!r} is not supported" ) @@ -482,8 +513,60 @@ def _wrapping_aad(header: dict[str, object]) -> bytes: ).encode("utf-8") -def _data_key(header: dict[str, object], passphrase: str) -> bytes: +def _passphrase_aad(header: dict[str, object]) -> bytes: + return b"openadapt-flow/sealed-set/passphrase-wrap/v3\0" + json.dumps( + {name: header[name] for name in ("format", "version", "kind", "data_key_id")}, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + + +def _envelope_data_key(header: dict[str, object], passphrase: Optional[str]) -> bytes: + """A version 3 set's DEK: through this computer's device identity or a + reviewer identity, else the legacy passphrase recipient.""" + from openadapt_flow import envelope + + if header.get("shredded"): + raise SealedSetError( + "this encrypted set was shredded: its wrapped keys were deleted, so " + "nobody can open it" + ) + data_key_id = header.get("data_key_id") + if not isinstance(data_key_id, str) or len(data_key_id) != 32: + raise SealedSetError("sealed-set envelope metadata is malformed") + try: + dek = envelope.unwrap(dict(header)) + except envelope.EnvelopeError as exc: + raise SealedSetError(str(exc)) from exc + if dek is not None: + return dek + wrapped = header.get("passphrase") + if passphrase and isinstance(wrapped, str): + try: + dek = crypto.decrypt_bytes( + base64.b64decode(wrapped, validate=True), + passphrase, + aad=_passphrase_aad(header), + ) + except ValueError as exc: + raise SealedSetError("sealed-set passphrase wrap is malformed") from exc + if len(dek) == 32: + return dek + raise SealedSetKeyError( + "no key on this computer opens this encrypted set: it is wrapped for " + + (", ".join(str(r) for r in header.get("recipients") or []) or "no one") # type: ignore[union-attr] + + (" and a passphrase" if isinstance(wrapped, str) else "") + + ". Set OPENADAPT_AGE_IDENTITY_FILE to a recipient's identity, or the " + "passphrase it was sealed with. Nothing was read." + ) + + +def _data_key(header: dict[str, object], passphrase: Optional[str]) -> bytes: """Unwrapped data keys stay in memory; no fallback key resolution here.""" + if header.get("version") == ENVELOPE_VERSION: + return _envelope_data_key(header, passphrase) + if not passphrase: + raise SealedSetKeyError("no key is configured to open this sealed set") try: if header.get("version") == 2: wrapped = header.get("wrapped_key") @@ -519,7 +602,7 @@ def _data_key(header: dict[str, object], passphrase: str) -> bytes: raise SealedSetError("sealed-set key header is malformed") from exc -def _derive(header: dict[str, object], passphrase: str) -> crypto.SetKey: +def _derive(header: dict[str, object], passphrase: Optional[str]) -> crypto.SetKey: return crypto.SetKey(_data_key(header, passphrase)) @@ -658,7 +741,7 @@ def _adoptable(root: Path, kind: str, rel: str) -> Optional[Codec]: ``plain`` for a structural file the inventory names, ``external`` for ciphertext of another keyed store, ``None`` for plaintext (refused).""" entry = classify(kind, rel) # type: ignore[arg-type] - if entry is not None and entry.classification == "structural": + if entry is not None and entry.classification in ("structural", "export"): return "plain" if crypto.is_encrypted((root / rel).read_bytes()): return "external" @@ -704,6 +787,70 @@ def _reconcile_run_files( # -- writing ----------------------------------------------------------------- +def _explicit_passphrase(passphrase: Optional[str]) -> bool: + """Whether ``passphrase`` is a configured key rather than this computer's + local one (which the device recipient replaces in a version 3 set).""" + if not passphrase: + return False + from openadapt_flow import at_rest + + return passphrase != at_rest.existing_key() + + +def _new_envelope( + kind: str, passphrase: Optional[str] +) -> Optional[tuple[dict[str, object], bytes, Optional[str]]]: + """A version 3 header for a new set, its DEK and the device identity that + MACs it; None for a configured passphrase with no organization recipient + (the version 1 header Flow always wrote).""" + from openadapt_flow import envelope + + try: + org = envelope.org_recipients() + except envelope.EnvelopeError as exc: + raise SealedSetError(f"Not writing an encrypted {kind}: {exc}") from exc + explicit = _explicit_passphrase(passphrase) + if explicit and not org: + return None + device: Optional[str] = None + recipients: list[str] = [] + if not explicit: + device = envelope.device_identity(create=True) + assert device is not None + recipients.append(envelope.device_recipient(device)) + recipients += [r for r in org if r not in recipients] + dek = secrets.token_bytes(32) + header: dict[str, object] = { + "format": FORMAT, + "version": ENVELOPE_VERSION, + "kind": kind, + "cipher": "AES-256-GCM", + "wrap": "age-x25519", + "data_key_id": secrets.token_hex(16), + "recipients": recipients, + } + header["age"] = envelope.wrap(dek, header, recipients) + if explicit: + header["passphrase"] = base64.b64encode( + crypto.encrypt_bytes(dek, passphrase, aad=_passphrase_aad(header)) + ).decode("ascii") + return header, dek, device + + +def _own_device(header: dict[str, object]) -> Optional[str]: + """This computer's device identity when ``header`` names it.""" + if header.get("version") != ENVELOPE_VERSION: + return None + from openadapt_flow import envelope + + device = envelope.device_identity(create=False) + if device is None: + return None + if envelope.device_recipient(device) in (header.get("recipients") or []): # type: ignore[operator] + return device + return None + + class SealedSetWriter: """Write a sealed set file by file, ciphertext only, then finalize it. @@ -718,13 +865,14 @@ def __init__( self, root: Path | str, kind: Kind, - passphrase: str, + passphrase: Optional[str], *, resume: bool = False, ) -> None: self.root = Path(root) self.kind: Kind = kind self._codecs: dict[str, Codec] = {} + self._device: Optional[str] = None self._hashes: dict[str, str] = {} self._lines: dict[str, list[bytes]] = {} self._lock = threading.RLock() @@ -732,12 +880,13 @@ def __init__( with mutation_lock(self.root): self._initialize(passphrase, resume=resume) - def _initialize(self, passphrase: str, *, resume: bool) -> None: + def _initialize(self, passphrase: Optional[str], *, resume: bool) -> None: kind = self.kind if resume and is_sealed(self.root): opened = SealedSet.open(self.root, passphrase, expect=kind) self._header: dict[str, object] = dict(opened._header) self._key = opened._key + self._device = _own_device(self._header) self._header_revision = _sha256((self.root / HEADER).read_bytes()) for rel, entry in opened._files.items(): self._codecs[rel] = entry["codec"] # type: ignore[assignment] @@ -746,6 +895,14 @@ def _initialize(self, passphrase: str, *, resume: bool) -> None: if is_sealed(self.root): raise SealedSetError(f"{self.root} is already a sealed set") self.root.mkdir(parents=True, exist_ok=True) + envelope_header = _new_envelope(kind, passphrase) + if envelope_header is not None: + self._header, dek, self._device = envelope_header + self._key = crypto.SetKey(dek) + self._write_header() + return + if not passphrase: + raise SealedSetKeyError(missing_key_message(self.root, kind)) salt = crypto.SetKey.new_salt() self._header = { "format": FORMAT, @@ -760,6 +917,14 @@ def _initialize(self, passphrase: str, *, resume: bool) -> None: self._write_header() def _write_header(self) -> None: + if self._header.get("version") == ENVELOPE_VERSION: + from openadapt_flow import envelope + + self._header.pop("device_mac", None) + if self._device is not None: + self._header["device_mac"] = envelope.device_mac( + self._header, self._device + ) raw = json.dumps(self._header, indent=2, sort_keys=True).encode("utf-8") _atomic_write(self.root / HEADER, raw) self._header_revision = _sha256(raw) @@ -794,7 +959,7 @@ def write(self, rel: str, data: bytes) -> None: entry = self._classified(rel) with self._mutation(): old = self._codecs.get(rel) - if entry.classification == "structural": + if entry.classification in ("structural", "export"): codec: Codec = "plain" blob = data else: @@ -1189,8 +1354,121 @@ def require_readable(path: Path | str, what: str) -> None: ) +# -- recipients and shredding -------------------------------------------------- + + +def _replace_header(root: Path, header: dict[str, object]) -> None: + raw = json.dumps(header, indent=2, sort_keys=True).encode("utf-8") + path = root / HEADER + tmp = path.with_name(f".{HEADER}.{secrets.token_hex(6)}.tmp") + try: + with open(tmp, "wb") as fh: + fh.write(raw) + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, path) + finally: + if os.path.lexists(tmp): + os.unlink(tmp) + if os.name == "posix": + fd = os.open(root, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def recipients_of(root: Path | str) -> list[str]: + """The public recipients a version 3 set is wrapped for (no key needed).""" + header = read_header(root) + listed = ( + header.get("recipients") if header.get("version") == ENVELOPE_VERSION else [] + ) + return [str(r) for r in listed or []] # type: ignore[union-attr] + + +def add_recipients(root: Path | str, recipients: list[str]) -> list[str]: + """Wrap a version 3 set's data key for more recipients (a share, or an + organization recipient added later). No file is re-encrypted. Run it on + the computer that wrote the set, so its device MAC stays valid.""" + from openadapt_flow import envelope + + base = Path(_abs(root)) + with mutation_lock(base): + header = read_header(base) + if header.get("version") != ENVELOPE_VERSION: + raise SealedSetError( + f"{base} is an older encrypted set (version " + f"{header.get('version')}); only version 3 sets have recipients" + ) + SealedSet.open(base, None) # the set must verify before it is shared + dek = _data_key(header, None) + wanted = list(header.get("recipients") or []) # type: ignore[call-overload] + for item in recipients: + text = str(envelope.parse_recipient(item)) + if text not in wanted: + wanted.append(text) + header["recipients"] = wanted + header["age"] = envelope.wrap(dek, header, wanted) + device = _own_device(header) + header.pop("device_mac", None) + if device is not None: + header["device_mac"] = envelope.device_mac(header, device) + _replace_header(base, header) + return wanted + + +def shred(root: Path | str) -> list[str]: + """Crypto-shred a sealed set: delete every wrapped copy of its data key, + and the durable checkpoints and other stores' ciphertext inside it. + + The set's own files stay on disk as ciphertext that no key opens. Returns + the set-relative paths of the other stores' files that were deleted. This + can't be undone; there is no recovery copy anywhere. + """ + base = Path(_abs(root)) + removed: list[str] = [] + with mutation_lock(base): + header = read_header(base) + for name in ( + "age", + "passphrase", + "wrapped_key", + "salt", + "kdf", + "kdf_n", + "kdf_r", + "kdf_p", + "device_mac", + ): + header.pop(name, None) + header["shredded"] = True + if header.get("version") != ENVELOPE_VERSION: + # Without its salt (v1) or wrapped key (v2) the DEK can't be + # derived; record the set as shredded the same way. + header["version"] = ENVELOPE_VERSION + header.setdefault("data_key_id", secrets.token_hex(16)) + _replace_header(base, header) + for rel in _disk_files(base): + path = base / rel + try: + data = path.read_bytes() + except OSError: + continue + if data[: len(crypto.SET_FILE_MAGIC)] == crypto.SET_FILE_MAGIC: + continue # the set's own ciphertext, now unopenable + if crypto.is_encrypted(data): + path.unlink() + removed.append(rel) + return removed + + __all__ = [ "BUNDLE_FILES", + "ENVELOPE_VERSION", + "add_recipients", + "recipients_of", + "shred", "HEADER", "LIBRARY_FILES", "RECORDING_ENV_KEY", diff --git a/packages/flow/openadapt_flow/tutorial.py b/packages/flow/openadapt_flow/tutorial.py index a3e4861cc1..7301ad376d 100644 --- a/packages/flow/openadapt_flow/tutorial.py +++ b/packages/flow/openadapt_flow/tutorial.py @@ -322,6 +322,13 @@ def record_tutorial( from openadapt_flow.recorder import Recorder delay = _validated_presentation_delay(presentation_delay_s) + if encryption_key is None: + from openadapt_flow import at_rest + from openadapt_flow import sealed_set as _sealed + + # Encrypted by default, like `record` (docs/phi_at_rest.md). + if at_rest.seal_new("a recording", recording_dir): + encryption_key = _sealed.recording_key() _http_json(f"{base_url.rstrip('/')}/api/reset", method="POST", body={}) entry_url = f"{base_url.rstrip('/')}/{TUTORIAL_ENTRY_QUERY}" backend, close = PlaywrightBackend.launch(entry_url, headless=not headed) diff --git a/packages/flow/pyproject.toml b/packages/flow/pyproject.toml index d0ebac63a9..64af7fbe5d 100644 --- a/packages/flow/pyproject.toml +++ b/packages/flow/pyproject.toml @@ -55,6 +55,13 @@ dependencies = [ # out of the box in a regulated/PHI deployment; the audited AEAD substrate # for docs/phi_at_rest.md. Imported lazily, only on the encryption path. "cryptography>=42.0", + # Encryption at rest is on by default (docs/phi_at_rest.md). Each encrypted + # recording, bundle or run has its own data key, wrapped with age (X25519) + # for its recipients through pyrage (MIT, Rust bindings to the audited rage + # crate), and this computer's device key lives in the OS keychain through + # keyring (MIT). Both are imported lazily, only on the encryption path. + "pyrage>=1.2,<2", + "keyring>=24", # The portable contracts (request, result and receipt models). They live # in openadapt-types, which depends only on pydantic, so a consumer of the # models never installs this package's vision stack; openadapt_flow.contracts diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index ba5300693f..839abcc75e 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -75,6 +75,13 @@ def _isolation_env(root: Path) -> dict[str, str | None]: "OPENADAPT_FLOW_PLAINTEXT_AT_REST": "test suite: synthetic data", "OPENADAPT_FLOW_AT_REST_HOME": str(root / ".at-rest-home"), "OPENADAPT_FLOW_AT_REST": None, + # The device key goes to a file in the isolated home, never to the + # OS keychain (no dialog, no write to the person's login keychain). + "OPENADAPT_FLOW_KEY_STORE": "file", + "OPENADAPT_ENCRYPT_AT_REST": None, + "OPENADAPT_ORG_RECIPIENTS": None, + "OPENADAPT_POLICY_FILE": str(root / ".no-policy.json"), + "OPENADAPT_AGE_IDENTITY_FILE": None, } diff --git a/packages/flow/tests/test_envelope_at_rest.py b/packages/flow/tests/test_envelope_at_rest.py new file mode 100644 index 0000000000..8e1c5906c4 --- /dev/null +++ b/packages/flow/tests/test_envelope_at_rest.py @@ -0,0 +1,350 @@ +"""Encrypted by default: the device key, recipients, sharing and shredding. + +Every test injects an in-memory keychain (or forces the file store), so no +test reads or writes the real OS keychain or raises an OS dialog. +""" + +from __future__ import annotations + +import base64 +import json +import os +from pathlib import Path +from typing import Optional + +import pyrage +import pytest + +from openadapt_flow import at_rest, crypto, envelope, sealed_set + +PNG = b"\x89PNG\r\n\x1a\n" + b"synthetic pixels" + + +class MemoryKeychain(at_rest.KeyStore): + """A keychain that lives in this test only.""" + + def __init__(self, *, broken: bool = False) -> None: + self.values: dict[str, str] = {} + self.broken = broken + self.reads = 0 + + def get(self, account: str) -> Optional[str]: + if self.broken: + raise at_rest.KeyStoreUnavailable("no keychain backend (test)") + self.reads += 1 + return self.values.get(account) + + def set(self, account: str, value: str) -> None: + if self.broken: + raise at_rest.KeyStoreUnavailable("no keychain backend (test)") + self.values[account] = value + + +@pytest.fixture +def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + for name in ( + at_rest.OPT_OUT_ENV, + at_rest.MODE_ENV, + at_rest.ENCRYPT_ENV, + at_rest.KEY_STORE_ENV, + crypto.ENV_KEY, + sealed_set.RECORDING_ENV_KEY, + envelope.ORG_RECIPIENTS_ENV, + envelope.IDENTITY_FILE_ENV, + ): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv(envelope.POLICY_FILE_ENV, str(tmp_path / "no-policy.json")) + root = tmp_path / "home" + monkeypatch.setenv(at_rest.HOME_ENV, str(root)) + keychain = MemoryKeychain() + at_rest.use_key_store(keychain) + at_rest._reset_for_tests() + yield root, keychain + at_rest.use_key_store(None) + at_rest._reset_for_tests() + + +def _seal(root: Path, files: dict[str, bytes], kind: str = "run") -> None: + with sealed_set.writing(root, kind, sealed_set.passphrase_for(kind)) as writer: + for rel, data in files.items(): + writer.write(rel, data) + + +def _header(root: Path) -> dict: + return json.loads((root / sealed_set.HEADER).read_text()) + + +def _on_disk(root: Path) -> list[bytes]: + return [p.read_bytes() for p in root.rglob("*") if p.is_file()] + + +# -- the device key ------------------------------------------------------------ + + +def test_device_key_goes_to_the_keychain_with_a_marker_only(home, capsys) -> None: + root, keychain = home + first = at_rest.device_secret(create=True) + assert first and first.startswith("AGE-SECRET-KEY-1") + assert list(keychain.values.values()) == [first] + marker = json.loads((root / "keys" / at_rest.MARKER_NAME).read_text()) + assert marker["store"] == "keychain" + assert first not in json.dumps(marker) # a check value, never the key + assert not (root / "keys" / at_rest.DEVICE_KEY_NAME).exists() + assert not (root / "keys" / at_rest.KEY_NAME).exists() + assert at_rest.device_secret(create=True) == first + assert "OS keychain entry" in capsys.readouterr().err + + +def test_a_missing_keychain_entry_fails_closed_and_mints_nothing(home) -> None: + root, keychain = home + at_rest.device_secret(create=True) + keychain.values.clear() + with pytest.raises(at_rest.LocalKeyError, match="missing"): + at_rest.local_key() + assert keychain.values == {} + assert not (root / "keys" / at_rest.DEVICE_KEY_NAME).exists() + + +def test_a_replaced_keychain_entry_fails_closed(home) -> None: + _root, keychain = home + at_rest.device_secret(create=True) + account = next(iter(keychain.values)) + keychain.values[account] = str(pyrage.x25519.Identity.generate()) + with pytest.raises(at_rest.LocalKeyError, match="does not hold"): + at_rest.device_secret(create=False) + + +def test_a_locked_keychain_fails_closed_once_the_key_lives_there(home) -> None: + _root, keychain = home + at_rest.device_secret(create=True) + keychain.broken = True + with pytest.raises(at_rest.LocalKeyError, match="Unlock the keychain"): + at_rest.existing_key() + + +def test_no_keychain_falls_back_to_a_private_file_with_a_warning(home, capsys) -> None: + root, keychain = home + keychain.broken = True + secret = at_rest.device_secret(create=True) + path = root / "keys" / at_rest.DEVICE_KEY_NAME + assert path.read_text().strip() == secret + if os.name == "posix": + assert path.stat().st_mode & 0o777 == 0o600 + assert path.parent.stat().st_mode & 0o777 == 0o700 + assert "WARNING: no OS keychain is available" in capsys.readouterr().err + + +def test_keychain_only_refuses_without_a_keychain(home, monkeypatch) -> None: + _root, keychain = home + keychain.broken = True + monkeypatch.setenv(at_rest.KEY_STORE_ENV, "keychain") + with pytest.raises(at_rest.LocalKeyError, match="keychain"): + at_rest.device_secret(create=True) + + +def test_a_key_file_from_an_earlier_version_keeps_working(home) -> None: + root, keychain = home + legacy = base64.urlsafe_b64encode(os.urandom(32)).decode() + keys = root / "keys" + keys.mkdir(parents=True, mode=0o700) + (keys / at_rest.KEY_NAME).write_text(legacy + "\n") + os.chmod(keys / at_rest.KEY_NAME, 0o600) + assert at_rest.local_key() == legacy + assert crypto.resolve_key(None) == legacy + assert keychain.values == {} + + +def test_tests_never_reach_the_real_keychain(monkeypatch) -> None: + at_rest.use_key_store(None) + monkeypatch.delenv(at_rest.KEY_STORE_ENV, raising=False) + assert "PYTEST_CURRENT_TEST" in os.environ + assert at_rest._store_choice() == "file" + + +# -- the opt-out ----------------------------------------------------------------- + + +def test_encrypt_zero_turns_it_off_with_one_warning_line(home, capsys) -> None: + root, _keychain = home + os.environ[at_rest.ENCRYPT_ENV] = "0" + try: + assert at_rest.seal_new("a recording", root / "rec") is False + assert at_rest.seal_new("a recording", root / "rec") is False + err = [line for line in capsys.readouterr().err.splitlines() if line] + assert len(err) == 1 and err[0].startswith("WARNING:") + ledger = (root / at_rest.LEDGER_NAME).read_text().splitlines() + assert json.loads(ledger[0])["reason"] == "OPENADAPT_ENCRYPT_AT_REST=0" + finally: + del os.environ[at_rest.ENCRYPT_ENV] + + +def test_a_mistyped_encrypt_setting_is_refused(monkeypatch) -> None: + monkeypatch.setenv(at_rest.ENCRYPT_ENV, "nope") + with pytest.raises(ValueError): + at_rest.opt_out_reason() + + +def test_strict_mode_ignores_the_opt_out(home, monkeypatch) -> None: + monkeypatch.setenv(at_rest.ENCRYPT_ENV, "0") + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + assert at_rest.seal_new("a recording", "x") is True + + +def test_new_artifacts_are_sealed_by_default(home) -> None: + assert at_rest.DEFAULT_SEALS_ARTIFACTS is True + assert at_rest.seals_by_default() is True + + +# -- recipients ------------------------------------------------------------------ + + +def test_a_new_run_is_wrapped_for_the_device_only_ciphertext_on_disk(home) -> None: + root, _keychain = home + run = root.parent / "run" + _seal(run, {"report.json": b'{"typed": "a synthetic value"}', "steps/a.png": PNG}) + header = _header(run) + assert header["version"] == sealed_set.ENVELOPE_VERSION + device = at_rest.device_secret(create=False) + assert header["recipients"] == [envelope.device_recipient(device)] + assert "passphrase" not in header and "device_mac" in header + for data in _on_disk(run): + assert b"a synthetic value" not in data and not data.startswith(PNG[:8]) + assert sealed_set.read_bytes(run / "steps" / "a.png") == PNG + + +def test_another_computer_cannot_open_it(home, monkeypatch) -> None: + root, _keychain = home + run = root.parent / "run" + _seal(run, {"report.json": b"{}"}) + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "elsewhere")) + with pytest.raises(sealed_set.SealedSetKeyError, match="no key on this computer"): + sealed_set.SealedSet.open(run, None) + + +def test_an_org_recipient_reads_it_without_the_device(home, monkeypatch) -> None: + root, _keychain = home + org = pyrage.x25519.Identity.generate() + monkeypatch.setenv(envelope.ORG_RECIPIENTS_ENV, str(org.to_public())) + run = root.parent / "run" + _seal(run, {"report.json": b"evidence"}) + assert str(org.to_public()) in sealed_set.recipients_of(run) + identity = root.parent / "reviewer.txt" + identity.write_text(f"# reviewer\n{org}\n") + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "reviewer-home")) + monkeypatch.setenv(envelope.IDENTITY_FILE_ENV, str(identity)) + assert sealed_set.SealedSet.open(run, None).read_bytes("report.json") == b"evidence" + + +def test_an_org_recipient_from_the_policy_file(home, monkeypatch, tmp_path) -> None: + org = pyrage.x25519.Identity.generate() + policy = tmp_path / "policy.json" + policy.write_text(json.dumps({"recipients": [str(org.to_public())]})) + monkeypatch.setenv(envelope.POLICY_FILE_ENV, str(policy)) + assert envelope.org_recipients() == [str(org.to_public())] + + +def test_a_malformed_org_recipient_refuses_the_write(home, monkeypatch) -> None: + root, _keychain = home + monkeypatch.setenv(envelope.ORG_RECIPIENTS_ENV, "age1notarecipient") + with pytest.raises(sealed_set.SealedSetError, match="not an age recipient"): + _seal(root.parent / "run", {"report.json": b"{}"}) + + +def test_share_rewraps_without_reencrypting(home, monkeypatch) -> None: + root, _keychain = home + run = root.parent / "run" + _seal(run, {"report.json": b"shared"}) + before = (run / "report.json.enc").read_bytes() + friend = pyrage.x25519.Identity.generate() + sealed_set.add_recipients(run, [str(friend.to_public())]) + assert (run / "report.json.enc").read_bytes() == before + assert sealed_set.read_bytes(run / "report.json") == b"shared" + identity = root.parent / "friend.txt" + identity.write_text(str(friend)) + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "friend-home")) + monkeypatch.setenv(envelope.IDENTITY_FILE_ENV, str(identity)) + assert sealed_set.read_bytes(run / "report.json") == b"shared" + + +def test_shred_makes_it_unreadable_and_drops_checkpoints(home) -> None: + root, _keychain = home + run = root.parent / "run" + run.mkdir() + (run / "checkpoints").mkdir() + checkpoint = crypto.encrypt_bytes(b"{}", "k" * 20, aad=crypto.CHECKPOINT_AAD) + (run / "checkpoints" / "s1.enc").write_bytes(checkpoint) + writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) + writer.write("report.json", b"gone") + writer.finalize(adopt_external=True) + removed = sealed_set.shred(run) + assert removed == ["checkpoints/s1.enc"] + assert not (run / "checkpoints" / "s1.enc").exists() + with pytest.raises(sealed_set.SealedSetError, match="shredded"): + sealed_set.read_bytes(run / "report.json") + assert "age" not in _header(run) + + +def test_shred_deletes_other_stores_ciphertext(home) -> None: + root, _keychain = home + run = root.parent / "run" + run.mkdir() + (run / "pending.json").write_bytes( + crypto.encrypt_bytes(b"{}", "k" * 20, aad=crypto.CHECKPOINT_AAD) + ) + writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) + writer.write("report.json", b"gone") + writer.finalize(adopt_external=True) + assert sealed_set.shred(run) == ["pending.json"] + assert not (run / "pending.json").exists() + + +def test_a_forged_header_for_this_device_is_refused(home) -> None: + """age has no sender authentication: the device MAC is what stops a + header someone else wrapped for this computer's public recipient.""" + root, _keychain = home + run = root.parent / "run" + _seal(run, {"report.json": b"real"}) + header = _header(run) + forged = dict(header) + forged["age"] = envelope.wrap(os.urandom(32), forged, forged["recipients"]) + (run / sealed_set.HEADER).write_text(json.dumps(forged)) + with pytest.raises(sealed_set.SealedSetError, match="device MAC"): + sealed_set.read_bytes(run / "report.json") + forged.pop("device_mac") + (run / sealed_set.HEADER).write_text(json.dumps(forged)) + with pytest.raises(sealed_set.SealedSetError, match="device MAC"): + sealed_set.read_bytes(run / "report.json") + + +def test_a_configured_key_keeps_the_header_flow_always_wrote(home, monkeypatch) -> None: + root, keychain = home + monkeypatch.setenv(crypto.ENV_KEY, "a-deployment-key-for-tests") + run = root.parent / "run" + _seal(run, {"report.json": b"{}"}) + assert _header(run)["version"] == 1 + assert keychain.values == {} # no device key was needed + + +def test_a_configured_key_and_an_org_recipient_both_open_it(home, monkeypatch) -> None: + root, _keychain = home + org = pyrage.x25519.Identity.generate() + monkeypatch.setenv(crypto.ENV_KEY, "a-deployment-key-for-tests") + monkeypatch.setenv(envelope.ORG_RECIPIENTS_ENV, str(org.to_public())) + run = root.parent / "run" + _seal(run, {"report.json": b"both"}) + header = _header(run) + assert header["version"] == 3 and "passphrase" in header + assert header["recipients"] == [str(org.to_public())] + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "other")) + assert sealed_set.read_bytes(run / "report.json") == b"both" + monkeypatch.setenv(crypto.ENV_KEY, "the-wrong-key-entirely") + with pytest.raises((sealed_set.SealedSetError, crypto.CryptoError)): + sealed_set.SealedSet.open(run, None) + + +def test_a_legacy_plaintext_folder_still_reads(home) -> None: + root, _keychain = home + plain = root.parent / "old-run" + plain.mkdir() + (plain / "report.json").write_bytes(b"{}") + assert sealed_set.read_bytes(plain / "report.json") == b"{}" diff --git a/packages/flow/uv.lock b/packages/flow/uv.lock index a84e4c492a..ea6c77f9fd 100644 --- a/packages/flow/uv.lock +++ b/packages/flow/uv.lock @@ -2628,8 +2628,10 @@ dependencies = [ { name = "cryptography" }, { name = "httpx" }, { name = "idna" }, + { name = "keyring" }, { name = "openadapt-types" }, { name = "pydantic" }, + { name = "pyrage" }, { name = "pyyaml" }, { name = "tomli", marker = "python_full_version < '3.11'" }, ] @@ -2846,6 +2848,7 @@ requires-dist = [ { name = "jinja2", marker = "extra == 'service-mlx'", specifier = ">=3.1,<4" }, { name = "jsonschema", marker = "extra == 'agent'", specifier = ">=4.20.0" }, { name = "jsonschema", marker = "extra == 'dev'", specifier = ">=4.21" }, + { name = "keyring", specifier = ">=24" }, { name = "keyring", marker = "extra == 'hosted'", specifier = ">=25" }, { name = "keyring", marker = "extra == 'keychain'", specifier = ">=24" }, { name = "langchain-core", marker = "extra == 'langgraph'", specifier = ">=1.7,<2" }, @@ -2886,6 +2889,7 @@ requires-dist = [ { name = "pyobjc-framework-cocoa", marker = "sys_platform == 'darwin' and extra == 'macos'", specifier = ">=10.3" }, { name = "pyobjc-framework-cocoa", marker = "sys_platform == 'darwin' and extra == 'native-ocr'", specifier = ">=10.0" }, { name = "pyobjc-framework-quartz", marker = "sys_platform == 'darwin' and extra == 'macos'", specifier = ">=10.3" }, + { name = "pyrage", specifier = ">=1.2,<2" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=5.0" }, { name = "pytest-timeout", marker = "extra == 'dev'", specifier = ">=2.2" }, @@ -3856,6 +3860,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3e/b9/3766cc361d93edb2ce81e2e1f87dd98f314d7d513877a342d31b30741680/pypng-0.20220715.0-py3-none-any.whl", hash = "sha256:4a43e969b8f5aaafb2a415536c1a8ec7e341cd6a3f957fd5b5f32a4cfeed902c", size = 58057, upload-time = "2022-07-15T14:11:03.713Z" }, ] +[[package]] +name = "pyrage" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/15/a4/612910dbedf7d9fb24ec58474849438b6f88e078e1a100f73a54a605d228/pyrage-1.4.0.tar.gz", hash = "sha256:545bf188e8d217ec88c32bc8e8bf56026c8c0b1b1f96d2688cedf1427ab0e827", size = 32198, upload-time = "2026-08-23T22:48:59.906Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/bb/6b167a449e95ecf0eaf4277c949a89a29dfc08cc533f710a9e6f12bef513/pyrage-1.4.0-cp310-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:bcf4177aea91a9f48951db8001c1385baafbae62cc15d691ef43efebaab6b8db", size = 1701313, upload-time = "2026-08-23T22:48:53.835Z" }, + { url = "https://files.pythonhosted.org/packages/5a/cb/d88aaab0b89141802473f6139fe8e05519d1b6ac06bff8231a1378a5674f/pyrage-1.4.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f868b360ccd3f836326d42b532fae3e8eb8340a88cca0a39c0ae10fce68f6cc5", size = 882978, upload-time = "2026-08-23T22:48:55.525Z" }, + { url = "https://files.pythonhosted.org/packages/d9/f0/41da7d88cfdad2eba492f3275ec50a65916ccd3a78140fb15875569ad1ff/pyrage-1.4.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7f4eb0cbc2b4aee5deac9862c47b3895866df5554153951af822e9c581e68558", size = 924673, upload-time = "2026-08-23T22:48:57.1Z" }, + { url = "https://files.pythonhosted.org/packages/d3/8c/354fdb9ee7b45a2060272c623536b2cf9f0996de2242eaac177cff3f8003/pyrage-1.4.0-cp310-abi3-win_amd64.whl", hash = "sha256:c4a5dcd24a14b5e0d4cccff13649a2b8f1609ad45d6438bb85f35d84b0c8155e", size = 848219, upload-time = "2026-08-23T22:48:58.702Z" }, +] + [[package]] name = "pyreadline3" version = "3.5.6" diff --git a/tests/conftest.py b/tests/conftest.py index f9bfce3b70..08a8e7beab 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -74,3 +74,10 @@ def _isolated_flow_at_rest(tmp_path_factory, monkeypatch): monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data") monkeypatch.delenv("OPENADAPT_FLOW_AT_REST", raising=False) monkeypatch.delenv("OPENADAPT_LEDGER_AUTHORITY_CONFIG", raising=False) + # Never the OS keychain from tests: no dialog, no login-keychain write. + monkeypatch.setenv("OPENADAPT_FLOW_KEY_STORE", "file") + monkeypatch.delenv("OPENADAPT_ENCRYPT_AT_REST", raising=False) + monkeypatch.delenv("OPENADAPT_ORG_RECIPIENTS", raising=False) + monkeypatch.setenv( + "OPENADAPT_POLICY_FILE", str(tmp_path_factory.mktemp("policy") / "none.json") + ) diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index a24e964ba7..0dbb37b2e5 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -1115,6 +1115,8 @@ def test_real_quickstart(tmp_path, monkeypatch, capfd): monkeypatch.delenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", raising=False) monkeypatch.setenv("OPENADAPT_FLOW_AT_REST_HOME", str(tmp_path / "at-rest")) monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(tmp_path / "seal")) + # The device key goes to a file here, never to the OS keychain. + monkeypatch.setenv("OPENADAPT_FLOW_KEY_STORE", "file") root = tmp_path / "openadapt-quickstart" stream = io.StringIO() outcome = run_quickstart( @@ -1135,14 +1137,38 @@ def test_real_quickstart(tmp_path, monkeypatch, capfd): assert outcome.broken.new_records == 0 assert outcome.broken.transaction_outcome == "RECONCILIATION_REQUIRED" assert f"{runs} of {runs} saved and checked" in output + from openadapt_flow import sealed_set + + notes = [] for index in range(1, runs + 1): - report = json.loads((root / f"run-{index}" / "report.json").read_text()) + run_dir = root / f"run-{index}" + # Encrypted by default: read in memory, receipts beside it. + report = json.loads(sealed_set.read_bytes(run_dir / "report.json")) assert report["execution_outcome"] == "VERIFIED" assert report["params"]["note"] in output + notes.append(report["params"]["note"].encode("utf-8")) + assert sealed_set.is_sealed(run_dir) + assert (run_dir / "seal.json").is_file() checkpoints = root / "run-1" / "checkpoints" assert list(checkpoints.glob("*.enc")) assert not list(checkpoints.glob("*.json")) - assert "Created a local encryption key at" in output + # 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"} + for path in root.rglob("*"): + if not path.is_file(): + continue + data = path.read_bytes() + if path.name not in plain_ok: + assert not data.startswith(b"\x89PNG"), path + assert not data.startswith(b"\xff\xd8\xff"), path + if path.name != "seal.html": + for note in notes: + assert note not in data, path + for folder in ("recording", "bundle", "run-1", "run-broken"): + assert sealed_set.is_sealed(root / folder), folder + assert "Created a local encryption key" in output # Neither the key notice nor a plaintext notice reached the terminal. err = capfd.readouterr().err assert "Created a local encryption key" not in err From 29e6e9220a8365ba214a740bb0792073c62df919 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:19:37 -0500 Subject: [PATCH 02/37] flow: key hierarchy per the evidence-encryption memo Sealed-set v3 now wraps each set's data key with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072) and a solo recovery key. Files are Tink AES256_GCM_HKDF_1MB streams, checked against Tink. Organization mode comes from a machine policy and fails closed without its recipient and archive. Hardware providers are interfaces with test doubles. Shred destroys the tracked bucket-key copies. age and the share verb are gone. --- CAPABILITIES.md | 3 +- llms-full.txt | 66 +- packages/flow/CHANGELOG.md | 32 +- packages/flow/docs/LIMITS.md | 15 +- packages/flow/docs/PRIVACY.md | 6 +- .../commands/08-run-on-premises/at-rest.md | 1 + packages/flow/docs/phi_at_rest.md | 263 +++-- packages/flow/openadapt_flow/__main__.py | 4 +- packages/flow/openadapt_flow/at_rest.py | 75 +- packages/flow/openadapt_flow/cli_at_rest.py | 125 +- packages/flow/openadapt_flow/crypto.py | 4 + packages/flow/openadapt_flow/envelope.py | 255 ----- packages/flow/openadapt_flow/key_hierarchy.py | 1012 +++++++++++++++++ packages/flow/openadapt_flow/sealed_set.py | 417 ++++--- packages/flow/openadapt_flow/stream_aead.py | 113 ++ packages/flow/pyproject.toml | 15 +- packages/flow/tests/conftest.py | 6 +- packages/flow/tests/test_envelope_at_rest.py | 350 ------ packages/flow/tests/test_key_hierarchy.py | 523 +++++++++ packages/flow/tests/test_stream_aead.py | 90 ++ packages/flow/uv.lock | 60 +- tests/conftest.py | 6 +- 22 files changed, 2437 insertions(+), 1004 deletions(-) delete mode 100644 packages/flow/openadapt_flow/envelope.py create mode 100644 packages/flow/openadapt_flow/key_hierarchy.py create mode 100644 packages/flow/openadapt_flow/stream_aead.py delete mode 100644 packages/flow/tests/test_envelope_at_rest.py create mode 100644 packages/flow/tests/test_key_hierarchy.py create mode 100644 packages/flow/tests/test_stream_aead.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 9c30b43e75..ea704c595f 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -347,7 +347,7 @@ improvising or retrying when something is off. | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | -| Encryption at rest by default, as envelope encryption: each recording, bundle and run has its own data key, wrapped with age (X25519) for this computer's device key (kept in the OS keychain, or a 0600 file with a warning where none works), optional organization recipients from the environment or a policy file, and shares added later; a configured `OPENADAPT_BUNDLE_KEY` stays a recipient. `at-rest shred` deletes the wrapped keys (crypto-shredding). Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line; strict mode also refuses what can't be encrypted yet | On this branch | Synthetic (device-key, fail-closed, recipient, share, shred, forged-header tests with an injected keychain); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.envelope`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#recipients) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On this branch | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | @@ -454,6 +454,7 @@ A test fails when a command has no file or this list is out of date. **Run on premises:** +- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. - `no-outbound` - `service` diff --git a/llms-full.txt b/llms-full.txt index 336d9b6236..706c2887dd 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -780,8 +780,8 @@ improvising or retrying when something is off. | Each package installs on its own within a size budget, checked in CI (privacy without desktop, capture without plotting) | Released ([#1270](https://github.com/OpenAdaptAI/OpenAdapt/pull/1270), [#1271](https://github.com/OpenAdaptAI/OpenAdapt/pull/1271), [#1279](https://github.com/OpenAdaptAI/OpenAdapt/pull/1279)) | CI | `.github/workflows/packages.yml` | | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | -| Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | -| Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | +| Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On this branch | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | @@ -888,6 +888,7 @@ A test fails when a command has no file or this list is out of date. **Run on premises:** +- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. - `no-outbound` - `service` @@ -2284,6 +2285,14 @@ postconditions, model requests, effect queries, logs, and reports. Keep those observations inside the declared execution boundary and apply storage, retention, access, and egress controls there. +Encryption at rest is on by default: recordings, bundles and run +directories (screenshots, frames, typed values, reports) are ciphertext on +disk, each under its own data key, wrapped through a per-set bucket key to +this computer's device key and, in organization mode, the organization's key +([`phi_at_rest.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md)). It protects +files at rest, not a running session: anyone who can run commands as the +signed-in person can read them, as Flow does. + See [`SANITIZED_ARTIFACTS.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SANITIZED_ARTIFACTS.md) for the review and exact-hash workflow, [`PRIVACY.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/PRIVACY.md) for the field-level data map, and [`ENTERPRISE_ARCHITECTURE.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ENTERPRISE_ARCHITECTURE.md) for component @@ -2308,13 +2317,19 @@ host hardening, storage encryption, backups, retention, access control, monitoring, effect-verifier integration, update validation, and disaster recovery. -The repository supplies integrity manifests, optional encryption at rest for -bundles, web recordings and the run directories of sealed bundles, destination -policy, local egress checks, and audit primitives. Encryption at rest does not -cover data in process memory, the target application's own storage, file names -and sizes, desktop recordings, or commands outside the list in -[`phi_at_rest.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md), which refuse sealed input; the key is a -passphrase in the environment, not a KMS. A content digest +The repository supplies integrity manifests, encryption at rest by default +for recordings, bundles and run directories, destination policy, local egress +checks, and audit primitives. Encryption at rest does not cover data in +process memory, the target application's own storage, file names and sizes, a +desktop recording's raw capture session while it records, cross-window +(`record --surface`) recordings, the receipt page, the logged artifacts in +[`phi_at_rest.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md), or commands outside its list, which refuse +sealed input. Without an organization policy only this computer's device key +(and a recovery key, if made) opens what it wrote. The device key is a +software key in the OS keychain (or a 0600 file where there is none) until the +Secure Enclave and TPM providers are built: code running as the signed-in +person can use it. Losing it loses the data unless an organization policy or a +recovery key exists. A content digest proves byte identity, not publisher identity. A local hash chain is tamper evident against ordinary changes, not tamper proof against an administrator who can rewrite it. Local approvals record provenance but are not enterprise-IdP @@ -2377,6 +2392,39 @@ automation into an independently certified transaction system. ## What changed in openadapt-flow 3.4.0 +### Encryption at rest by default + +- Recordings (web, the quickstart and tutorial, and desktop once converted), + compiled bundles and every run directory (report, step screenshots, crops, + frames, evidence, `REPORT.md`) are now encrypted at rest by default, with + no setup, as sealed-set version 3: a data key per set, wrapped with HPKE + (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, and files as + Tink AES-256-GCM-HKDF 1 MiB streams. The bucket key is wrapped to the + device runtime key (only while the set is written; bundles keep it), the + device viewer key, organization keys and a recovery key. +- Organization mode, from a machine policy (MDM profile, Group Policy, a + root-owned `/etc/openadapt/policy.json`): organization recipients (P-256 + or RSA-OAEP-3072) and a key archive are required, and recording stops + without them. Solo users can make a recovery key + (`openadapt-flow at-rest recovery create`). +- `openadapt-flow at-rest status` shows the keys and policy; + `at-rest shred` destroys a set's tracked bucket-key copies. +- The device key is a software P-256 key in the OS keychain through + `keyring` (a 0600 file with a warning where there is none). Secure + Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test + doubles, not built yet. +- A configured `OPENADAPT_BUNDLE_KEY` or `OPENADAPT_RECORDING_KEY` still wins + outside organization mode (deprecated), and `~/.openadapt/keys/at-rest.key` + keeps working. Version 1 and 2 sets and plaintext folders still read. +- `OPENADAPT_ENCRYPT_AT_REST=0`, or `--no-encrypt` on `record`, `compile`, + `run` and `replay`, turns it off with a one-line warning and a ledger line. +- Receipts (`seal.json`, `receipt.*`, `public-seal.json`) stay plaintext and + are now written for encrypted runs too; their digests are over the + plaintext `report.json`. `seal verify`, `inspect report-run`, the receipt + page and the quickstart read encrypted runs. The receipt page embeds the + report, so beside an encrypted run it is logged as a plaintext copy. +- Core dependencies: `cryptography>=50` (HPKE) and `keyring`. + ### Features - Dropdowns, searchable selects, type-aheads and native selects are recorded, diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 6d5db95509..a389cd2775 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -22,27 +22,33 @@ - Recordings (web, the quickstart and tutorial, and desktop once converted), compiled bundles and every run directory (report, step screenshots, crops, frames, evidence, `REPORT.md`) are now encrypted at rest by default, with - no setup. Each set has its own data key, wrapped with age (X25519, through - `pyrage`) for its recipients: this computer's device key, kept in the OS - keychain through `keyring` (macOS Keychain, Windows Credential Manager, - Linux Secret Service; a 0600 file with a warning where none works), and - optional organization recipients (`OPENADAPT_ORG_RECIPIENTS` or a policy - file). `openadapt-flow at-rest status|share|shred` shows the key and - recipients, wraps a set for more recipients, and crypto-shreds it. + no setup, as sealed-set version 3: a data key per set, wrapped with HPKE + (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, and files as + Tink AES-256-GCM-HKDF 1 MiB streams. The bucket key is wrapped to the + device runtime key (only while the set is written; bundles keep it), the + device viewer key, organization keys and a recovery key. +- Organization mode, from a machine policy (MDM profile, Group Policy, a + root-owned `/etc/openadapt/policy.json`): organization recipients (P-256 + or RSA-OAEP-3072) and a key archive are required, and recording stops + without them. Solo users can make a recovery key + (`openadapt-flow at-rest recovery create`). +- `openadapt-flow at-rest status` shows the keys and policy; + `at-rest shred` destroys a set's tracked bucket-key copies. +- The device key is a software P-256 key in the OS keychain through + `keyring` (a 0600 file with a warning where there is none). Secure + Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test + doubles, not built yet. - A configured `OPENADAPT_BUNDLE_KEY` or `OPENADAPT_RECORDING_KEY` still wins - and keeps the header Flow always wrote. A key file from an earlier version - (`~/.openadapt/keys/at-rest.key`) keeps working. Plaintext folders still - read. + outside organization mode (deprecated), and `~/.openadapt/keys/at-rest.key` + keeps working. Version 1 and 2 sets and plaintext folders still read. - `OPENADAPT_ENCRYPT_AT_REST=0`, or `--no-encrypt` on `record`, `compile`, `run` and `replay`, turns it off with a one-line warning and a ledger line. -- A missing, locked or replaced keychain entry fails closed with a clear - error; Flow never makes a new key over it. - Receipts (`seal.json`, `receipt.*`, `public-seal.json`) stay plaintext and are now written for encrypted runs too; their digests are over the plaintext `report.json`. `seal verify`, `inspect report-run`, the receipt page and the quickstart read encrypted runs. The receipt page embeds the report, so beside an encrypted run it is logged as a plaintext copy. -- New core dependencies: `pyrage` and `keyring`. +- Core dependencies: `cryptography>=50` (HPKE) and `keyring`. ### Features diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index 721b121c3f..83270242bd 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -1005,8 +1005,9 @@ retention, access, and egress controls there. Encryption at rest is on by default: recordings, bundles and run directories (screenshots, frames, typed values, reports) are ciphertext on -disk, each under its own data key wrapped for this computer's device key and -any organization recipients ([`phi_at_rest.md`](phi_at_rest.md)). It protects +disk, each under its own data key, wrapped through a per-set bucket key to +this computer's device key and, in organization mode, the organization's key +([`phi_at_rest.md`](phi_at_rest.md)). It protects files at rest, not a running session: anyone who can run commands as the signed-in person can read them, as Flow does. @@ -1041,10 +1042,12 @@ process memory, the target application's own storage, file names and sizes, a desktop recording's raw capture session while it records, cross-window (`record --surface`) recordings, the receipt page, the logged artifacts in [`phi_at_rest.md`](phi_at_rest.md), or commands outside its list, which refuse -sealed input. By default only this computer's device key, kept in the OS -keychain (or a 0600 file where there is none), opens what it wrote: it is not a -hardware-bound key, a KMS or an escrow, and losing it loses the data unless an -organization recipient was configured. A content digest +sealed input. Without an organization policy only this computer's device key +(and a recovery key, if made) opens what it wrote. The device key is a +software key in the OS keychain (or a 0600 file where there is none) until the +Secure Enclave and TPM providers are built: code running as the signed-in +person can use it. Losing it loses the data unless an organization policy or a +recovery key exists. A content digest proves byte identity, not publisher identity. A local hash chain is tamper evident against ordinary changes, not tamper proof against an administrator who can rewrite it. Local approvals record provenance but are not enterprise-IdP diff --git a/packages/flow/docs/PRIVACY.md b/packages/flow/docs/PRIVACY.md index 688bbac235..6b06e77336 100644 --- a/packages/flow/docs/PRIVACY.md +++ b/packages/flow/docs/PRIVACY.md @@ -55,8 +55,8 @@ Paths this rule does not cover yet are listed under Scrubbing and encryption are separate controls. Recordings, bundles, run directories and durable checkpoints are encrypted by default, with no setup: -each set under its own data key, wrapped for this computer's device key (in -the OS keychain) and any organization recipients, or for a configured key. +each set under its own data key, wrapped through a per-set bucket key to this +computer's device key and, in organization mode, the organization's key. `OPENADAPT_FLOW_AT_REST=strict` also refuses the outputs that can't be encrypted yet ([phi_at_rest.md](phi_at_rest.md#default-opt-out-and-strict-mode)). @@ -104,7 +104,7 @@ what protects it. | # | Where (file:symbol) | PHI written | Control | |---|---|---|---| -| 1 | `recorder.py` recording dir | `frames/*.png` (full screenshots), `events.jsonl` (literal typed `text` incl. param values, `structured_identity` DOM text), `meta.json` (`params` example values), `network.jsonl` | **Encrypted at rest by default** — the web recorder writes only AES-256-GCM ciphertext from the first frame, under a per-recording data key wrapped for this computer's device key (kept in the OS keychain) and any organization recipients, or under `OPENADAPT_RECORDING_KEY` / `OPENADAPT_BUNDLE_KEY` when set ([phi_at_rest.md](phi_at_rest.md)). A desktop recording is encrypted when it is converted; its raw capture session is plaintext while it records, then deleted. Not scrubbed (the recording is the compile input; scrubbing it would corrupt the demo). Under `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` (logged), and for cross-window `record --surface` recordings (logged): filesystem controls + retention policy. | +| 1 | `recorder.py` recording dir | `frames/*.png` (full screenshots), `events.jsonl` (literal typed `text` incl. param values, `structured_identity` DOM text), `meta.json` (`params` example values), `network.jsonl` | **Encrypted at rest by default** — the web recorder writes only AES-256-GCM ciphertext from the first frame, under a per-recording data key wrapped through a bucket key to this computer's device key and, in organization mode, the organization's key, or under `OPENADAPT_RECORDING_KEY` / `OPENADAPT_BUNDLE_KEY` when set ([phi_at_rest.md](phi_at_rest.md)). A desktop recording is encrypted when it is converted; its raw capture session is plaintext while it records, then deleted. Not scrubbed (the recording is the compile input; scrubbing it would corrupt the demo). Under `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` (logged), and for cross-window `record --surface` recordings (logged): filesystem controls + retention policy. | | 2 | `compiler/compile.py` → `ir.Workflow.save` → `workflow.json` | `anchor.ocr_text`, `anchor.context_text`, `anchor.structured_identity` (identity band = name/DOB/MRN), `step.text` (literal TYPE), `params`, `step.intent`; plus `templates/*.png` and `identifier_crop` PNGs (rendered PHI) and the compiler sidecars | **Encrypted at rest by default** — `compile` (and `seal`) encrypt every bundle file that can hold patient data under one sealed index ([phi_at_rest.md](phi_at_rest.md)). Not scrubbed: the bundle *must* carry the recorded identity evidence to verify identity on replay. An unsealed bundle: filesystem controls + retention policy. | | 3 | `runtime/replayer.py` → `RunReport.save` → `report.json` | `params`, `workflow_name`, per-step `intent`, `error`, `IdentityCheck.expected`/`observed` (recorded vs live band text — raw PHI), `UnarmedStep.*` | Session tokens, CSRF tokens, OAuth grants and credential headers in its URLs and strings are **redacted when it is written** and listed in `redactions` ([REPORT_REDACTION.md](REPORT_REDACTION.md)); a Seal refuses a report that still holds one. **Encrypted at rest by default** — every run directory is sealed: report, frames, crops, checkpoints and approvals; the receipt files beside it stay plaintext and hold only digests over the plaintext report. Under the opt-out, or for a run feature that can't be sealed yet (logged), a documented boundary: the machine artifact and identity audit trail, under filesystem controls + retention policy. The shareable derivative (`REPORT.md`) IS scrubbed — see below. | | 4 | `runtime/replayer.py:_save_step_png` → `steps/*.png` | full before/after frames | **Scrubbed** — routed through `scrub_image_bytes`; redacted when `OPENADAPT_FLOW_SCRUB_IMAGES=1` (opt-in under `auto`) **or implied under `SCRUB=on`** (a pinned run redacts frames without the extra flag). | diff --git a/packages/flow/docs/commands/08-run-on-premises/at-rest.md b/packages/flow/docs/commands/08-run-on-premises/at-rest.md index e69de29bb2..e25f2b7478 100644 --- a/packages/flow/docs/commands/08-run-on-premises/at-rest.md +++ b/packages/flow/docs/commands/08-run-on-premises/at-rest.md @@ -0,0 +1 @@ +Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index 3db7b32224..1153ef2157 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -14,9 +14,9 @@ machine), [phi_in_transit.md](phi_in_transit.md) (PHI on the wire) and ## Default, opt-out and strict mode Flow encrypts recordings, bundles and run directories by default, with no -setup. Each one gets its own random data key, and that key is wrapped for -its recipients (see [Recipients](#recipients)). By default the only recipient -is this computer's device key. +setup. Each one gets its own random data key, wrapped through a per-set +bucket key to this computer's device key and, in an organization, to the +organization's key (see [Key hierarchy](#key-hierarchy)). | | Default | `OPENADAPT_FLOW_AT_REST=strict` | | --- | --- | --- | @@ -48,8 +48,8 @@ all of them. Files encrypted earlier still read under the opt-out, with the key that encrypted them. **Healthcare and other regulated deployments:** set -`OPENADAPT_FLOW_AT_REST=strict`, and an organization recipient or a key from -your secret manager. Strict mode runs: +`OPENADAPT_FLOW_AT_REST=strict` and an organization policy +([Organization policy](#organization-policy)). Strict mode runs: - `record`, `compile`, `induce`, `admit run`, `run`, `replay` and `resume`, which encrypt what they write, plaintext input included; @@ -101,69 +101,153 @@ files included. It fails if any of them holds plaintext. What stays readable is listed under [What is not encrypted](#what-is-not-encrypted). -## Recipients +## Key hierarchy -Every encrypted recording, bundle and run directory (format version 3) has -its own random 256-bit data key. Its files are encrypted under that key with -AES-256-GCM. The header wraps the data key for each recipient with -[age](https://age-encryption.org) (X25519, through `pyrage`, MIT, which binds -the audited `rage` crate). Who can open the set is the list of recipients: +The design is the evidence-encryption memo of 2026-11-20 +(openadapt-internal `docs/design/evidence-encryption-2026-11/MEMO.md`). +Every new recording, bundle and run directory (sealed-set format version 3) +has three layers of keys: -| Recipient | Who holds the private key | Set by | +``` +data key (DEK, 256-bit random, one per set) + wrapped with HPKE (RFC 9180: DHKEM P-256, HKDF-SHA256, AES-256-GCM) to +bucket key pair (P-256, one per set) + whose private half is wrapped, in a bucket record, to + the device runtime key only while the set is being written + the device viewer key user presence on hardware + organization key(s) P-256 HPKE or RSA-OAEP-3072; required in org mode + a recovery key solo mode, optional +``` + +- **Files.** Each file is a Tink `AES256_GCM_HKDF_1MB` stream (1 MiB + segments, last segment flagged, so a truncated file fails to open) under a + payload key derived from the DEK and the set id, with the file's path in + the set as associated data. `tests/test_stream_aead.py` checks the format + against Tink itself. +- **Header.** `.openadapt-sealed.json` holds the set id, the key reference + (bucket id and fingerprint), the DEK wrapped to the bucket's public key, + the index, and two HMAC-SHA-256 MACs: one under a key derived from the DEK, + one under a key derived from the bucket's private key. The second stops + someone who knows the bucket's public key from writing a set this computer + would accept. +- **Algorithms.** NIST-approved throughout: P-256, HKDF-SHA256, AES-256-GCM, + RSA-OAEP with SHA-256. All come from the `cryptography` package (50 or + later). This is not a FIPS 140-3 validated module unless you run it on a + FIPS-validated OpenSSL provider. + +### Where the bucket record lives + +| | Solo (default, no policy) | Organization mode (`mode: org`) | +| --- | --- | --- | +| Record | Inside the set's header (`records: inline`), so it travels with backups | `~/.openadapt/keys/buckets/.json` plus a copy in the organization's `key_archive` (`records: archive`); never in the header | +| Wrapped to | Device viewer key (and runtime key while open), recovery key if one exists | Device viewer key (runtime while open, local copy only), organization keys, recovery key if set | +| Lost laptop | Backups open with the recovery key; without one they can't be opened | Every set whose record reached the archive opens with the organization key | +| Crypto-shredding | This disk's copy only: a backup still opens with the recovery key | Every tracked copy: the local record (overwritten, then deleted) and the archive copy | + +A bundle keeps its runtime stanza after it is written, because programs +replay unattended. Recordings and runs lose it when they are finalized; from +then on the viewer key (Touch ID or Windows Hello, on hardware) opens them. + +### Device keys + +| Platform | Provider | Status | | --- | --- | --- | -| **The device** (default) | This computer: an age identity Flow creates on first use and keeps in the OS keychain (macOS Keychain, Windows Credential Manager with DPAPI, Linux Secret Service) | Nothing to set | -| **The organization** (optional) | Your reviewers and auditors, in your own KMS, HSM or age plugin | `OPENADAPT_ORG_RECIPIENTS=age1...` (comma-separated), or `{"recipients": ["age1..."]}` in the policy file (`OPENADAPT_POLICY_FILE`, default `~/.openadapt/policy.json`), which IT or MDM can place | -| **A share** | Whoever you give it to | `openadapt-flow at-rest share DIR --recipient age1...` | -| **A configured key** (legacy) | Your secret manager | `OPENADAPT_BUNDLE_KEY`, `OPENADAPT_RECORDING_KEY` | - -- With an organization recipient, a device writes evidence the organization - can read later, on another computer and after the person who recorded it - has left. A reviewer opens it with `OPENADAPT_AGE_IDENTITY_FILE` pointing - at an age identity file. A malformed organization recipient stops the - write: evidence is never written silently without it. -- `share` rewraps the same data key for more recipients; no file is - re-encrypted. Run it on the computer that wrote the set. -- A configured key still wins: with one set and no organization recipient, - Flow writes the version 1 header it always wrote, keyed by that passphrase - (scrypt N=2^15, r=8, p=1). With both, the passphrase and the organization - are recipients, and the device is not. -- age has no sender authentication, so a device-written header also carries - an HMAC under a key derived from the device identity. The device refuses a - header that names it but lacks a valid HMAC. -- OpenAdapt Cloud never holds a key, a wrapped key or recovery material. - -**Where the device key lives.** The device identity is stored with -`keyring` in the OS keychain, entry `openadapt-flow-at-rest`. Next to it, +| macOS | Secure Enclave runtime key; Secure Enclave viewer key with Touch ID | Interface and test double only; **not built**, pending a check on real hardware | +| Windows | TPM key through the Platform Crypto Provider; Windows Hello viewer key | Interface and test double only; **not built**, pending a check on real hardware | +| Linux | TPM2 key | Interface only; **not built** | +| Everywhere today | A software P-256 key in the OS keychain through `keyring` (macOS Keychain, Windows Credential Manager with DPAPI, Linux Secret Service), else a 0600 file with a warning | Built; `at-rest status` labels it `software` | + +A software key protects against a copied disk, backup or ticket attachment, +not against code running as you. `require_hardware_device_key: true` in the +policy refuses the software key. Next to a keychain-held key, `~/.openadapt/keys/device-key.store.json` records which entry holds it and a -check value; it holds no key material. If the entry is later missing, locked, -denied or different, Flow fails closed with a clear error and never makes a -new key over it. Where no keychain works (a headless Linux box without Secret -Service, for example), the identity goes to `~/.openadapt/keys/device.agekey`, -mode 0600 in a 0700 directory, with a warning. `OPENADAPT_FLOW_KEY_STORE` -picks the store: `auto` (default), `keychain` (fail without one) or `file`. -`OPENADAPT_FLOW_AT_REST_HOME` (or `OPENADAPT_HOME`) moves the marker and the -file. Back the device key up: what it alone encrypts can't be read without -it. A key file from an earlier version (`~/.openadapt/keys/at-rest.key`) -keeps being used as the local passphrase, so nothing it encrypted is -orphaned. - -The keychain item is readable by your login session; it is not a -non-exportable hardware key. A Secure Enclave or TPM provider (for example -through an age plugin) would slot in behind the same recipient interface -(`openadapt_flow.envelope`); it is not built yet. - -`openadapt-flow at-rest status` shows the mode, where the device key is kept, -its public recipient and the organization recipients. It prints no key -material. +check value (no key material). If that entry is later missing, locked or +different, Flow fails closed and never makes a new key over it. +`OPENADAPT_FLOW_KEY_STORE` picks the software key's store: `auto` +(default), `keychain` or `file`. + +### Organization policy + +The organization makes its key in its own KMS or HSM and distributes a policy +file. Flow reads the first one found, and a user file never overrides a +machine one: + +1. macOS: the managed preferences profile `ai.openadapt.policy` (MDM); +2. Windows: `HKLM\SOFTWARE\Policies\OpenAdapt`, value `Policy` (Group + Policy, Intune); +3. Linux: `/etc/openadapt/policy.json`, owned by root and writable by root + only; +4. `OPENADAPT_POLICY=`. It may set organization mode only when it is + owned by root (`OPENADAPT_POLICY_TRUST_USER_FILE=1` lifts that for + development, and status says so). + +```json +{ + "schema": "openadapt.ai/policy/v1", + "org": "example-health", + "mode": "org", + "recipients": [ + {"role": "org", "status": "active", "type": "hpke-p256", + "public_key": "", "fingerprint": "sha256:…", + "kms_uri": "arn:aws:kms:…"}, + {"role": "org", "status": "retired", "type": "rsa-oaep-3072-sha256", + "public_key": ""} + ], + "key_archive": "file:///Volumes/keys/openadapt/", + "require_hardware_device_key": false, + "max_unarchived": 50 +} +``` + +- In organization mode, a missing or unreadable policy, no active + organization recipient, or no `key_archive` stops recording and running. +- If the archive is unreachable, records stay local as "not yet archived" + (`at-rest status` counts them), and new sets stop after `max_unarchived`. +- Only a local or mounted path (`file://`) is supported as `key_archive` so + far; `s3://` and `smb://` refuse. +- OpenAdapt Cloud never distributes the organization's key or holds any key. + +A reviewer opens a set with the archive copy of its record in +`~/.openadapt/keys/buckets/` and `OPENADAPT_ORG_KEY_FILE` (a PEM private +key). Unwrapping through the KMS itself (`Decrypt`, `DeriveSharedSecret`) is +not built yet. + +### Solo recovery + +`openadapt-flow at-rest recovery create` makes a recovery key: 32 random +bytes shown once as a 52-character code, turned into a P-256 key with HPKE's +DeriveKeyPair. Only its public half is stored; it becomes a recipient of +every new set. Open with it on another computer by setting +`OPENADAPT_RECOVERY_CODE`. Without one, a lost or reset computer means its +encrypted runs can't be opened. + +### Legacy keys + +- `OPENADAPT_BUNDLE_KEY` and `OPENADAPT_RECORDING_KEY` still win outside + organization mode: Flow writes the version 1 header it always wrote, + keyed by that passphrase (scrypt N=2^15, r=8, p=1). They are deprecated. +- `~/.openadapt/keys/at-rest.key` (mode 0600), the key earlier versions + made, still opens what it encrypted, and is still the local passphrase of + durable checkpoints and attended state, which keep their own containers. +- Version 1 and 2 sets, and plaintext folders, still read. + +`openadapt-flow at-rest status` shows the mode, the policy source, the device +keys, the organization fingerprints, the recovery key and the unarchived +count. It prints no key material. ## Crypto-shredding -`openadapt-flow at-rest shred DIR --yes` deletes every wrapped copy of a -set's data key (and the salt of an older set), and deletes the durable -checkpoints and other stores' ciphertext inside it. Nobody can open the set -afterwards, and there is no recovery copy anywhere. The library call is -`openadapt_flow.sealed_set.shred`, for a retention job. Copies you made -elsewhere (backups, shares already opened) are outside its reach. +`openadapt-flow at-rest shred DIR --yes` destroys the set's bucket key: the +local record is overwritten and deleted, and the archive copy deleted. It +also drops the record from the header, and deletes the durable checkpoints +and other stores' ciphertext inside the set. It returns a shred record +(bucket id, time, copies destroyed). The library call is +`openadapt_flow.sealed_set.shred`, for a retention job. In solo mode it +reaches only this disk's copy, and says so. + +It does not reach plaintext that leaked earlier (a screenshot pasted into a +ticket, a crash dump), copies someone opened and saved, or a desktop +recording's raw capture session. ## Receipts @@ -175,9 +259,8 @@ digests, never the report's contents. **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` bytes, decrypted in memory. So a receipt is the same whether the run is -encrypted, rewrapped for a share, or was never encrypted, and checking it -needs a recipient's key to read the report. `seal verify` and the receipt -page decrypt the report to check it. +encrypted or not, and checking it needs a key that opens the report. +`seal verify` and the receipt page decrypt the report to check it. The receipt page (`seal.html`) embeds the run report so it can check the receipt in the browser. Beside an encrypted run it is therefore a plaintext @@ -187,45 +270,41 @@ strict mode refuses it. ## Desktop recordings The desktop recorders capture through openadapt-capture, which writes its -raw session (input database and screen video) in plaintext under -`/.capture` while recording. When recording stops, Flow converts it into -an encrypted recording and deletes the raw session, so only ciphertext is -left. Until then, and if the process is killed before it converts, the raw -session is plaintext on disk. Record on an encrypted volume when that window -matters. +raw session (input database and screen video) in plaintext while recording, +in a private 0700 folder beside the output. When recording stops, Flow +converts it, encrypts the converted recording into the output, and deletes +the raw session and the converted plaintext. Until then, and if the process +is killed before it converts, they are plaintext on disk; deleting them is not +a secure erase. So crypto-shredding can't be claimed for a desktop recording +(NIST SP 800-88r2 3.2.2). Record on an encrypted volume. Encrypting inside the +recorder, before the first write, is not built yet. ## Keys | Variable | Used for | | --- | --- | -| `OPENADAPT_BUNDLE_KEY` | A legacy passphrase recipient for bundles and their run directories. | -| `OPENADAPT_RECORDING_KEY` | The same for recordings. When it is unset, recordings use `OPENADAPT_BUNDLE_KEY`. | -| `OPENADAPT_ORG_RECIPIENTS` | Organization age recipients for every new set. | -| `OPENADAPT_AGE_IDENTITY_FILE` | age identities a reviewer reads sets with. | -| `OPENADAPT_FLOW_KEY_STORE` | Where the device key is kept: `auto`, `keychain` or `file`. | - -Each set is opened once per reader or writer handle. That handle reuses its -data key to seal or open files with AES-256-GCM, a fresh random 96-bit nonce -for each write, and the file's path in the associated data. Independent -path-helper reads authenticate again; the module retains no reader or -passphrase cache. Caller inputs and derived keys remain sensitive memory; -releasing a handle does not promise erasure. AES-256-GCM and scrypt come from -the `cryptography` package, and X25519 wrapping from `pyrage`. Durable -checkpoints and attended state keep their own containers, under the -configured key or a local passphrase derived from the device key (or the -earlier `at-rest.key`). - -Files are encrypted whole, in memory, not as a stream: a very large file -(a long screen video) needs its size in memory to read or write. +| `OPENADAPT_POLICY` | A policy file, when no machine policy exists. | +| `OPENADAPT_RECOVERY_CODE` | The solo recovery code, to open sets on another computer. | +| `OPENADAPT_ORG_KEY_FILE` | An organization recipient's PEM private key, for a reviewer. | +| `OPENADAPT_FLOW_KEY_STORE` | Where the software device key is kept: `auto`, `keychain` or `file`. | +| `OPENADAPT_BUNDLE_KEY` | Deprecated: a passphrase for bundles and their run directories (version 1 header). | +| `OPENADAPT_RECORDING_KEY` | Deprecated: the same for recordings. | + +Each set is opened once per reader or writer handle, which reuses its keys +for that operation. Independent path-helper reads open the set again; the +module retains no reader or passphrase cache. Caller inputs and derived keys +remain sensitive memory; releasing a handle does not promise erasure. Files +are encrypted whole in memory: a very large file needs its size in memory to +read or write. ## Sealed sets A sealed bundle, an encrypted recording and an encrypted run directory share one format, the sealed set: -- `.openadapt-sealed.json` holds the wrapped data key (version 3: one age - stanza per recipient; version 1: the salt and scrypt parameters) and an - index sealed with the data key. The index lists every other file with the +- `.openadapt-sealed.json` holds the wrapped data key (version 3: wrapped + to the set's bucket key, see [Key hierarchy](#key-hierarchy); version 1: + the salt and scrypt parameters) and an index sealed with the data key. The index lists every other file with the SHA-256 of its bytes on disk. The header also repeats the index digest (`set_digest`) for an inventory that has no key; Flow trusts only the copy it recomputes from the authenticated index. diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 93ae422877..dff13c79c8 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13731,9 +13731,8 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.cli_undo:_cmd_undo_list", "openadapt_flow.cli_undo:_cmd_undo_approve", "openadapt_flow.cli_undo:_cmd_undo_run", - # Rewrap or shred a set's header only; no file is decrypted to disk. + # Shreds a set's key only; no file is decrypted to disk. "openadapt_flow.__main__:_cmd_report_run", - "openadapt_flow.cli_at_rest:_cmd_share", "openadapt_flow.cli_at_rest:_cmd_shred", } ) @@ -13782,6 +13781,7 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.cli_service:_cmd_restart", "openadapt_flow.cli_service:_cmd_run", "openadapt_flow.cli_at_rest:_cmd_status", + "openadapt_flow.cli_at_rest:_cmd_recovery_create", "openadapt_flow.cli_no_outbound:_cmd_add", "openadapt_flow.cli_no_outbound:_cmd_derive", "openadapt_flow.cli_no_outbound:_cmd_list", diff --git a/packages/flow/openadapt_flow/at_rest.py b/packages/flow/openadapt_flow/at_rest.py index b43df2097a..65684ef078 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -66,11 +66,10 @@ LEDGER_NAME: Final[str] = "plaintext-at-rest.jsonl" KEY_NAME: Final[str] = "at-rest.key" MARKER_NAME: Final[str] = "device-key.store.json" -DEVICE_KEY_NAME: Final[str] = "device.agekey" +DEVICE_KEY_NAME: Final[str] = "device-software.key" KEYCHAIN_SERVICE: Final[str] = "openadapt-flow-at-rest" _MARKER_SCHEMA: Final[str] = "openadapt.flow.at-rest-key-store/v1" _CHECK_LABEL: Final[bytes] = b"openadapt-flow/device-key-check/v1" -_PASSPHRASE_LABEL: Final[bytes] = b"openadapt-flow/local-passphrase/v1" #: How long a reader waits for another process that is creating the key. _CREATE_WAIT_S: Final[float] = 5.0 #: How long one keychain call may take before Flow gives up on it. @@ -462,16 +461,18 @@ def _account() -> str: return f"device-key:{_home().expanduser().resolve()}" +#: Prefix of a software device key: a P-256 private scalar, base64url. +SOFTWARE_KEY_PREFIX: Final[str] = "OADEV-P256-1:" + + def _valid_secret(text: Optional[str]) -> bool: - if not text or not text.startswith("AGE-SECRET-KEY-1"): + if not text or not text.startswith(SOFTWARE_KEY_PREFIX): return False try: - import pyrage - - pyrage.x25519.Identity.from_str(text) - except Exception: # noqa: BLE001 - not an identity + raw = base64.urlsafe_b64decode(text[len(SOFTWARE_KEY_PREFIX) :].encode("ascii")) + except (ValueError, UnicodeEncodeError): return False - return True + return len(raw) == 32 def _check(text: str) -> str: @@ -563,31 +564,35 @@ def device_secret(*, create: bool) -> Optional[str]: ) from exc -def _derived_passphrase(secret: str) -> str: - """The local passphrase for the stores that take one (durable - checkpoints, attended state), derived from the device identity.""" - import hashlib - import hmac - - raw = hmac.new(secret.encode("ascii"), _PASSPHRASE_LABEL, hashlib.sha256).digest() - return base64.urlsafe_b64encode(raw).decode("ascii") - - def local_key() -> str: - """This computer's local passphrase, creating the device key on first use. - - A key file from an earlier version (``at-rest.key``) is used as it is, so - nothing encrypted under it is orphaned. - """ + """This computer's local passphrase for the stores that take one (durable + checkpoints, attended state, the version 1 sets an earlier version + wrote), created on first use at ``keys/at-rest.key`` (0600).""" path = local_key_path() try: + return _local_passphrase(path) + except OSError as exc: + raise LocalKeyError( + f"Flow could not create or read its local encryption key at {path} " + f"({exc}). Set OPENADAPT_BUNDLE_KEY, or {HOME_ENV} to a writable " + "private directory. Nothing was written." + ) from exc + + +def _local_passphrase(path: Path) -> str: + with _lock: if path.exists(): return _read(path) - except OSError as exc: - raise LocalKeyError(f"{path} can't be read ({exc}).") from exc - secret = device_secret(create=True) - assert secret is not None - return _derived_passphrase(secret) + _private_dir(path.parent) + text = base64.urlsafe_b64encode(secrets.token_bytes(_KEY_BYTES)).decode() + if not _link_new(path, (text + "\n").encode("ascii")): + return _read(path) + print( + "Created a local encryption key for recordings, bundles and runs " + f"at {path}. Back it up: what it encrypts can't be read without it.", + file=sys.stderr, + ) + return text def _existing(path: Path, *, wait: bool) -> Optional[str]: @@ -644,10 +649,13 @@ def _link_new(path: Path, data: bytes) -> bool: def _create_device(path: Path) -> str: - import pyrage + from cryptography.hazmat.primitives.asymmetric import ec _private_dir(path.parent) - text = str(pyrage.x25519.Identity.generate()) + scalar = ec.generate_private_key(ec.SECP256R1()).private_numbers().private_value + text = SOFTWARE_KEY_PREFIX + base64.urlsafe_b64encode( + scalar.to_bytes(32, "big") + ).decode("ascii") choice = _store_choice() why_not = "" if choice != "file": @@ -771,12 +779,11 @@ def existing_key() -> Optional[str]: and records nothing. None when there is no local key yet.""" path = local_key_path() try: - if path.exists(): - return _read(path) + if not path.exists(): + return None + return _read(path) except OSError as exc: raise LocalKeyError(f"{path} can't be read ({exc}).") from exc - secret = device_secret(create=False) - return _derived_passphrase(secret) if secret is not None else None def default_key() -> Optional[str]: diff --git a/packages/flow/openadapt_flow/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py index a0273ad524..d2fec9f749 100644 --- a/packages/flow/openadapt_flow/cli_at_rest.py +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -1,12 +1,13 @@ -"""``openadapt-flow at-rest``: who can open encrypted runs, and shredding them. +"""``openadapt-flow at-rest``: who can open encrypted runs, recovery and shredding. -- ``status`` prints where this computer's device key is kept, its public - recipient, the organization recipients new sets are wrapped for, and the - encryption mode. It prints no key material. -- ``share DIR --recipient age1...`` wraps an encrypted recording, bundle or - run for more recipients. No file is re-encrypted. -- ``shred DIR --yes`` deletes every wrapped key of an encrypted set, which - makes it unreadable by anyone. It can't be undone. +- ``status`` prints the mode, the policy and where it came from, the device + keys (hardware or software), the organization recipients by fingerprint, + the recovery key and how many key records await the archive. It prints no + key material. +- ``recovery create`` makes a solo recovery key: the code is shown once and + never stored; its public half becomes a recipient of every new run. +- ``shred DIR --yes`` destroys an encrypted set's bucket key (every tracked + copy), so nobody can open it. It can't be undone. See docs/phi_at_rest.md. """ @@ -18,53 +19,69 @@ import sys from pathlib import Path +RECOVERY_WARNING = ( + "Anyone with this code can open every recording and run on this computer, " + "including ones that show patient or customer data. Store it offline. " + "OpenAdapt can't recover it for you." +) + def _cmd_status(args: argparse.Namespace) -> int: - from openadapt_flow import at_rest, envelope + from openadapt_flow import at_rest + from openadapt_flow import key_hierarchy as kh try: - org = envelope.org_recipients() - device = envelope.device_identity(create=False) + policy = kh.load_policy() + status = kh.describe(policy) mode = ( "strict" if at_rest.strict() else ("off" if at_rest.opt_out_reason() is not None else "on") ) - except (envelope.EnvelopeError, at_rest.LocalKeyError, ValueError) as exc: + except (kh.KeyHierarchyError, at_rest.LocalKeyError, ValueError) as exc: print(f"at-rest: {exc}", file=sys.stderr) return 2 - status = { - "encryption": mode, - "configured_key": at_rest.explicit_key(), - "device_key": at_rest.key_location(), - "device_recipient": envelope.device_recipient(device) if device else None, - "org_recipients": org, - "policy_file": str(envelope.policy_path()), - } + status = {"encryption": mode, "configured_key": at_rest.explicit_key(), **status} if args.json: print(json.dumps(status, indent=2, sort_keys=True)) return 0 print(f"Encryption at rest: {mode}") - print(f"Device key: {status['device_key'] or 'not created yet'}") - if status["device_recipient"]: - print(f"Device recipient: {status['device_recipient']}") - print("Organization recipients: " + (", ".join(org) if org else "none")) + print( + f"Mode: {status['mode']} (records {status['records']}); policy: {status['policy_source']}" + ) + print(f"Device runtime key: {status['device_runtime_key'] or 'not created yet'}") + print(f"Device viewer key: {status['device_viewer_key'] or 'not created yet'}") + for item in status["org_recipients"]: + print(f"Organization recipient ({item['status']}): {item['fingerprint']}") + if status["mode"] == "org": + print(f"Key records not yet archived: {status['unarchived']}") + elif not status["recovery_key"]: + print("No recovery key. Create one: openadapt-flow at-rest recovery create") if status["configured_key"]: - print("A configured key (OPENADAPT_BUNDLE_KEY) is also a recipient.") + print("A configured key (OPENADAPT_BUNDLE_KEY) is set: deprecated.") return 0 -def _cmd_share(args: argparse.Namespace) -> int: - from openadapt_flow import envelope, sealed_set +def _cmd_recovery_create(args: argparse.Namespace) -> int: + from openadapt_flow import key_hierarchy as kh - try: - recipients = sealed_set.add_recipients(Path(args.dir), list(args.recipient)) - except (sealed_set.SealedSetError, envelope.EnvelopeError) as exc: - print(f"at-rest share: {exc}", file=sys.stderr) + if kh.recovery_recipient() is not None and not args.replace: + print( + "at-rest recovery: a recovery key exists. Pass --replace to make a new " + "one for new runs (older runs stay on the old one).", + file=sys.stderr, + ) return 2 - print(f"{args.dir} is now wrapped for {len(recipients)} recipient(s):") - for item in recipients: - print(f" {item}") + code, recipient = kh.new_recovery_code() + kh.save_recovery_recipient(recipient) + print(RECOVERY_WARNING) + print() + print(f"Recovery code: {code}") + print() + print( + f"New runs are also wrapped to this key ({recipient.fpr}). To open with it, " + f"set {kh.RECOVERY_CODE_ENV}." + ) return 0 @@ -83,14 +100,17 @@ def _cmd_shred(args: argparse.Namespace) -> int: ) return 2 try: - removed = sealed_set.shred(root) + record = sealed_set.shred(root) except sealed_set.SealedSetError as exc: print(f"at-rest shred: {exc}", file=sys.stderr) return 2 - print( - f"Shredded {root}: its wrapped keys are deleted, so nobody can open it" - + (f"; also deleted {len(removed)} checkpoint file(s)." if removed else ".") - ) + copies = ", ".join(record.get("copies_destroyed") or []) or "none tracked" # type: ignore[arg-type] + print(f"Shredded {root}: bucket key copies destroyed: {copies}.") + if record.get("records") == "inline": + print( + "This run kept its key record inside its files (solo mode), so a " + "backup copy still opens with the recovery key until you delete it." + ) return 0 @@ -98,31 +118,22 @@ def register(sub: argparse._SubParsersAction) -> None: p = sub.add_parser( "at-rest", help=( - "Encryption at rest: show this computer's device key and recipients, " - "share an encrypted run with another recipient, or crypto-shred it" + "Encryption at rest: show the device keys, policy and recipients, " + "make a recovery key, or crypto-shred an encrypted run" ), allow_abbrev=False, ) rsub = p.add_subparsers(dest="at_rest_cmd", required=True) - s = rsub.add_parser( - "status", help="Where the key is kept and who can read new runs" - ) + s = rsub.add_parser("status", help="Where the keys are and who can open new runs") s.add_argument("--json", action="store_true") s.set_defaults(func=_cmd_status) + s = rsub.add_parser("recovery", help="The solo recovery key") + rec = s.add_subparsers(dest="recovery_cmd", required=True) + c = rec.add_parser("create", help="Make a recovery key; the code is shown once") + c.add_argument("--replace", action="store_true") + c.set_defaults(func=_cmd_recovery_create) s = rsub.add_parser( - "share", help="Wrap an encrypted recording, bundle or run for more recipients" - ) - s.add_argument("dir", help="The encrypted directory") - s.add_argument( - "--recipient", - action="append", - required=True, - metavar="AGE1...", - help="An age X25519 recipient (repeat for more)", - ) - s.set_defaults(func=_cmd_share) - s = rsub.add_parser( - "shred", help="Delete an encrypted set's wrapped keys; nobody can open it after" + "shred", help="Destroy an encrypted set's bucket key; nobody can open it after" ) s.add_argument("dir", help="The encrypted directory") s.add_argument("--yes", action="store_true", help="Confirm; this can't be undone") diff --git a/packages/flow/openadapt_flow/crypto.py b/packages/flow/openadapt_flow/crypto.py index ee2dfad539..5c2b15e7b4 100644 --- a/packages/flow/openadapt_flow/crypto.py +++ b/packages/flow/openadapt_flow/crypto.py @@ -171,6 +171,8 @@ def is_encrypted(data: bytes) -> bool: """ if data[: len(SET_FILE_MAGIC)] == SET_FILE_MAGIC: return True + if data[: len(SET3_FILE_MAGIC)] == SET3_FILE_MAGIC: + return True if data[: len(SALTED_FILE_MAGIC)] == SALTED_FILE_MAGIC: return True try: @@ -292,6 +294,8 @@ def decrypt_bytes(container: bytes, key: Optional[str], *, aad: bytes) -> bytes: #: Prefix of a per-file container sealed under a :class:`SetKey`. SET_FILE_MAGIC: Final[bytes] = b"OAFLOW-SEALED-1\n" +#: A version 3 sealed-set file: a Tink AES-256-GCM-HKDF stream follows. +SET3_FILE_MAGIC: Final[bytes] = b"OAFLOW-SEALED-3\n" class SetKey: diff --git a/packages/flow/openadapt_flow/envelope.py b/packages/flow/openadapt_flow/envelope.py deleted file mode 100644 index 7c86d2a3f0..0000000000 --- a/packages/flow/openadapt_flow/envelope.py +++ /dev/null @@ -1,255 +0,0 @@ -"""Who can open an encrypted recording, bundle or run: its recipients. - -Every sealed set (:mod:`openadapt_flow.sealed_set`) has its own random data -key (DEK). The files are encrypted under the DEK, and the DEK is *wrapped* -for each recipient in the set's header. Format version 3 wraps it with age -(https://age-encryption.org, through ``pyrage``, X25519 recipients): - -* **The device recipient** (the default). An age identity Flow creates on - this computer on first use and keeps in the OS keychain (macOS Keychain, - Windows Credential Manager with DPAPI, Linux Secret Service), or in a 0600 - file with a warning where no keychain works (:mod:`openadapt_flow.at_rest`). - It lets the computer that recorded a run replay and view it. -* **Organization recipients** (optional). Public age recipients (``age1...``) - from ``OPENADAPT_ORG_RECIPIENTS`` or a policy file - (``OPENADAPT_POLICY_FILE``, default ``$OPENADAPT_HOME/policy.json``, key - ``"recipients"``) that IT or MDM can place. The organization's reviewers - hold the private key in their own KMS, HSM or age plugin; Flow never sees - it. A reviewer opens a set with ``OPENADAPT_AGE_IDENTITY_FILE``. -* **Share recipients**, added later by :func:`add_recipients`, which rewraps - the same DEK without re-encrypting any file. - -A configured passphrase (``OPENADAPT_BUNDLE_KEY`` or -``OPENADAPT_RECORDING_KEY``) is a legacy recipient: with it, and no -organization recipient, Flow writes the version 2 header it always wrote. - -:func:`shred` deletes a set's wrapped keys (and the durable checkpoints that -another store encrypted inside it). With them gone the ciphertext can't be -opened by anyone: this is the crypto-shredding retention primitive. - -OpenAdapt Cloud never holds a key, a wrapped key or recovery material. - -A device-written header also carries ``device_mac``, an HMAC under a key -derived from the device identity, over the whole header. age has no sender -authentication, so without it anyone who knows the public device recipient -could write a set this computer would open. The device refuses a header that -names it but lacks a valid MAC. - -The provider layer is deliberately thin: :func:`device_identity` and -:func:`org_recipients` are the only places that decide who the recipients -are. -""" - -from __future__ import annotations - -import base64 -import hashlib -import hmac -import json -import os -from pathlib import Path -from typing import Any, Final, Optional, Sequence - -ORG_RECIPIENTS_ENV: Final[str] = "OPENADAPT_ORG_RECIPIENTS" -POLICY_FILE_ENV: Final[str] = "OPENADAPT_POLICY_FILE" -IDENTITY_FILE_ENV: Final[str] = "OPENADAPT_AGE_IDENTITY_FILE" -_WRAP_SCHEMA: Final[str] = "openadapt.flow.wrapped-dek/v3" -_MAC_LABEL: Final[bytes] = b"openadapt-flow/sealed-set/device-mac/v3" - - -class EnvelopeError(ValueError): - """A recipient is malformed, or no recipient this computer holds opens a set.""" - - -def _pyrage() -> Any: - try: - import pyrage - except ImportError as exc: # pragma: no cover - a core dependency - raise EnvelopeError( - "pyrage is not installed, so Flow can't open or write version 3 " - "encrypted sets. Reinstall openadapt-flow." - ) from exc - return pyrage - - -# -- recipients ---------------------------------------------------------------- - - -def parse_recipient(text: str) -> Any: - """An age X25519 recipient, or :class:`EnvelopeError`.""" - pyrage = _pyrage() - try: - return pyrage.x25519.Recipient.from_str(text.strip()) - except Exception as exc: # noqa: BLE001 - pyrage raises several types - raise EnvelopeError( - f"{text.strip()[:12]}... is not an age recipient (age1...)" - ) from exc - - -def _home() -> Path: - root = os.environ.get("OPENADAPT_HOME") - return Path(root) if root else Path.home() / ".openadapt" - - -def policy_path() -> Path: - configured = os.environ.get(POLICY_FILE_ENV) - return Path(configured) if configured else _home() / "policy.json" - - -def org_recipients() -> list[str]: - """The organization's public recipients, from the environment and the - policy file. A malformed entry raises: an org recipient that is silently - skipped is evidence the organization can't read later.""" - found: list[str] = [] - raw = os.environ.get(ORG_RECIPIENTS_ENV) or "" - found += [item for item in raw.replace(",", " ").split() if item] - path = policy_path() - if path.is_file(): - try: - policy = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: - raise EnvelopeError(f"{path} is not a readable policy file") from exc - listed = policy.get("recipients", []) if isinstance(policy, dict) else None - if not isinstance(listed, list) or not all(isinstance(r, str) for r in listed): - raise EnvelopeError(f"{path}: 'recipients' must be a list of age1... keys") - found += listed - out: list[str] = [] - for item in found: - text = str(parse_recipient(item)) - if text not in out: - out.append(text) - return out - - -# -- identities ---------------------------------------------------------------- - - -def device_identity(*, create: bool) -> Optional[str]: - """This computer's age identity (``AGE-SECRET-KEY-1...``), created on first - use when ``create``. None when there is none and ``create`` is False.""" - from openadapt_flow import at_rest - - return at_rest.device_secret(create=create) - - -def device_recipient(identity: str) -> str: - return str(_pyrage().x25519.Identity.from_str(identity).to_public()) - - -def _extra_identities() -> list[Any]: - """Identities a reviewer configured (``OPENADAPT_AGE_IDENTITY_FILE``).""" - path = os.environ.get(IDENTITY_FILE_ENV) - if not path: - return [] - pyrage = _pyrage() - try: - lines = Path(path).read_text(encoding="utf-8").splitlines() - except OSError as exc: - raise EnvelopeError(f"{IDENTITY_FILE_ENV}: {path} can't be read") from exc - out = [] - for line in lines: - line = line.strip() - if line and not line.startswith("#"): - try: - out.append(pyrage.x25519.Identity.from_str(line)) - except Exception as exc: # noqa: BLE001 - raise EnvelopeError( - f"{IDENTITY_FILE_ENV}: {path} holds a line that is not an age " - "identity" - ) from exc - return out - - -# -- wrapping ------------------------------------------------------------------ - - -def _binding(header: dict[str, Any]) -> dict[str, Any]: - return { - "schema": _WRAP_SCHEMA, - "kind": header["kind"], - "data_key_id": header["data_key_id"], - } - - -def wrap(dek: bytes, header: dict[str, Any], recipients: Sequence[str]) -> str: - """The DEK sealed by age to ``recipients``, bound to the set's identity.""" - pyrage = _pyrage() - payload = json.dumps( - {**_binding(header), "dek": base64.b64encode(dek).decode("ascii")}, - sort_keys=True, - ).encode("utf-8") - parsed = [parse_recipient(r) for r in recipients] - return base64.b64encode(pyrage.encrypt(payload, parsed)).decode("ascii") - - -def unwrap(header: dict[str, Any]) -> Optional[bytes]: - """The DEK, through the device identity or a configured reviewer identity. - None when no identity this computer holds is a recipient.""" - wrapped = header.get("age") - if not isinstance(wrapped, str): - return None - identities = _extra_identities() - device = device_identity(create=False) - device_rcpt: Optional[str] = None - pyrage = _pyrage() - if device is not None: - device_rcpt = device_recipient(device) - if device_rcpt in (header.get("recipients") or []): - check_device_mac(header, device) - identities.insert(0, pyrage.x25519.Identity.from_str(device)) - if not identities: - return None - try: - payload = pyrage.decrypt(base64.b64decode(wrapped, validate=True), identities) - except Exception: # noqa: BLE001 - not a recipient, or damaged - return None - try: - body = json.loads(payload) - dek = base64.b64decode(body["dek"], validate=True) - except (ValueError, KeyError, TypeError) as exc: - raise EnvelopeError("the wrapped data key is malformed") from exc - if {k: body.get(k) for k in _binding(header)} != _binding(header) or len(dek) != 32: - raise EnvelopeError("the wrapped data key belongs to another set") - return dek - - -# -- the device MAC ------------------------------------------------------------ - - -def _mac_key(identity: str) -> bytes: - return hmac.new(identity.encode("ascii"), _MAC_LABEL, hashlib.sha256).digest() - - -def _mac_body(header: dict[str, Any]) -> bytes: - body = {k: v for k, v in header.items() if k not in ("device_mac", "set_digest")} - return json.dumps(body, sort_keys=True, separators=(",", ":")).encode("utf-8") - - -def device_mac(header: dict[str, Any], identity: str) -> str: - return hmac.new(_mac_key(identity), _mac_body(header), hashlib.sha256).hexdigest() - - -def check_device_mac(header: dict[str, Any], identity: str) -> None: - """Refuse a header that names this device but that it did not write.""" - got = header.get("device_mac") - if not isinstance(got, str) or not hmac.compare_digest( - got, device_mac(header, identity) - ): - raise EnvelopeError( - "this encrypted set names this computer as a recipient, but its " - "header was not written here (device MAC missing or wrong)" - ) - - -__all__ = [ - "EnvelopeError", - "check_device_mac", - "device_identity", - "device_mac", - "device_recipient", - "org_recipients", - "parse_recipient", - "policy_path", - "unwrap", - "wrap", -] diff --git a/packages/flow/openadapt_flow/key_hierarchy.py b/packages/flow/openadapt_flow/key_hierarchy.py new file mode 100644 index 0000000000..d7658a0c06 --- /dev/null +++ b/packages/flow/openadapt_flow/key_hierarchy.py @@ -0,0 +1,1012 @@ +"""Who can open an encrypted run: the key hierarchy behind sealed-set v3. + +Design: openadapt-internal ``docs/design/evidence-encryption-2026-11/MEMO.md`` +(sections 3.1 to 3.8). The layers:: + + data key (DEK, 256-bit, one per sealed set) + wrapped by HPKE (P-256, HKDF-SHA256, AES-256-GCM) to + a bucket key pair (P-256, one per set) + whose private half is wrapped, in a *bucket record*, to + the device runtime key (only while the set is being written) + the device viewer key (user presence on hardware) + organization key(s) (P-256 HPKE or RSA-OAEP-3072; required in + organization mode) + a recovery key (solo mode, optional) + +The sealed-set header carries only the DEK wrapped to the bucket's public +key. The bucket record is what crypto-shredding destroys: + +* **Organization mode** (``records: archive``): the record lives in + ``$OPENADAPT_HOME/keys/buckets/`` and a copy goes to the organization's key + archive. Shredding deletes both; backups of the evidence then hold only + ciphertext no key opens. +* **Solo mode** (``records: inline``): the record travels inside the header, + so a recovery key can open backups. Shredding reaches only copies you can + delete. + +Device keys come from :class:`DeviceKeyProvider` implementations. The +hardware providers (Secure Enclave, TPM, Touch ID or Windows Hello) are +interfaces here with test doubles; they report themselves unavailable until +they are built and checked on real hardware, and Flow then uses a *software* +P-256 key kept in the OS keychain (or a 0600 file), labelled as such in +``at-rest status``. ``require_hardware_device_key`` in the policy refuses +that fallback. + +No key, wrapped key or recovery material ever goes to OpenAdapt Cloud, and +the organization's public key comes only from a machine policy (MDM, Group +Policy, a root-owned file), never from Cloud. + +Primitives: HPKE, ECDH P-256, RSA-OAEP, HKDF and AES-GCM from the +``cryptography`` package. Nothing here is a new primitive. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import secrets +import stat +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Final, Optional + +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa + +BUCKET_SCHEMA: Final[str] = "openadapt.ai/bucket-record/v1" +POLICY_SCHEMA: Final[str] = "openadapt.ai/policy/v1" +SHRED_SCHEMA: Final[str] = "openadapt.ai/shred-record/v1" +HPKE_P256: Final[str] = "hpke-p256" +RSA_OAEP_3072: Final[str] = "rsa-oaep-3072-sha256" +STANZA_TYPE: Final[str] = "hpke-p256-aes256gcm" + +POLICY_ENV: Final[str] = "OPENADAPT_POLICY" +#: A user-owned policy file may set organization mode only with this set +#: (development and tests); machine policies never need it. +TRUST_USER_POLICY_ENV: Final[str] = "OPENADAPT_POLICY_TRUST_USER_FILE" +RECOVERY_CODE_ENV: Final[str] = "OPENADAPT_RECOVERY_CODE" +#: A PEM private key of an organization or break-glass recipient, for a +#: reviewer opening evidence without a KMS (KMS unwrap is not built yet). +ORG_KEY_FILE_ENV: Final[str] = "OPENADAPT_ORG_KEY_FILE" + +ROLE_RUNTIME: Final[str] = "runtime" +ROLE_VIEWER: Final[str] = "viewer" +ROLE_DEVICE_SOFTWARE: Final[str] = "device-software" +ROLE_ORG: Final[str] = "org" +ROLE_BREAK_GLASS: Final[str] = "break-glass" +ROLE_RECOVERY: Final[str] = "recovery" + +#: Machine-scope policy locations, first match wins. Tests replace this. +MACHINE_POLICY_SOURCES: list[str] = [ + "/Library/Managed Preferences/ai.openadapt.policy.plist", + "HKLM\\SOFTWARE\\Policies\\OpenAdapt", + "/etc/openadapt/policy.json", +] + +_SUITE_LABEL: Final[bytes] = b"openadapt.ai/bucket/v1/wrap\0" +_RECOVERY_SALT: Final[bytes] = b"openadapt.ai/recovery-key/v1" + + +class KeyHierarchyError(ValueError): + """A policy, recipient or bucket record is missing, malformed or refused.""" + + +class NoRecipientKey(KeyHierarchyError): + """No key this computer holds opens the bucket record.""" + + +# -- primitives -------------------------------------------------------------- + + +def _suite() -> Any: + from cryptography.hazmat.primitives import hpke + + return hpke.Suite(hpke.KEM.P256, hpke.KDF.HKDF_SHA256, hpke.AEAD.AES_256_GCM) + + +def _spki(public: Any) -> bytes: + return public.public_bytes( + serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo + ) + + +def fingerprint(public: Any) -> str: + return "sha256:" + hashlib.sha256(_spki(public)).hexdigest() + + +def hpke_seal( + public: ec.EllipticCurvePublicKey, plaintext: bytes, info: bytes +) -> bytes: + return bytes(_suite().encrypt(plaintext, public, info)) + + +def hpke_open(private: ec.EllipticCurvePrivateKey, sealed: bytes, info: bytes) -> bytes: + return bytes(_suite().decrypt(sealed, private, info)) + + +def _scalar(private: ec.EllipticCurvePrivateKey) -> bytes: + return private.private_numbers().private_value.to_bytes(32, "big") + + +def _from_scalar(raw: bytes) -> ec.EllipticCurvePrivateKey: + return ec.derive_private_key(int.from_bytes(raw, "big"), ec.SECP256R1()) + + +def _b64(data: bytes) -> str: + return base64.b64encode(data).decode("ascii") + + +def _unb64(text: Any) -> bytes: + if not isinstance(text, str): + raise KeyHierarchyError("a bucket record field is not base64 text") + return base64.b64decode(text, validate=True) + + +# -- recipients ---------------------------------------------------------------- + + +@dataclass(frozen=True) +class Recipient: + """A public key the bucket's private half is wrapped to.""" + + role: str + type: str + public_key: Any + status: str = "active" + kms_uri: Optional[str] = None + + @property + def fpr(self) -> str: + return fingerprint(self.public_key) + + def wrap(self, secret: bytes, info: bytes) -> bytes: + if self.type == HPKE_P256: + return hpke_seal(self.public_key, secret, info) + if self.type == RSA_OAEP_3072: + return bytes( + self.public_key.encrypt( + secret, + padding.OAEP( + mgf=padding.MGF1(hashes.SHA256()), + algorithm=hashes.SHA256(), + label=info, + ), + ) + ) + raise KeyHierarchyError(f"unknown recipient type {self.type!r}") + + @classmethod + def from_policy(cls, entry: Any) -> "Recipient": + if not isinstance(entry, dict): + raise KeyHierarchyError("a policy recipient is not an object") + kind = entry.get("type") + try: + public = serialization.load_der_public_key(_unb64(entry.get("public_key"))) + except (ValueError, KeyHierarchyError) as exc: + raise KeyHierarchyError( + "a policy recipient's public_key is not SPKI" + ) from exc + if kind == HPKE_P256: + ok = isinstance(public, ec.EllipticCurvePublicKey) and isinstance( + public.curve, ec.SECP256R1 + ) + elif kind == RSA_OAEP_3072: + ok = isinstance(public, rsa.RSAPublicKey) and public.key_size >= 3072 + else: + ok = False + if not ok: + raise KeyHierarchyError( + f"a policy recipient must be {HPKE_P256} (P-256) or " + f"{RSA_OAEP_3072} (RSA 3072+), not {kind!r}" + ) + recipient = cls( + role=str(entry.get("role") or ROLE_ORG), + type=str(kind), + public_key=public, + status=str(entry.get("status") or "active"), + kms_uri=entry.get("kms_uri") + if isinstance(entry.get("kms_uri"), str) + else None, + ) + stated = entry.get("fingerprint") + if stated is not None and stated != recipient.fpr: + raise KeyHierarchyError( + f"a policy recipient's fingerprint {stated} does not match its key " + f"({recipient.fpr})" + ) + return recipient + + +class Unwrapper: + """Something that can open a stanza wrapped to its public key.""" + + role: str = "" + label: str = "" + + def public(self) -> Any: # pragma: no cover - interface + raise NotImplementedError + + @property + def fpr(self) -> str: + return fingerprint(self.public()) + + def unwrap(self, sealed: bytes, info: bytes) -> bytes: # pragma: no cover + raise NotImplementedError + + +class SoftwareKey(Unwrapper): + """A P-256 key held in software (keychain, DPAPI, a file, or a reviewer's + PEM). Same-user code can use it: status labels it ``software``.""" + + def __init__(self, private: Any, role: str, label: str = "software") -> None: + self._private = private + self.role = role + self.label = label + + def public(self) -> Any: + return self._private.public_key() + + def recipient(self) -> Recipient: + kind = ( + HPKE_P256 + if isinstance(self._private, ec.EllipticCurvePrivateKey) + else RSA_OAEP_3072 + ) + return Recipient(self.role, kind, self.public()) + + def unwrap(self, sealed: bytes, info: bytes) -> bytes: + if isinstance(self._private, rsa.RSAPrivateKey): + return bytes( + self._private.decrypt( + sealed, + padding.OAEP( + mgf=padding.MGF1(hashes.SHA256()), + algorithm=hashes.SHA256(), + label=info, + ), + ) + ) + return hpke_open(self._private, sealed, info) + + +# -- device key providers ------------------------------------------------------ + + +class DeviceKeyProvider(Unwrapper): + """A device key in secure hardware. ``available()`` says whether this + computer has it; ``ensure()`` creates it on first use. The private half + never leaves the hardware: ``unwrap`` asks the hardware to open a stanza + (and, for a viewer key, the person to approve).""" + + name = "hardware" + presence = False + + def available(self) -> bool: # pragma: no cover - interface + raise NotImplementedError + + def ensure(self) -> None: # pragma: no cover - interface + raise NotImplementedError + + def recipient(self) -> Recipient: + return Recipient(self.role, HPKE_P256, self.public()) + + +class _NotBuilt(DeviceKeyProvider): + """A hardware provider whose platform binding isn't built yet. It reports + itself unavailable, so Flow falls back to the labelled software key.""" + + why = "not built yet; needs a check on real hardware" + + def available(self) -> bool: + return False + + def ensure(self) -> None: + raise KeyHierarchyError(f"{self.name}: {self.why}") + + def public(self) -> Any: + raise KeyHierarchyError(f"{self.name}: {self.why}") + + def unwrap(self, sealed: bytes, info: bytes) -> bytes: + raise KeyHierarchyError(f"{self.name}: {self.why}") + + +class SecureEnclaveRuntimeKey(_NotBuilt): + """macOS: a Secure Enclave P-256 key, ``privateKeyUsage``, + ``WhenUnlockedThisDeviceOnly``, no presence (runtime role).""" + + name = "macOS Secure Enclave runtime key" + role = ROLE_RUNTIME + + +class SecureEnclaveViewerKey(_NotBuilt): + """macOS: a Secure Enclave P-256 key that needs Touch ID or the login + password (``userPresence``) for every unwrap (viewer role).""" + + name = "macOS Secure Enclave viewer key (Touch ID)" + role = ROLE_VIEWER + presence = True + + +class TpmRuntimeKey(_NotBuilt): + """Windows: a non-exportable TPM P-256 key through the Microsoft Platform + Crypto Provider; Linux: a tpm2-tss key (runtime role).""" + + name = "TPM runtime key" + role = ROLE_RUNTIME + + +class WindowsHelloViewerKey(_NotBuilt): + """Windows: a Windows Hello (Passport) key, or a TPM key with a UI policy + (viewer role).""" + + name = "Windows Hello viewer key" + role = ROLE_VIEWER + presence = True + + +class HardwareDouble(DeviceKeyProvider): + """A stand-in for a hardware key in tests: a software key that counts + unwraps and, for a viewer key, the presence prompts it would have shown. + ``deny`` makes the next prompt fail, as a cancelled Touch ID would.""" + + def __init__(self, role: str, *, presence: bool = False, name: str = "") -> None: + self.role = role + self.presence = presence + self.name = name or f"test {role} key" + self.label = "hardware (test double)" + self._private: Optional[ec.EllipticCurvePrivateKey] = None + self.unwraps = 0 + self.prompts = 0 + self.deny = False + + def available(self) -> bool: + return True + + def ensure(self) -> None: + if self._private is None: + self._private = ec.generate_private_key(ec.SECP256R1()) + + def public(self) -> Any: + self.ensure() + assert self._private is not None + return self._private.public_key() + + def unwrap(self, sealed: bytes, info: bytes) -> bytes: + self.ensure() + assert self._private is not None + if self.presence: + self.prompts += 1 + if self.deny: + raise KeyHierarchyError(f"{self.name}: the person cancelled the prompt") + self.unwraps += 1 + return hpke_open(self._private, sealed, info) + + +def _platform_hardware() -> tuple[DeviceKeyProvider, DeviceKeyProvider]: + if sys.platform == "darwin": + return SecureEnclaveRuntimeKey(), SecureEnclaveViewerKey() + if sys.platform == "win32": + return TpmRuntimeKey(), WindowsHelloViewerKey() + return TpmRuntimeKey(), TpmRuntimeKey() + + +_injected: Optional[tuple[Unwrapper, Unwrapper]] = None + + +def use_device_keys( + runtime: Optional[Unwrapper], viewer: Optional[Unwrapper] = None +) -> None: + """Replace the device keys (tests); ``None`` restores the platform's.""" + global _injected + _injected = None if runtime is None else (runtime, viewer or runtime) + + +def _software_device(create: bool) -> Optional[SoftwareKey]: + from openadapt_flow import at_rest + + text = at_rest.device_secret(create=create) + if text is None: + return None + raw = base64.urlsafe_b64decode(text[len(at_rest.SOFTWARE_KEY_PREFIX) :].encode()) + return SoftwareKey(_from_scalar(raw), ROLE_DEVICE_SOFTWARE) + + +def device_keys(*, create: bool) -> Optional[tuple[Unwrapper, Unwrapper]]: + """``(runtime, viewer)``: hardware keys where this computer has them, + else one software key in both roles. None when there is none yet and + ``create`` is False.""" + if _injected is not None: + for key in _injected: + if isinstance(key, DeviceKeyProvider) and create: + key.ensure() + return _injected + runtime, viewer = _platform_hardware() + if runtime.available() and viewer.available(): + if create: + runtime.ensure() + viewer.ensure() + return runtime, viewer + software = _software_device(create) + if software is None: + return None + return software, software + + +def is_software(key: Unwrapper) -> bool: + return isinstance(key, SoftwareKey) + + +# -- recovery key -------------------------------------------------------------- + + +def _hpke_derive_p256(ikm: bytes) -> ec.EllipticCurvePrivateKey: + """RFC 9180 section 7.1.3 DeriveKeyPair for DHKEM(P-256, HKDF-SHA256).""" + import hmac + + suite_id = b"KEM" + (0x0010).to_bytes(2, "big") + + def extract(salt: bytes, label: bytes, ikm_: bytes) -> bytes: + return hmac.new( + salt or b"\0" * 32, b"HPKE-v1" + suite_id + label + ikm_, hashlib.sha256 + ).digest() + + def expand(prk: bytes, label: bytes, info: bytes, length: int) -> bytes: + labeled = length.to_bytes(2, "big") + b"HPKE-v1" + suite_id + label + info + out, block, counter = b"", b"", 1 + while len(out) < length: + block = hmac.new( + prk, block + labeled + bytes([counter]), hashlib.sha256 + ).digest() + out += block + counter += 1 + return out[:length] + + order = int("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", 16) + dkp_prk = extract(b"", b"dkp_prk", ikm) + for counter in range(256): + candidate = bytearray(expand(dkp_prk, b"candidate", bytes([counter]), 32)) + value = int.from_bytes(candidate, "big") + if 0 < value < order: + return ec.derive_private_key(value, ec.SECP256R1()) + raise KeyHierarchyError("recovery key derivation failed") # pragma: no cover + + +def recovery_code_to_key(code: str) -> SoftwareKey: + cleaned = "".join(ch for ch in code.upper() if ch.isalnum()) + try: + raw = base64.b32decode(cleaned + "=" * (-len(cleaned) % 8)) + except ValueError as exc: + raise KeyHierarchyError("that is not an OpenAdapt recovery code") from exc + if len(raw) != 32: + raise KeyHierarchyError("that is not an OpenAdapt recovery code") + return SoftwareKey(_hpke_derive_p256(raw), ROLE_RECOVERY, label="recovery") + + +def new_recovery_code() -> tuple[str, Recipient]: + """A new recovery code (52 characters) and its public recipient. The code + is shown once and never stored.""" + raw = secrets.token_bytes(32) + code = base64.b32encode(raw).decode("ascii").rstrip("=") + grouped = "-".join(code[i : i + 4] for i in range(0, len(code), 4)) + return grouped, recovery_code_to_key(code).recipient() + + +def _home() -> Path: + from openadapt_flow import at_rest + + return at_rest._home() + + +def recovery_path() -> Path: + return _home() / "keys" / "recovery.pub.json" + + +def save_recovery_recipient(recipient: Recipient) -> Path: + path = recovery_path() + _write_private( + path, + json.dumps( + { + "schema": "openadapt.ai/recovery-recipient/v1", + "public_key": _b64(_spki(recipient.public_key)), + "fingerprint": recipient.fpr, + }, + indent=2, + ).encode(), + ) + return path + + +def recovery_recipient() -> Optional[Recipient]: + path = recovery_path() + if not path.is_file(): + return None + entry = json.loads(path.read_text(encoding="utf-8")) + return Recipient.from_policy({**entry, "type": HPKE_P256, "role": ROLE_RECOVERY}) + + +# -- policy --------------------------------------------------------------------- + + +@dataclass +class Policy: + """The organization policy, or the solo default (no file).""" + + mode: str = "solo" + records: str = "inline" + recipients: list[Recipient] = field(default_factory=list) + key_archive: Optional[str] = None + require_hardware_device_key: bool = False + max_unarchived: int = 50 + source: str = "default (no policy)" + org: Optional[str] = None + + @property + def active_org(self) -> list[Recipient]: + return [ + r + for r in self.recipients + if r.status == "active" and r.role in (ROLE_ORG, ROLE_BREAK_GLASS) + ] + + +def _read_machine_source(source: str) -> Optional[dict]: + if source.startswith("HKLM\\"): + if sys.platform != "win32": + return None + try: # pragma: no cover - Windows only + import winreg + + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, source[5:]) as handle: + value, _ = winreg.QueryValueEx(handle, "Policy") + return json.loads(value) + except OSError: # pragma: no cover + return None + path = Path(source) + if not path.is_file(): + return None + if path.suffix == ".plist": + import plistlib + + data = plistlib.loads(path.read_bytes()) + body = data.get("Policy", data) if isinstance(data, dict) else None + return json.loads(body) if isinstance(body, (str, bytes)) else body + if os.name == "posix": + info = path.stat() + if info.st_uid != 0 or info.st_mode & (stat.S_IWGRP | stat.S_IWOTH): + raise KeyHierarchyError( + f"{path} must be owned by root and writable by root only; it is " + "not, so the machine policy can't be trusted. Nothing was written." + ) + return json.loads(path.read_text(encoding="utf-8")) + + +def load_policy() -> Policy: + """The first policy found: machine sources first, then ``OPENADAPT_POLICY``. + A user-writable file never overrides a machine one, and can set + organization mode only when it is root-owned (or the trust variable is + set, for development).""" + for source in MACHINE_POLICY_SOURCES: + try: + raw = _read_machine_source(source) + except (OSError, ValueError) as exc: + raise KeyHierarchyError( + f"the machine policy {source} can't be read: {exc}" + ) from exc + if raw is not None: + return _parse_policy(raw, f"machine: {source}") + configured = os.environ.get(POLICY_ENV) + if not configured: + return Policy() + path = Path(configured) + if not path.is_file(): + return Policy(source=f"{POLICY_ENV} names no file") + try: + raw = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise KeyHierarchyError(f"{path} is not a readable policy file") from exc + policy = _parse_policy(raw, f"file: {path}") + if policy.mode == "org" and os.name == "posix" and path.stat().st_uid != 0: + if os.environ.get(TRUST_USER_POLICY_ENV) != "1": + raise KeyHierarchyError( + f"{path} sets organization mode but is not owned by root, so it " + "can't be trusted (a user could swap the organization's key). " + "Install it as a machine policy. Nothing was written." + ) + policy.source += " (user-owned, trusted for development)" + return policy + + +def _parse_policy(raw: Any, source: str) -> Policy: + if not isinstance(raw, dict) or raw.get("schema") != POLICY_SCHEMA: + raise KeyHierarchyError(f"{source} is not an {POLICY_SCHEMA} policy") + mode = raw.get("mode", "solo") + if mode not in ("solo", "org"): + raise KeyHierarchyError(f"{source}: mode must be 'solo' or 'org'") + records = raw.get("records", "archive" if mode == "org" else "inline") + if records not in ("archive", "inline"): + raise KeyHierarchyError(f"{source}: records must be 'archive' or 'inline'") + entries = raw.get("recipients", []) + if not isinstance(entries, list): + raise KeyHierarchyError(f"{source}: recipients must be a list") + policy = Policy( + mode=mode, + records=records, + recipients=[Recipient.from_policy(entry) for entry in entries], + key_archive=raw.get("key_archive"), + require_hardware_device_key=bool(raw.get("require_hardware_device_key", False)), + max_unarchived=int(raw.get("max_unarchived", 50)), + source=source, + org=raw.get("org"), + ) + if mode == "org": + if not policy.active_org: + raise KeyHierarchyError( + f"{source} sets organization mode but names no active organization " + "recipient. Recording and running stop until it does." + ) + if records == "archive" and not policy.key_archive: + raise KeyHierarchyError( + f"{source} sets organization mode with records: archive but no " + "key_archive. Recording and running stop until it does." + ) + return policy + + +# -- bucket records --------------------------------------------------------------- + + +def _stanza_info(bucket_id: str, role: str, fpr: str) -> bytes: + return ( + _SUITE_LABEL + bucket_id.encode() + b"\0" + role.encode() + b"\0" + fpr.encode() + ) + + +def buckets_dir() -> Path: + return _home() / "keys" / "buckets" + + +def _write_private(path: Path, data: bytes) -> None: + from openadapt_flow import at_rest + + at_rest._private_dir(path.parent) + tmp = path.with_name(f".{path.name}.{secrets.token_hex(4)}.tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + os.write(fd, data) + os.fsync(fd) + finally: + os.close(fd) + os.replace(tmp, path) + + +@dataclass +class Bucket: + """A bucket key pair and its record (the private half, wrapped).""" + + bucket_id: str + private: Optional[ec.EllipticCurvePrivateKey] + public: ec.EllipticCurvePublicKey + record: dict[str, Any] + + @property + def fpr(self) -> str: + return fingerprint(self.public) + + def key_ref(self) -> dict[str, str]: + return {"bucket_id": self.bucket_id, "bucket_pub_fpr": self.fpr} + + +def _stanza(recipient: Recipient, bucket_id: str, secret: bytes) -> dict[str, str]: + info = _stanza_info(bucket_id, recipient.role, recipient.fpr) + return { + "role": recipient.role, + "type": recipient.type, + "fpr": recipient.fpr, + "ct": _b64(recipient.wrap(secret, info)), + } + + +def new_bucket(kind: str, policy: Optional[Policy] = None) -> Bucket: + """A fresh bucket for one sealed set, wrapped to the policy's recipients. + + Organization mode refuses without its active organization recipient and + archive (fail closed), and when ``max_unarchived`` records have not + reached the archive yet. + """ + policy = policy or load_policy() + device = device_keys(create=True) + assert device is not None + runtime, viewer = device + if policy.require_hardware_device_key and ( + is_software(runtime) or is_software(viewer) + ): + raise KeyHierarchyError( + "the policy requires a hardware device key, and this computer has " + "only a software key. Nothing was written." + ) + if policy.mode == "org" and policy.records == "archive": + pending = unarchived_count() + if pending >= policy.max_unarchived: + raise KeyHierarchyError( + f"{pending} encrypted sets have not reached the organization key " + f"archive ({policy.key_archive}); the policy allows " + f"{policy.max_unarchived}. Reconnect so they archive. Nothing was " + "written." + ) + private = ec.generate_private_key(ec.SECP256R1()) + bucket_id = secrets.token_hex(16) + secret = _scalar(private) + recipients: list[Recipient] = [] + seen: set[str] = set() + + def add(recipient: Recipient) -> None: + if recipient.fpr not in seen: + seen.add(recipient.fpr) + recipients.append(recipient) + + if not is_software(runtime): + add(Recipient(ROLE_RUNTIME, HPKE_P256, runtime.public())) + add(Recipient(viewer.role or ROLE_VIEWER, HPKE_P256, viewer.public())) + for item in policy.active_org: + add(item) + recovery = recovery_recipient() + if recovery is not None: + add(recovery) + record = { + "schema": BUCKET_SCHEMA, + "bucket_id": bucket_id, + "kind": kind, + "bucket_pub": _b64(_spki(private.public_key())), + "bucket_pub_fpr": fingerprint(private.public_key()), + "mode": policy.mode, + "records": policy.records, + "created_at": time.time(), + "archived": False, + "stanzas": [_stanza(r, bucket_id, secret) for r in recipients], + } + bucket = Bucket(bucket_id, private, private.public_key(), record) + if policy.records == "archive": + _store_local(record) + return bucket + + +def _record_path(bucket_id: str) -> Path: + if not all(ch in "0123456789abcdef" for ch in bucket_id) or len(bucket_id) != 32: + raise KeyHierarchyError("a bucket id is malformed") + return buckets_dir() / f"{bucket_id}.json" + + +def _store_local(record: dict[str, Any]) -> None: + _write_private( + _record_path(record["bucket_id"]), json.dumps(record, indent=2).encode() + ) + + +def _archive_dir(policy: Policy) -> Path: + target = policy.key_archive or "" + if target.startswith("file://"): + target = target[len("file://") :] + if "://" in target: + raise KeyHierarchyError( + f"key_archive {policy.key_archive}: only a local or mounted path " + "(file://) is supported yet; s3:// and smb:// are not built." + ) + return Path(target) + + +def archive(bucket: Bucket, policy: Optional[Policy] = None) -> bool: + """Copy the bucket record to the organization's archive. The runtime + stanza is never archived. Returns False (and keeps the record local, as + unarchived) when the archive is unreachable.""" + policy = policy or load_policy() + if policy.records != "archive": + return False + copy = dict(bucket.record) + copy["stanzas"] = [s for s in copy["stanzas"] if s["role"] != ROLE_RUNTIME] + try: + folder = _archive_dir(policy) + folder.mkdir(parents=True, exist_ok=True) + target = folder / f"{bucket.bucket_id}.json" + target.write_text(json.dumps(copy, indent=2), encoding="utf-8") + except OSError: + return False + bucket.record["archived"] = True + _store_local(bucket.record) + return True + + +def close(bucket: Bucket) -> None: + """The set is written: drop the runtime stanza, so only the viewer, + organization or recovery key opens it from now on.""" + bucket.record["stanzas"] = [ + s for s in bucket.record["stanzas"] if s["role"] != ROLE_RUNTIME + ] + if bucket.record.get("records") == "archive": + _store_local(bucket.record) + + +def unarchived_count() -> int: + folder = buckets_dir() + if not folder.is_dir(): + return 0 + count = 0 + for path in folder.glob("*.json"): + try: + if not json.loads(path.read_text(encoding="utf-8")).get("archived"): + count += 1 + except (OSError, ValueError): + continue + return count + + +def find_record( + key_ref: dict[str, Any], inline: Optional[dict[str, Any]] +) -> dict[str, Any]: + bucket_id = str(key_ref.get("bucket_id")) + if inline is not None: + return inline + path = _record_path(bucket_id) + if path.is_file(): + return json.loads(path.read_text(encoding="utf-8")) + raise NoRecipientKey( + f"this computer has no key record for bucket {bucket_id}. Open it as the " + "organization (its archive copy and key), or it was shredded." + ) + + +def _candidates() -> list[Unwrapper]: + out: list[Unwrapper] = [] + device = device_keys(create=False) + if device is not None: + runtime, viewer = device + out.append(runtime) + if viewer is not runtime: + out.append(viewer) + code = os.environ.get(RECOVERY_CODE_ENV) + if code: + out.append(recovery_code_to_key(code)) + org_file = os.environ.get(ORG_KEY_FILE_ENV) + if org_file: + try: + private = serialization.load_pem_private_key( + Path(org_file).read_bytes(), password=None + ) + except (OSError, ValueError) as exc: + raise KeyHierarchyError( + f"{ORG_KEY_FILE_ENV}: {org_file} can't be read" + ) from exc + out.append(SoftwareKey(private, ROLE_ORG, label="organization (file)")) + return out + + +def open_bucket(record: dict[str, Any], *, prefer_runtime: bool = True) -> Bucket: + """Unwrap a bucket's private half with the first key this computer holds.""" + if record.get("schema") != BUCKET_SCHEMA: + raise KeyHierarchyError("not a bucket record") + if record.get("shredded"): + raise NoRecipientKey("this bucket was shredded; nobody can open it") + bucket_id = str(record["bucket_id"]) + public = serialization.load_der_public_key(_unb64(record["bucket_pub"])) + if fingerprint(public) != record.get("bucket_pub_fpr"): + raise KeyHierarchyError( + "the bucket record's public key does not match its fingerprint" + ) + stanzas = {s.get("fpr"): s for s in record.get("stanzas") or []} + for key in _candidates(): + try: + fpr = key.fpr + except KeyHierarchyError: + continue + stanza = stanzas.get(fpr) + if stanza is None: + continue + info = _stanza_info(bucket_id, str(stanza["role"]), fpr) + try: + secret = key.unwrap(_unb64(stanza["ct"]), info) + except KeyHierarchyError: + raise + except Exception as exc: # noqa: BLE001 - wrong key or damaged stanza + raise KeyHierarchyError( + f"the {stanza['role']} stanza does not open" + ) from exc + private = _from_scalar(secret) + if fingerprint(private.public_key()) != record["bucket_pub_fpr"]: + raise KeyHierarchyError( + "the unwrapped bucket key does not match the record" + ) + return Bucket(bucket_id, private, private.public_key(), record) # type: ignore[arg-type] + raise NoRecipientKey( + "no key on this computer opens this encrypted set: it is wrapped for " + + ", ".join(f"{s.get('role')} {s.get('fpr')}" for s in stanzas.values()) + + ". Open it with its organization key, or set " + f"{RECOVERY_CODE_ENV}. Nothing was read." + ) + + +def shred(record: dict[str, Any], policy: Optional[Policy] = None) -> dict[str, Any]: + """Destroy every tracked copy of a bucket record: the local one + (overwritten, then deleted) and the archive copy. Returns the shred + record, which names the bucket and time and holds no key.""" + policy = policy or load_policy() + bucket_id = str(record["bucket_id"]) + removed: list[str] = [] + path = _record_path(bucket_id) + if path.is_file(): + size = path.stat().st_size + with open(path, "r+b") as handle: + handle.write(b"\0" * size) + handle.flush() + os.fsync(handle.fileno()) + path.unlink() + removed.append("local") + if policy.records == "archive" and policy.key_archive: + try: + target = _archive_dir(policy) / f"{bucket_id}.json" + if target.is_file(): + target.unlink() + removed.append("archive") + except (OSError, KeyHierarchyError): + pass + return { + "schema": SHRED_SCHEMA, + "bucket_id": bucket_id, + "shredded_at": time.time(), + "copies_destroyed": removed, + "records": record.get("records"), + } + + +def describe(policy: Policy) -> dict[str, Any]: + device = device_keys(create=False) + runtime_label = viewer_label = None + if device is not None: + runtime_label = getattr(device[0], "label", "") + viewer_label = getattr(device[1], "label", "") + recovery = recovery_recipient() + return { + "mode": policy.mode, + "records": policy.records, + "policy_source": policy.source, + "org_recipients": [ + {"role": r.role, "type": r.type, "fingerprint": r.fpr, "status": r.status} + for r in policy.recipients + ], + "key_archive": policy.key_archive, + "unarchived": unarchived_count() if policy.records == "archive" else 0, + "device_runtime_key": runtime_label, + "device_viewer_key": viewer_label, + "recovery_key": recovery.fpr if recovery else None, + } + + +__all__ = [ + "Bucket", + "DeviceKeyProvider", + "HardwareDouble", + "KeyHierarchyError", + "NoRecipientKey", + "Policy", + "Recipient", + "SoftwareKey", + "archive", + "close", + "describe", + "device_keys", + "find_record", + "fingerprint", + "hpke_open", + "hpke_seal", + "load_policy", + "new_bucket", + "new_recovery_code", + "open_bucket", + "recovery_code_to_key", + "save_recovery_recipient", + "shred", + "use_device_keys", +] diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index c7320f1e91..3751d9ea58 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -55,7 +55,7 @@ from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path, PurePosixPath -from typing import Final, Iterator, Literal, Optional +from typing import Any, Final, Iterator, Literal, Optional from openadapt_flow import crypto from openadapt_flow.sealed_maintenance import mutation_lock @@ -64,8 +64,8 @@ FORMAT: Final[str] = "openadapt-flow-sealed-set" FORMAT_VERSION: Final[int] = 1 SEALED_SUFFIX: Final[str] = ".enc" -#: Format version 3: a random data key wrapped for recipients -#: (:mod:`openadapt_flow.envelope`). +#: Format version 3: a per-set data key wrapped to a bucket key +#: (:mod:`openadapt_flow.key_hierarchy`), Tink streaming payload. ENVELOPE_VERSION: Final[int] = 3 _LEGACY_DERIVATION_FIELDS: Final[frozenset[str]] = frozenset( {"salt", "kdf", "kdf_n", "kdf_r", "kdf_p"} @@ -513,58 +513,170 @@ def _wrapping_aad(header: dict[str, object]) -> bytes: ).encode("utf-8") -def _passphrase_aad(header: dict[str, object]) -> bytes: - return b"openadapt-flow/sealed-set/passphrase-wrap/v3\0" + json.dumps( - {name: header[name] for name in ("format", "version", "kind", "data_key_id")}, - sort_keys=True, - separators=(",", ":"), - ).encode("utf-8") +_V3_WRAP: Final[bytes] = b"openadapt.ai/sealed-set/v3/wrap\0" +_V3_PAYLOAD: Final[bytes] = b"openadapt.ai/sealed-set/v3/payload\0" +_V3_HEADER: Final[bytes] = b"openadapt.ai/sealed-set/v3/header" +_V3_BUCKET_MAC: Final[bytes] = b"openadapt.ai/sealed-set/v3/bucket-mac" +PAYLOAD: Final[str] = "tink-aes256-gcm-hkdf-1mb" +_MAC_EXCLUDED: Final[frozenset[str]] = frozenset({"mac", "bucket_mac", "set_digest"}) + + +def _hkdf(ikm: bytes, info: bytes) -> bytes: + from cryptography.hazmat.primitives import hashes + from cryptography.hazmat.primitives.kdf.hkdf import HKDF + + return HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=info).derive(ikm) + + +def _v3_wrap_info(header: dict[str, object], fpr: str) -> bytes: + return ( + _V3_WRAP + + str(header["set_id"]).encode() + + str(header["kind"]).encode() + + fpr.encode() + ) + + +def _mac_body(header: dict[str, object]) -> bytes: + body = {k: v for k, v in header.items() if k not in _MAC_EXCLUDED} + return json.dumps(body, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +class V3Key: + """A version 3 set's data key. Files are Tink AES-256-GCM-HKDF 1 MiB + streams (:mod:`openadapt_flow.stream_aead`) under a payload key derived + from the DEK and the set id, with the file's set path as associated + data. ``bucket`` is the opened bucket, which MACs the header.""" + + def __init__(self, dek: bytes, set_id: str, bucket: object = None) -> None: + self._payload = _hkdf(dek, _V3_PAYLOAD + set_id.encode()) + self._header_key = _hkdf(dek, _V3_HEADER) + self.bucket = bucket + + def seal(self, plaintext: bytes, *, aad: bytes) -> bytes: + from openadapt_flow import stream_aead + + return crypto.SET3_FILE_MAGIC + stream_aead.encrypt( + self._payload, plaintext, aad + ) + + def open(self, container: bytes, *, aad: bytes) -> bytes: + from openadapt_flow import stream_aead + + if container[: len(crypto.SET3_FILE_MAGIC)] != crypto.SET3_FILE_MAGIC: + raise SealedSetError("not a version 3 sealed-set file") + try: + return stream_aead.decrypt( + self._payload, container[len(crypto.SET3_FILE_MAGIC) :], aad + ) + except stream_aead.StreamError as exc: + raise crypto.DecryptionError(str(exc)) from exc + def _bucket_mac_key(self) -> Optional[bytes]: + private = getattr(self.bucket, "private", None) + if private is None: + return None + scalar = private.private_numbers().private_value.to_bytes(32, "big") + return _hkdf(scalar, _V3_BUCKET_MAC) + + def stamp(self, header: dict[str, object]) -> None: + """Write the header MACs (DEK and bucket key) into ``header``.""" + import hmac + + body = _mac_body(header) + header["mac"] = hmac.new(self._header_key, body, hashlib.sha256).hexdigest() + bucket_key = self._bucket_mac_key() + if bucket_key is not None: + header["bucket_mac"] = hmac.new( + bucket_key, body, hashlib.sha256 + ).hexdigest() + + def check(self, header: dict[str, object]) -> None: + import hmac + + body = _mac_body(header) + want = hmac.new(self._header_key, body, hashlib.sha256).hexdigest() + bucket_key = self._bucket_mac_key() + bucket_want = ( + hmac.new(bucket_key, body, hashlib.sha256).hexdigest() + if bucket_key + else None + ) + got, bucket_got = header.get("mac"), header.get("bucket_mac") + if not ( + isinstance(got, str) + and hmac.compare_digest(got, want) + and isinstance(bucket_got, str) + and bucket_want is not None + and hmac.compare_digest(bucket_got, bucket_want) + ): + raise SealedSetError( + "the encrypted set's header was changed after it was written, or " + "was not written with its bucket key (header MAC mismatch)" + ) -def _envelope_data_key(header: dict[str, object], passphrase: Optional[str]) -> bytes: - """A version 3 set's DEK: through this computer's device identity or a - reviewer identity, else the legacy passphrase recipient.""" - from openadapt_flow import envelope + +def _open_v3(header: dict[str, object]) -> V3Key: + """Open a version 3 set: find its bucket record, unwrap the bucket key + with a key this computer holds, unwrap the DEK, check the header MACs.""" + from openadapt_flow import key_hierarchy as kh if header.get("shredded"): raise SealedSetError( - "this encrypted set was shredded: its wrapped keys were deleted, so " + "this encrypted set was shredded: its bucket key was destroyed, so " "nobody can open it" ) - data_key_id = header.get("data_key_id") - if not isinstance(data_key_id, str) or len(data_key_id) != 32: - raise SealedSetError("sealed-set envelope metadata is malformed") + key_ref = header.get("key_ref") + set_id = header.get("set_id") + if ( + not isinstance(key_ref, dict) + or not isinstance(set_id, str) + or len(set_id) != 32 + ): + raise SealedSetError("sealed-set version 3 header is malformed") + inline = header.get("bucket_record") try: - dek = envelope.unwrap(dict(header)) - except envelope.EnvelopeError as exc: + record = kh.find_record(key_ref, inline if isinstance(inline, dict) else None) + if record.get("bucket_id") != key_ref.get("bucket_id"): + raise SealedSetError("the bucket record belongs to another set") + bucket = kh.open_bucket(record) + except kh.NoRecipientKey as exc: + raise SealedSetKeyError(str(exc)) from exc + except kh.KeyHierarchyError as exc: raise SealedSetError(str(exc)) from exc - if dek is not None: - return dek - wrapped = header.get("passphrase") - if passphrase and isinstance(wrapped, str): - try: - dek = crypto.decrypt_bytes( - base64.b64decode(wrapped, validate=True), - passphrase, - aad=_passphrase_aad(header), - ) - except ValueError as exc: - raise SealedSetError("sealed-set passphrase wrap is malformed") from exc - if len(dek) == 32: - return dek - raise SealedSetKeyError( - "no key on this computer opens this encrypted set: it is wrapped for " - + (", ".join(str(r) for r in header.get("recipients") or []) or "no one") # type: ignore[union-attr] - + (" and a passphrase" if isinstance(wrapped, str) else "") - + ". Set OPENADAPT_AGE_IDENTITY_FILE to a recipient's identity, or the " - "passphrase it was sealed with. Nothing was read." + except RuntimeError as exc: # the device key is locked, missing or replaced + from openadapt_flow import at_rest + + if isinstance(exc, at_rest.LocalKeyError): + raise SealedSetKeyError(str(exc)) from exc + raise + if bucket.fpr != key_ref.get("bucket_pub_fpr"): + raise SealedSetError("the bucket record does not match the set's key reference") + stanza = next( + ( + s + for s in header.get("stanzas") or [] # type: ignore[union-attr] + if isinstance(s, dict) and s.get("fpr") == bucket.fpr + ), + None, ) + if stanza is None: + raise SealedSetError("the set has no data key wrapped to its bucket") + try: + dek = kh.hpke_open( + bucket.private, # type: ignore[arg-type] + base64.b64decode(str(stanza["ct"]), validate=True), + _v3_wrap_info(header, bucket.fpr), + ) + except Exception as exc: # noqa: BLE001 - wrong bucket or damaged stanza + raise SealedSetError("the set's data key does not unwrap") from exc + key = V3Key(dek, set_id, bucket) + key.check(header) + return key def _data_key(header: dict[str, object], passphrase: Optional[str]) -> bytes: """Unwrapped data keys stay in memory; no fallback key resolution here.""" - if header.get("version") == ENVELOPE_VERSION: - return _envelope_data_key(header, passphrase) if not passphrase: raise SealedSetKeyError("no key is configured to open this sealed set") try: @@ -602,7 +714,9 @@ def _data_key(header: dict[str, object], passphrase: Optional[str]) -> bytes: raise SealedSetError("sealed-set key header is malformed") from exc -def _derive(header: dict[str, object], passphrase: Optional[str]) -> crypto.SetKey: +def _derive(header: dict[str, object], passphrase: Optional[str]) -> Any: + if header.get("version") == ENVELOPE_VERSION: + return _open_v3(header) return crypto.SetKey(_data_key(header, passphrase)) @@ -789,7 +903,7 @@ def _reconcile_run_files( def _explicit_passphrase(passphrase: Optional[str]) -> bool: """Whether ``passphrase`` is a configured key rather than this computer's - local one (which the device recipient replaces in a version 3 set).""" + local one (which the key hierarchy replaces for new sets).""" if not passphrase: return False from openadapt_flow import at_rest @@ -797,58 +911,46 @@ def _explicit_passphrase(passphrase: Optional[str]) -> bool: return passphrase != at_rest.existing_key() -def _new_envelope( +def _new_v3( kind: str, passphrase: Optional[str] -) -> Optional[tuple[dict[str, object], bytes, Optional[str]]]: - """A version 3 header for a new set, its DEK and the device identity that - MACs it; None for a configured passphrase with no organization recipient - (the version 1 header Flow always wrote).""" - from openadapt_flow import envelope +) -> Optional[tuple[dict[str, object], V3Key]]: + """A version 3 header for a new set and its key; None for a configured + passphrase outside organization mode (the version 1 header Flow always + wrote: explicit keys still win, deprecated).""" + from openadapt_flow import key_hierarchy as kh try: - org = envelope.org_recipients() - except envelope.EnvelopeError as exc: + policy = kh.load_policy() + if _explicit_passphrase(passphrase) and policy.mode != "org": + return None + bucket = kh.new_bucket(kind, policy) + if policy.records == "archive": + kh.archive(bucket, policy) + except kh.KeyHierarchyError as exc: raise SealedSetError(f"Not writing an encrypted {kind}: {exc}") from exc - explicit = _explicit_passphrase(passphrase) - if explicit and not org: - return None - device: Optional[str] = None - recipients: list[str] = [] - if not explicit: - device = envelope.device_identity(create=True) - assert device is not None - recipients.append(envelope.device_recipient(device)) - recipients += [r for r in org if r not in recipients] + set_id = secrets.token_hex(16) dek = secrets.token_bytes(32) header: dict[str, object] = { "format": FORMAT, "version": ENVELOPE_VERSION, + "set_id": set_id, "kind": kind, "cipher": "AES-256-GCM", - "wrap": "age-x25519", - "data_key_id": secrets.token_hex(16), - "recipients": recipients, + "payload": PAYLOAD, + "key_ref": bucket.key_ref(), } - header["age"] = envelope.wrap(dek, header, recipients) - if explicit: - header["passphrase"] = base64.b64encode( - crypto.encrypt_bytes(dek, passphrase, aad=_passphrase_aad(header)) - ).decode("ascii") - return header, dek, device - - -def _own_device(header: dict[str, object]) -> Optional[str]: - """This computer's device identity when ``header`` names it.""" - if header.get("version") != ENVELOPE_VERSION: - return None - from openadapt_flow import envelope - - device = envelope.device_identity(create=False) - if device is None: - return None - if envelope.device_recipient(device) in (header.get("recipients") or []): # type: ignore[operator] - return device - return None + header["stanzas"] = [ + { + "type": kh.STANZA_TYPE, + "fpr": bucket.fpr, + "ct": base64.b64encode( + kh.hpke_seal(bucket.public, dek, _v3_wrap_info(header, bucket.fpr)) + ).decode("ascii"), + } + ] + if policy.records == "inline": + header["bucket_record"] = bucket.record + return header, V3Key(dek, set_id, bucket) class SealedSetWriter: @@ -872,7 +974,7 @@ def __init__( self.root = Path(root) self.kind: Kind = kind self._codecs: dict[str, Codec] = {} - self._device: Optional[str] = None + self._new = False self._hashes: dict[str, str] = {} self._lines: dict[str, list[bytes]] = {} self._lock = threading.RLock() @@ -886,7 +988,6 @@ def _initialize(self, passphrase: Optional[str], *, resume: bool) -> None: opened = SealedSet.open(self.root, passphrase, expect=kind) self._header: dict[str, object] = dict(opened._header) self._key = opened._key - self._device = _own_device(self._header) self._header_revision = _sha256((self.root / HEADER).read_bytes()) for rel, entry in opened._files.items(): self._codecs[rel] = entry["codec"] # type: ignore[assignment] @@ -895,10 +996,10 @@ def _initialize(self, passphrase: Optional[str], *, resume: bool) -> None: if is_sealed(self.root): raise SealedSetError(f"{self.root} is already a sealed set") self.root.mkdir(parents=True, exist_ok=True) - envelope_header = _new_envelope(kind, passphrase) - if envelope_header is not None: - self._header, dek, self._device = envelope_header - self._key = crypto.SetKey(dek) + created = _new_v3(kind, passphrase) + if created is not None: + self._header, self._key = created + self._new = True self._write_header() return if not passphrase: @@ -917,14 +1018,8 @@ def _initialize(self, passphrase: Optional[str], *, resume: bool) -> None: self._write_header() def _write_header(self) -> None: - if self._header.get("version") == ENVELOPE_VERSION: - from openadapt_flow import envelope - - self._header.pop("device_mac", None) - if self._device is not None: - self._header["device_mac"] = envelope.device_mac( - self._header, self._device - ) + if isinstance(self._key, V3Key): + self._key.stamp(self._header) raw = json.dumps(self._header, indent=2, sort_keys=True).encode("utf-8") _atomic_write(self.root / HEADER, raw) self._header_revision = _sha256(raw) @@ -1085,9 +1180,27 @@ def finalize(self, *, adopt_external: bool = False) -> str: # Informational copy for inventories; the authenticated value is # the one recomputed from the sealed index on open. self._header["set_digest"] = digest + if self._new and isinstance(self._key, V3Key) and self.kind != "bundle": + self._close_bucket() self._write_header() return digest + def _close_bucket(self) -> None: + """The set is written: its bucket record loses the runtime stanza, so + from now on only the viewer, organization or recovery key opens it. + A bundle keeps it: programs replay unattended.""" + from openadapt_flow import key_hierarchy as kh + + bucket = self._key.bucket # type: ignore[union-attr] + if bucket is None: + return + kh.close(bucket) + if "bucket_record" in self._header: + self._header["bucket_record"] = bucket.record + elif bucket.record.get("records") == "archive": + kh.archive(bucket) + self._new = False + # -- path-based helpers ------------------------------------------------------ # @@ -1378,76 +1491,70 @@ def _replace_header(root: Path, header: dict[str, object]) -> None: os.close(fd) -def recipients_of(root: Path | str) -> list[str]: - """The public recipients a version 3 set is wrapped for (no key needed).""" - header = read_header(root) - listed = ( - header.get("recipients") if header.get("version") == ENVELOPE_VERSION else [] - ) - return [str(r) for r in listed or []] # type: ignore[union-attr] +def key_record_of(root: Path | str) -> Optional[dict[str, object]]: + """The bucket record of a version 3 set (no key material in the clear): + inline in the header, or this computer's local copy. None otherwise.""" + from openadapt_flow import key_hierarchy as kh - -def add_recipients(root: Path | str, recipients: list[str]) -> list[str]: - """Wrap a version 3 set's data key for more recipients (a share, or an - organization recipient added later). No file is re-encrypted. Run it on - the computer that wrote the set, so its device MAC stays valid.""" - from openadapt_flow import envelope - - base = Path(_abs(root)) - with mutation_lock(base): - header = read_header(base) - if header.get("version") != ENVELOPE_VERSION: - raise SealedSetError( - f"{base} is an older encrypted set (version " - f"{header.get('version')}); only version 3 sets have recipients" - ) - SealedSet.open(base, None) # the set must verify before it is shared - dek = _data_key(header, None) - wanted = list(header.get("recipients") or []) # type: ignore[call-overload] - for item in recipients: - text = str(envelope.parse_recipient(item)) - if text not in wanted: - wanted.append(text) - header["recipients"] = wanted - header["age"] = envelope.wrap(dek, header, wanted) - device = _own_device(header) - header.pop("device_mac", None) - if device is not None: - header["device_mac"] = envelope.device_mac(header, device) - _replace_header(base, header) - return wanted + header = read_header(root) + if header.get("version") != ENVELOPE_VERSION or header.get("shredded"): + return None + inline = header.get("bucket_record") + try: + return kh.find_record( + header.get("key_ref") or {}, # type: ignore[arg-type] + inline if isinstance(inline, dict) else None, + ) + except kh.KeyHierarchyError: + return None -def shred(root: Path | str) -> list[str]: - """Crypto-shred a sealed set: delete every wrapped copy of its data key, - and the durable checkpoints and other stores' ciphertext inside it. +def shred(root: Path | str) -> dict[str, object]: + """Crypto-shred a sealed set. - The set's own files stay on disk as ciphertext that no key opens. Returns - the set-relative paths of the other stores' files that were deleted. This - can't be undone; there is no recovery copy anywhere. + A version 3 set: destroy its bucket key's tracked copies (this + computer's record, overwritten then deleted, and the organization + archive's copy), drop the record and data-key stanza from the header, + and delete the durable checkpoints and other stores' ciphertext inside + it. In solo mode (record inline) this reaches only the copy on this disk: + backups still hold a record the recovery key opens. An older set loses + its salt (v1) or wrapped key (v2) instead. Returns the shred record. It + can't be undone. """ + from openadapt_flow import key_hierarchy as kh + base = Path(_abs(root)) removed: list[str] = [] with mutation_lock(base): header = read_header(base) + shred_record: dict[str, object] = {"schema": kh.SHRED_SCHEMA} + if header.get("version") == ENVELOPE_VERSION and not header.get("shredded"): + inline = header.get("bucket_record") + try: + record = kh.find_record( + header.get("key_ref") or {}, # type: ignore[arg-type] + inline if isinstance(inline, dict) else None, + ) + shred_record = kh.shred(record) + except kh.KeyHierarchyError: + shred_record["copies_destroyed"] = [] for name in ( - "age", - "passphrase", + "bucket_record", + "stanzas", "wrapped_key", "salt", "kdf", "kdf_n", "kdf_r", "kdf_p", - "device_mac", + "mac", + "bucket_mac", ): header.pop(name, None) header["shredded"] = True - if header.get("version") != ENVELOPE_VERSION: - # Without its salt (v1) or wrapped key (v2) the DEK can't be - # derived; record the set as shredded the same way. - header["version"] = ENVELOPE_VERSION - header.setdefault("data_key_id", secrets.token_hex(16)) + header["version"] = ENVELOPE_VERSION + header.setdefault("set_id", secrets.token_hex(16)) + header["shred_record"] = shred_record _replace_header(base, header) for rel in _disk_files(base): path = base / rel @@ -1455,19 +1562,23 @@ def shred(root: Path | str) -> list[str]: data = path.read_bytes() except OSError: continue - if data[: len(crypto.SET_FILE_MAGIC)] == crypto.SET_FILE_MAGIC: + if data[: len(crypto.SET_FILE_MAGIC)] in ( + crypto.SET_FILE_MAGIC, + crypto.SET3_FILE_MAGIC, + ): continue # the set's own ciphertext, now unopenable if crypto.is_encrypted(data): path.unlink() removed.append(rel) - return removed + shred_record["store_files_deleted"] = removed + return shred_record __all__ = [ "BUNDLE_FILES", "ENVELOPE_VERSION", - "add_recipients", - "recipients_of", + "V3Key", + "key_record_of", "shred", "HEADER", "LIBRARY_FILES", diff --git a/packages/flow/openadapt_flow/stream_aead.py b/packages/flow/openadapt_flow/stream_aead.py new file mode 100644 index 0000000000..6a0554f7de --- /dev/null +++ b/packages/flow/openadapt_flow/stream_aead.py @@ -0,0 +1,113 @@ +"""Tink's AES-256-GCM-HKDF streaming AEAD wire format, 1 MiB segments. + +This is the payload format of a version 3 sealed set +(:mod:`openadapt_flow.sealed_set`). It follows Tink's ``AES256_GCM_HKDF_1MB`` +key template byte for byte (https://developers.google.com/tink/streaming-aead/ +aes_gcm_hkdf_streaming), built from the AES-GCM and HKDF primitives of the +``cryptography`` package; ``tests/test_stream_aead.py`` checks it against Tink +itself when Tink is installed. Nothing here is a new construction: + +* header: one length byte (40), a 32-byte random salt, a 7-byte random nonce + prefix; +* the segment key is HKDF-SHA256(ikm=key, salt=salt, info=associated data), + 32 bytes, so the associated data (the file's path in its set) is bound + through the key; +* segment ``i`` is AES-256-GCM under the nonce ``prefix || i (4 bytes, big + endian) || last-segment flag (1 byte)``, with no further associated data; +* ciphertext segments are 1 MiB, the first shortened by the header; the last + segment is flagged, so a truncated stream fails to open. + +It works on whole byte strings: the files Flow encrypts are read and written +in memory. +""" + +from __future__ import annotations + +import os +from typing import Final + +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.kdf.hkdf import HKDF + +KEY_SIZE: Final[int] = 32 +SEGMENT_SIZE: Final[int] = 1024 * 1024 +_SALT: Final[int] = KEY_SIZE +_PREFIX: Final[int] = 7 +_TAG: Final[int] = 16 +HEADER_SIZE: Final[int] = 1 + _SALT + _PREFIX + + +class StreamError(ValueError): + """A stream is malformed, truncated, tampered with, or under another key.""" + + +def _segment_key(key: bytes, salt: bytes, aad: bytes) -> AESGCM: + if len(key) != KEY_SIZE: + raise StreamError("a streaming key must be 32 bytes") + derived = HKDF(algorithm=hashes.SHA256(), length=KEY_SIZE, salt=salt, info=aad) + return AESGCM(derived.derive(key)) + + +def _nonce(prefix: bytes, index: int, last: bool) -> bytes: + return prefix + index.to_bytes(4, "big") + (b"\x01" if last else b"\x00") + + +def encrypt(key: bytes, plaintext: bytes, aad: bytes) -> bytes: + salt = os.urandom(_SALT) + prefix = os.urandom(_PREFIX) + aead = _segment_key(key, salt, aad) + out = [bytes([HEADER_SIZE]), salt, prefix] + first = SEGMENT_SIZE - HEADER_SIZE - _TAG + rest = SEGMENT_SIZE - _TAG + pieces = [plaintext[:first]] + offset = first + while offset < len(plaintext): + pieces.append(plaintext[offset : offset + rest]) + offset += rest + for index, piece in enumerate(pieces): + last = index == len(pieces) - 1 + out.append(aead.encrypt(_nonce(prefix, index, last), piece, None)) + return b"".join(out) + + +def decrypt(key: bytes, ciphertext: bytes, aad: bytes) -> bytes: + if len(ciphertext) < HEADER_SIZE + _TAG or ciphertext[0] != HEADER_SIZE: + raise StreamError("not an AES-256-GCM-HKDF stream") + salt = ciphertext[1 : 1 + _SALT] + prefix = ciphertext[1 + _SALT : HEADER_SIZE] + aead = _segment_key(key, salt, aad) + body = ciphertext[HEADER_SIZE:] + sizes = [SEGMENT_SIZE - HEADER_SIZE] + total = sizes[0] + while total < len(body): + sizes.append(SEGMENT_SIZE) + total += SEGMENT_SIZE + out = [] + offset = 0 + for index, size in enumerate(sizes): + segment = body[offset : offset + size] + offset += size + last = offset >= len(body) + if len(segment) < _TAG: + raise StreamError("the stream is truncated") + try: + out.append(aead.decrypt(_nonce(prefix, index, last), segment, None)) + except InvalidTag as exc: + raise StreamError( + "the stream does not authenticate (wrong key, tampered or truncated)" + ) from exc + if last: + break + return b"".join(out) + + +__all__ = [ + "HEADER_SIZE", + "KEY_SIZE", + "SEGMENT_SIZE", + "StreamError", + "decrypt", + "encrypt", +] diff --git a/packages/flow/pyproject.toml b/packages/flow/pyproject.toml index 64af7fbe5d..a3bd1c109b 100644 --- a/packages/flow/pyproject.toml +++ b/packages/flow/pyproject.toml @@ -54,13 +54,12 @@ dependencies = [ # Workflow.save(encrypt=True) / load(key=...) and encrypted checkpoints work # out of the box in a regulated/PHI deployment; the audited AEAD substrate # for docs/phi_at_rest.md. Imported lazily, only on the encryption path. - "cryptography>=42.0", - # Encryption at rest is on by default (docs/phi_at_rest.md). Each encrypted - # recording, bundle or run has its own data key, wrapped with age (X25519) - # for its recipients through pyrage (MIT, Rust bindings to the audited rage - # crate), and this computer's device key lives in the OS keychain through - # keyring (MIT). Both are imported lazily, only on the encryption path. - "pyrage>=1.2,<2", + # 50 brings HPKE (RFC 9180), which wraps each encrypted set's data key + # (docs/phi_at_rest.md, openadapt_flow.key_hierarchy). + "cryptography>=50.0", + # Encryption at rest is on by default. Where this computer has no secure + # hardware key, its software device key lives in the OS keychain through + # keyring (MIT). Imported lazily, only on the encryption path. "keyring>=24", # The portable contracts (request, result and receipt models). They live # in openadapt-types, which depends only on pydantic, so a consumer of the @@ -114,6 +113,8 @@ browser = [ "playwright>=1.44", ] dev = [ + # tests/test_stream_aead.py checks the sealed-set v3 payload against Tink. + "tink>=1.16,<2", # The test suite exercises record, compile and replay. "numpy>=1.26", "opencv-python>=4.9,<5.1", diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index 839abcc75e..d980bc776e 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -79,9 +79,9 @@ def _isolation_env(root: Path) -> dict[str, str | None]: # OS keychain (no dialog, no write to the person's login keychain). "OPENADAPT_FLOW_KEY_STORE": "file", "OPENADAPT_ENCRYPT_AT_REST": None, - "OPENADAPT_ORG_RECIPIENTS": None, - "OPENADAPT_POLICY_FILE": str(root / ".no-policy.json"), - "OPENADAPT_AGE_IDENTITY_FILE": None, + "OPENADAPT_POLICY": None, + "OPENADAPT_RECOVERY_CODE": None, + "OPENADAPT_ORG_KEY_FILE": None, } diff --git a/packages/flow/tests/test_envelope_at_rest.py b/packages/flow/tests/test_envelope_at_rest.py deleted file mode 100644 index 8e1c5906c4..0000000000 --- a/packages/flow/tests/test_envelope_at_rest.py +++ /dev/null @@ -1,350 +0,0 @@ -"""Encrypted by default: the device key, recipients, sharing and shredding. - -Every test injects an in-memory keychain (or forces the file store), so no -test reads or writes the real OS keychain or raises an OS dialog. -""" - -from __future__ import annotations - -import base64 -import json -import os -from pathlib import Path -from typing import Optional - -import pyrage -import pytest - -from openadapt_flow import at_rest, crypto, envelope, sealed_set - -PNG = b"\x89PNG\r\n\x1a\n" + b"synthetic pixels" - - -class MemoryKeychain(at_rest.KeyStore): - """A keychain that lives in this test only.""" - - def __init__(self, *, broken: bool = False) -> None: - self.values: dict[str, str] = {} - self.broken = broken - self.reads = 0 - - def get(self, account: str) -> Optional[str]: - if self.broken: - raise at_rest.KeyStoreUnavailable("no keychain backend (test)") - self.reads += 1 - return self.values.get(account) - - def set(self, account: str, value: str) -> None: - if self.broken: - raise at_rest.KeyStoreUnavailable("no keychain backend (test)") - self.values[account] = value - - -@pytest.fixture -def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - for name in ( - at_rest.OPT_OUT_ENV, - at_rest.MODE_ENV, - at_rest.ENCRYPT_ENV, - at_rest.KEY_STORE_ENV, - crypto.ENV_KEY, - sealed_set.RECORDING_ENV_KEY, - envelope.ORG_RECIPIENTS_ENV, - envelope.IDENTITY_FILE_ENV, - ): - monkeypatch.delenv(name, raising=False) - monkeypatch.setenv(envelope.POLICY_FILE_ENV, str(tmp_path / "no-policy.json")) - root = tmp_path / "home" - monkeypatch.setenv(at_rest.HOME_ENV, str(root)) - keychain = MemoryKeychain() - at_rest.use_key_store(keychain) - at_rest._reset_for_tests() - yield root, keychain - at_rest.use_key_store(None) - at_rest._reset_for_tests() - - -def _seal(root: Path, files: dict[str, bytes], kind: str = "run") -> None: - with sealed_set.writing(root, kind, sealed_set.passphrase_for(kind)) as writer: - for rel, data in files.items(): - writer.write(rel, data) - - -def _header(root: Path) -> dict: - return json.loads((root / sealed_set.HEADER).read_text()) - - -def _on_disk(root: Path) -> list[bytes]: - return [p.read_bytes() for p in root.rglob("*") if p.is_file()] - - -# -- the device key ------------------------------------------------------------ - - -def test_device_key_goes_to_the_keychain_with_a_marker_only(home, capsys) -> None: - root, keychain = home - first = at_rest.device_secret(create=True) - assert first and first.startswith("AGE-SECRET-KEY-1") - assert list(keychain.values.values()) == [first] - marker = json.loads((root / "keys" / at_rest.MARKER_NAME).read_text()) - assert marker["store"] == "keychain" - assert first not in json.dumps(marker) # a check value, never the key - assert not (root / "keys" / at_rest.DEVICE_KEY_NAME).exists() - assert not (root / "keys" / at_rest.KEY_NAME).exists() - assert at_rest.device_secret(create=True) == first - assert "OS keychain entry" in capsys.readouterr().err - - -def test_a_missing_keychain_entry_fails_closed_and_mints_nothing(home) -> None: - root, keychain = home - at_rest.device_secret(create=True) - keychain.values.clear() - with pytest.raises(at_rest.LocalKeyError, match="missing"): - at_rest.local_key() - assert keychain.values == {} - assert not (root / "keys" / at_rest.DEVICE_KEY_NAME).exists() - - -def test_a_replaced_keychain_entry_fails_closed(home) -> None: - _root, keychain = home - at_rest.device_secret(create=True) - account = next(iter(keychain.values)) - keychain.values[account] = str(pyrage.x25519.Identity.generate()) - with pytest.raises(at_rest.LocalKeyError, match="does not hold"): - at_rest.device_secret(create=False) - - -def test_a_locked_keychain_fails_closed_once_the_key_lives_there(home) -> None: - _root, keychain = home - at_rest.device_secret(create=True) - keychain.broken = True - with pytest.raises(at_rest.LocalKeyError, match="Unlock the keychain"): - at_rest.existing_key() - - -def test_no_keychain_falls_back_to_a_private_file_with_a_warning(home, capsys) -> None: - root, keychain = home - keychain.broken = True - secret = at_rest.device_secret(create=True) - path = root / "keys" / at_rest.DEVICE_KEY_NAME - assert path.read_text().strip() == secret - if os.name == "posix": - assert path.stat().st_mode & 0o777 == 0o600 - assert path.parent.stat().st_mode & 0o777 == 0o700 - assert "WARNING: no OS keychain is available" in capsys.readouterr().err - - -def test_keychain_only_refuses_without_a_keychain(home, monkeypatch) -> None: - _root, keychain = home - keychain.broken = True - monkeypatch.setenv(at_rest.KEY_STORE_ENV, "keychain") - with pytest.raises(at_rest.LocalKeyError, match="keychain"): - at_rest.device_secret(create=True) - - -def test_a_key_file_from_an_earlier_version_keeps_working(home) -> None: - root, keychain = home - legacy = base64.urlsafe_b64encode(os.urandom(32)).decode() - keys = root / "keys" - keys.mkdir(parents=True, mode=0o700) - (keys / at_rest.KEY_NAME).write_text(legacy + "\n") - os.chmod(keys / at_rest.KEY_NAME, 0o600) - assert at_rest.local_key() == legacy - assert crypto.resolve_key(None) == legacy - assert keychain.values == {} - - -def test_tests_never_reach_the_real_keychain(monkeypatch) -> None: - at_rest.use_key_store(None) - monkeypatch.delenv(at_rest.KEY_STORE_ENV, raising=False) - assert "PYTEST_CURRENT_TEST" in os.environ - assert at_rest._store_choice() == "file" - - -# -- the opt-out ----------------------------------------------------------------- - - -def test_encrypt_zero_turns_it_off_with_one_warning_line(home, capsys) -> None: - root, _keychain = home - os.environ[at_rest.ENCRYPT_ENV] = "0" - try: - assert at_rest.seal_new("a recording", root / "rec") is False - assert at_rest.seal_new("a recording", root / "rec") is False - err = [line for line in capsys.readouterr().err.splitlines() if line] - assert len(err) == 1 and err[0].startswith("WARNING:") - ledger = (root / at_rest.LEDGER_NAME).read_text().splitlines() - assert json.loads(ledger[0])["reason"] == "OPENADAPT_ENCRYPT_AT_REST=0" - finally: - del os.environ[at_rest.ENCRYPT_ENV] - - -def test_a_mistyped_encrypt_setting_is_refused(monkeypatch) -> None: - monkeypatch.setenv(at_rest.ENCRYPT_ENV, "nope") - with pytest.raises(ValueError): - at_rest.opt_out_reason() - - -def test_strict_mode_ignores_the_opt_out(home, monkeypatch) -> None: - monkeypatch.setenv(at_rest.ENCRYPT_ENV, "0") - monkeypatch.setenv(at_rest.MODE_ENV, "strict") - assert at_rest.seal_new("a recording", "x") is True - - -def test_new_artifacts_are_sealed_by_default(home) -> None: - assert at_rest.DEFAULT_SEALS_ARTIFACTS is True - assert at_rest.seals_by_default() is True - - -# -- recipients ------------------------------------------------------------------ - - -def test_a_new_run_is_wrapped_for_the_device_only_ciphertext_on_disk(home) -> None: - root, _keychain = home - run = root.parent / "run" - _seal(run, {"report.json": b'{"typed": "a synthetic value"}', "steps/a.png": PNG}) - header = _header(run) - assert header["version"] == sealed_set.ENVELOPE_VERSION - device = at_rest.device_secret(create=False) - assert header["recipients"] == [envelope.device_recipient(device)] - assert "passphrase" not in header and "device_mac" in header - for data in _on_disk(run): - assert b"a synthetic value" not in data and not data.startswith(PNG[:8]) - assert sealed_set.read_bytes(run / "steps" / "a.png") == PNG - - -def test_another_computer_cannot_open_it(home, monkeypatch) -> None: - root, _keychain = home - run = root.parent / "run" - _seal(run, {"report.json": b"{}"}) - monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "elsewhere")) - with pytest.raises(sealed_set.SealedSetKeyError, match="no key on this computer"): - sealed_set.SealedSet.open(run, None) - - -def test_an_org_recipient_reads_it_without_the_device(home, monkeypatch) -> None: - root, _keychain = home - org = pyrage.x25519.Identity.generate() - monkeypatch.setenv(envelope.ORG_RECIPIENTS_ENV, str(org.to_public())) - run = root.parent / "run" - _seal(run, {"report.json": b"evidence"}) - assert str(org.to_public()) in sealed_set.recipients_of(run) - identity = root.parent / "reviewer.txt" - identity.write_text(f"# reviewer\n{org}\n") - monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "reviewer-home")) - monkeypatch.setenv(envelope.IDENTITY_FILE_ENV, str(identity)) - assert sealed_set.SealedSet.open(run, None).read_bytes("report.json") == b"evidence" - - -def test_an_org_recipient_from_the_policy_file(home, monkeypatch, tmp_path) -> None: - org = pyrage.x25519.Identity.generate() - policy = tmp_path / "policy.json" - policy.write_text(json.dumps({"recipients": [str(org.to_public())]})) - monkeypatch.setenv(envelope.POLICY_FILE_ENV, str(policy)) - assert envelope.org_recipients() == [str(org.to_public())] - - -def test_a_malformed_org_recipient_refuses_the_write(home, monkeypatch) -> None: - root, _keychain = home - monkeypatch.setenv(envelope.ORG_RECIPIENTS_ENV, "age1notarecipient") - with pytest.raises(sealed_set.SealedSetError, match="not an age recipient"): - _seal(root.parent / "run", {"report.json": b"{}"}) - - -def test_share_rewraps_without_reencrypting(home, monkeypatch) -> None: - root, _keychain = home - run = root.parent / "run" - _seal(run, {"report.json": b"shared"}) - before = (run / "report.json.enc").read_bytes() - friend = pyrage.x25519.Identity.generate() - sealed_set.add_recipients(run, [str(friend.to_public())]) - assert (run / "report.json.enc").read_bytes() == before - assert sealed_set.read_bytes(run / "report.json") == b"shared" - identity = root.parent / "friend.txt" - identity.write_text(str(friend)) - monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "friend-home")) - monkeypatch.setenv(envelope.IDENTITY_FILE_ENV, str(identity)) - assert sealed_set.read_bytes(run / "report.json") == b"shared" - - -def test_shred_makes_it_unreadable_and_drops_checkpoints(home) -> None: - root, _keychain = home - run = root.parent / "run" - run.mkdir() - (run / "checkpoints").mkdir() - checkpoint = crypto.encrypt_bytes(b"{}", "k" * 20, aad=crypto.CHECKPOINT_AAD) - (run / "checkpoints" / "s1.enc").write_bytes(checkpoint) - writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) - writer.write("report.json", b"gone") - writer.finalize(adopt_external=True) - removed = sealed_set.shred(run) - assert removed == ["checkpoints/s1.enc"] - assert not (run / "checkpoints" / "s1.enc").exists() - with pytest.raises(sealed_set.SealedSetError, match="shredded"): - sealed_set.read_bytes(run / "report.json") - assert "age" not in _header(run) - - -def test_shred_deletes_other_stores_ciphertext(home) -> None: - root, _keychain = home - run = root.parent / "run" - run.mkdir() - (run / "pending.json").write_bytes( - crypto.encrypt_bytes(b"{}", "k" * 20, aad=crypto.CHECKPOINT_AAD) - ) - writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) - writer.write("report.json", b"gone") - writer.finalize(adopt_external=True) - assert sealed_set.shred(run) == ["pending.json"] - assert not (run / "pending.json").exists() - - -def test_a_forged_header_for_this_device_is_refused(home) -> None: - """age has no sender authentication: the device MAC is what stops a - header someone else wrapped for this computer's public recipient.""" - root, _keychain = home - run = root.parent / "run" - _seal(run, {"report.json": b"real"}) - header = _header(run) - forged = dict(header) - forged["age"] = envelope.wrap(os.urandom(32), forged, forged["recipients"]) - (run / sealed_set.HEADER).write_text(json.dumps(forged)) - with pytest.raises(sealed_set.SealedSetError, match="device MAC"): - sealed_set.read_bytes(run / "report.json") - forged.pop("device_mac") - (run / sealed_set.HEADER).write_text(json.dumps(forged)) - with pytest.raises(sealed_set.SealedSetError, match="device MAC"): - sealed_set.read_bytes(run / "report.json") - - -def test_a_configured_key_keeps_the_header_flow_always_wrote(home, monkeypatch) -> None: - root, keychain = home - monkeypatch.setenv(crypto.ENV_KEY, "a-deployment-key-for-tests") - run = root.parent / "run" - _seal(run, {"report.json": b"{}"}) - assert _header(run)["version"] == 1 - assert keychain.values == {} # no device key was needed - - -def test_a_configured_key_and_an_org_recipient_both_open_it(home, monkeypatch) -> None: - root, _keychain = home - org = pyrage.x25519.Identity.generate() - monkeypatch.setenv(crypto.ENV_KEY, "a-deployment-key-for-tests") - monkeypatch.setenv(envelope.ORG_RECIPIENTS_ENV, str(org.to_public())) - run = root.parent / "run" - _seal(run, {"report.json": b"both"}) - header = _header(run) - assert header["version"] == 3 and "passphrase" in header - assert header["recipients"] == [str(org.to_public())] - monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "other")) - assert sealed_set.read_bytes(run / "report.json") == b"both" - monkeypatch.setenv(crypto.ENV_KEY, "the-wrong-key-entirely") - with pytest.raises((sealed_set.SealedSetError, crypto.CryptoError)): - sealed_set.SealedSet.open(run, None) - - -def test_a_legacy_plaintext_folder_still_reads(home) -> None: - root, _keychain = home - plain = root.parent / "old-run" - plain.mkdir() - (plain / "report.json").write_bytes(b"{}") - assert sealed_set.read_bytes(plain / "report.json") == b"{}" diff --git a/packages/flow/tests/test_key_hierarchy.py b/packages/flow/tests/test_key_hierarchy.py new file mode 100644 index 0000000000..4fd956634d --- /dev/null +++ b/packages/flow/tests/test_key_hierarchy.py @@ -0,0 +1,523 @@ +"""Encrypted by default through the key hierarchy (sealed-set v3). + +Every test injects device keys (hardware test doubles or the software key in +an in-memory keychain), and replaces the machine policy sources, so no test +reads the real OS keychain, the Secure Enclave or a TPM, or raises an OS +dialog. +""" + +from __future__ import annotations + +import base64 +import json +import os +import plistlib +from pathlib import Path +from typing import Optional + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec, rsa + +from openadapt_flow import at_rest, crypto, sealed_set +from openadapt_flow import key_hierarchy as kh + +PNG = b"\x89PNG\r\n\x1a\n" + b"synthetic pixels" +TYPED = b"a synthetic typed value" + + +class MemoryKeychain(at_rest.KeyStore): + """A keychain that lives in this test only.""" + + def __init__(self) -> None: + self.values: dict[str, str] = {} + self.broken = False + + def get(self, account: str) -> Optional[str]: + if self.broken: + raise at_rest.KeyStoreUnavailable("no keychain backend (test)") + return self.values.get(account) + + def set(self, account: str, value: str) -> None: + if self.broken: + raise at_rest.KeyStoreUnavailable("no keychain backend (test)") + self.values[account] = value + + +@pytest.fixture +def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + for name in ( + at_rest.OPT_OUT_ENV, + at_rest.MODE_ENV, + at_rest.ENCRYPT_ENV, + at_rest.KEY_STORE_ENV, + crypto.ENV_KEY, + sealed_set.RECORDING_ENV_KEY, + kh.POLICY_ENV, + kh.TRUST_USER_POLICY_ENV, + kh.RECOVERY_CODE_ENV, + kh.ORG_KEY_FILE_ENV, + ): + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(kh, "MACHINE_POLICY_SOURCES", []) + root = tmp_path / "home" + monkeypatch.setenv(at_rest.HOME_ENV, str(root)) + keychain = MemoryKeychain() + at_rest.use_key_store(keychain) + kh.use_device_keys(None) + at_rest._reset_for_tests() + yield root, keychain + at_rest.use_key_store(None) + kh.use_device_keys(None) + at_rest._reset_for_tests() + + +def _seal(root: Path, files: dict[str, bytes], kind: str = "run") -> None: + with sealed_set.writing(root, kind, sealed_set.passphrase_for(kind)) as writer: + for rel, data in files.items(): + writer.write(rel, data) + + +def _header(root: Path) -> dict: + return json.loads((root / sealed_set.HEADER).read_text()) + + +def _assert_ciphertext_only(root: Path) -> None: + for path in root.rglob("*"): + if path.is_file(): + data = path.read_bytes() + assert TYPED not in data and not data.startswith(PNG[:8]), path + + +def _p256_policy( + tmp_path: Path, monkeypatch, **extra +) -> tuple[Path, ec.EllipticCurvePrivateKey]: + org = ec.generate_private_key(ec.SECP256R1()) + spki = org.public_key().public_bytes( + serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo + ) + policy = { + "schema": kh.POLICY_SCHEMA, + "org": "example-health", + "mode": "org", + "recipients": [ + { + "role": "org", + "status": "active", + "type": kh.HPKE_P256, + "public_key": base64.b64encode(spki).decode(), + "fingerprint": kh.fingerprint(org.public_key()), + } + ], + "key_archive": str(tmp_path / "archive"), + **extra, + } + path = tmp_path / "policy.json" + path.write_text(json.dumps(policy)) + monkeypatch.setenv(kh.POLICY_ENV, str(path)) + monkeypatch.setenv(kh.TRUST_USER_POLICY_ENV, "1") + key_file = tmp_path / "org-key.pem" + key_file.write_bytes( + org.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + return key_file, org + + +# -- defaults --------------------------------------------------------------------- + + +def test_a_new_run_is_v3_ciphertext_only_and_reads_back(home) -> None: + root, keychain = home + run = root.parent / "run" + _seal(run, {"report.json": b'{"typed": "%s"}' % TYPED, "steps/a.png": PNG}) + header = _header(run) + assert header["version"] == sealed_set.ENVELOPE_VERSION + assert header["payload"] == "tink-aes256-gcm-hkdf-1mb" + assert header["stanzas"][0]["type"] == kh.STANZA_TYPE + record = header["bucket_record"] # solo mode: inline, travels with backups + assert [s["role"] for s in record["stanzas"]] == [kh.ROLE_DEVICE_SOFTWARE] + assert len(keychain.values) == 1 # the software device key, in the keychain + _assert_ciphertext_only(run) + assert sealed_set.read_bytes(run / "steps" / "a.png") == PNG + + +def test_another_computer_cannot_open_it(home, monkeypatch) -> None: + root, _keychain = home + run = root.parent / "run" + _seal(run, {"report.json": b"{}"}) + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "elsewhere")) + at_rest.use_key_store(MemoryKeychain()) + with pytest.raises(sealed_set.SealedSetKeyError, match="no key on this computer"): + sealed_set.SealedSet.open(run, None) + + +def test_a_header_rewrapped_by_someone_else_is_refused(home) -> None: + """The bucket public key is not secret: a new DEK wrapped to it, with a + DEK MAC, still lacks the bucket-key MAC.""" + root, _keychain = home + run = root.parent / "run" + _seal(run, {"report.json": b"real"}) + header = _header(run) + public = serialization.load_der_public_key( + base64.b64decode(header["bucket_record"]["bucket_pub"]) + ) + dek = os.urandom(32) + header["stanzas"][0]["ct"] = base64.b64encode( + kh.hpke_seal( + public, dek, sealed_set._v3_wrap_info(header, header["stanzas"][0]["fpr"]) + ) + ).decode() + forged = sealed_set.V3Key(dek, header["set_id"]) + forged.stamp(header) + (run / sealed_set.HEADER).write_text(json.dumps(header)) + with pytest.raises(sealed_set.SealedSetError, match="MAC"): + sealed_set.read_bytes(run / "report.json") + + +def test_an_edited_header_is_refused(home) -> None: + root, _keychain = home + run = root.parent / "run" + _seal(run, {"report.json": b"real"}) + header = _header(run) + header["kind"] = "bundle" + (run / sealed_set.HEADER).write_text(json.dumps(header)) + with pytest.raises(sealed_set.SealedSetError): + sealed_set.read_bytes(run / "report.json") + + +def test_a_configured_key_keeps_the_v1_header(home, monkeypatch) -> None: + root, keychain = home + monkeypatch.setenv(crypto.ENV_KEY, "a-deployment-key-for-tests") + run = root.parent / "run" + _seal(run, {"report.json": b"{}"}) + assert _header(run)["version"] == 1 + assert keychain.values == {} + + +def test_a_legacy_plaintext_folder_and_key_file_still_work(home) -> None: + root, _keychain = home + legacy = base64.urlsafe_b64encode(os.urandom(32)).decode() + keys = root / "keys" + keys.mkdir(parents=True, mode=0o700) + (keys / at_rest.KEY_NAME).write_text(legacy + "\n") + os.chmod(keys / at_rest.KEY_NAME, 0o600) + assert crypto.resolve_key(None) == legacy + old = root.parent / "old" + with sealed_set.writing(old, "run", legacy) as writer: # what main wrote + writer.write("report.json", b"old") + assert _header(old)["version"] == 1 + assert sealed_set.read_bytes(old / "report.json") == b"old" + plain = root.parent / "plain" + plain.mkdir() + (plain / "report.json").write_bytes(b"{}") + assert sealed_set.read_bytes(plain / "report.json") == b"{}" + + +# -- hardware providers (test doubles) ------------------------------------------- + + +def test_runtime_stanza_only_while_open_then_the_viewer_prompts(home) -> None: + root, _keychain = home + runtime = kh.HardwareDouble(kh.ROLE_RUNTIME) + viewer = kh.HardwareDouble(kh.ROLE_VIEWER, presence=True) + kh.use_device_keys(runtime, viewer) + run = root.parent / "run" + writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) + roles = [s["role"] for s in writer._header["bucket_record"]["stanzas"]] + assert roles == [kh.ROLE_RUNTIME, kh.ROLE_VIEWER] + writer.write("report.json", TYPED) + writer.finalize() + roles = [s["role"] for s in _header(run)["bucket_record"]["stanzas"]] + assert roles == [kh.ROLE_VIEWER] + assert sealed_set.read_bytes(run / "report.json") == TYPED + assert viewer.prompts == 1 and runtime.unwraps == 0 + viewer.deny = True + with pytest.raises(sealed_set.SealedSetError, match="cancelled"): + sealed_set.read_bytes(run / "report.json") + + +def test_a_bundle_keeps_its_runtime_stanza_for_unattended_replay(home) -> None: + root, _keychain = home + runtime = kh.HardwareDouble(kh.ROLE_RUNTIME) + viewer = kh.HardwareDouble(kh.ROLE_VIEWER, presence=True) + kh.use_device_keys(runtime, viewer) + bundle = root.parent / "bundle" + _seal(bundle, {"workflow.json": b"{}"}, kind="bundle") + assert sealed_set.read_bytes(bundle / "workflow.json") == b"{}" + assert viewer.prompts == 0 and runtime.unwraps == 1 + + +def test_the_hardware_providers_are_not_built_and_fall_back_labelled(home) -> None: + for provider in ( + kh.SecureEnclaveRuntimeKey(), + kh.SecureEnclaveViewerKey(), + kh.TpmRuntimeKey(), + kh.WindowsHelloViewerKey(), + ): + assert provider.available() is False + runtime, viewer = kh.device_keys(create=True) + assert kh.is_software(runtime) and runtime is viewer + assert kh.describe(kh.load_policy())["device_runtime_key"] == "software" + + +def test_require_hardware_refuses_the_software_key(home, tmp_path, monkeypatch) -> None: + path = tmp_path / "solo-policy.json" + path.write_text( + json.dumps({"schema": kh.POLICY_SCHEMA, "require_hardware_device_key": True}) + ) + monkeypatch.setenv(kh.POLICY_ENV, str(path)) + with pytest.raises(sealed_set.SealedSetError, match="hardware device key"): + _seal(home[0].parent / "run", {"report.json": b"{}"}) + + +# -- the software device key in the keychain ------------------------------------------ + + +def test_a_missing_keychain_entry_fails_closed_and_mints_nothing(home) -> None: + root, keychain = home + _seal(root.parent / "run", {"report.json": b"{}"}) + keychain.values.clear() + with pytest.raises(sealed_set.SealedSetError, match="missing"): + sealed_set.read_bytes(root.parent / "run" / "report.json") + assert keychain.values == {} + + +def test_a_locked_keychain_fails_closed(home) -> None: + root, keychain = home + _seal(root.parent / "run", {"report.json": b"{}"}) + keychain.broken = True + with pytest.raises(at_rest.LocalKeyError, match="Unlock the keychain"): + at_rest.device_secret(create=False) + + +def test_no_keychain_falls_back_to_a_private_file_with_a_warning(home, capsys) -> None: + root, keychain = home + keychain.broken = True + secret = at_rest.device_secret(create=True) + path = root / "keys" / at_rest.DEVICE_KEY_NAME + assert path.read_text().strip() == secret + if os.name == "posix": + assert path.stat().st_mode & 0o777 == 0o600 + assert "WARNING: no OS keychain is available" in capsys.readouterr().err + + +def test_tests_never_reach_the_real_keychain(monkeypatch) -> None: + at_rest.use_key_store(None) + monkeypatch.delenv(at_rest.KEY_STORE_ENV, raising=False) + assert "PYTEST_CURRENT_TEST" in os.environ + assert at_rest._store_choice() == "file" + + +# -- organization mode -------------------------------------------------------------- + + +def test_org_mode_archives_and_the_org_opens_it_elsewhere( + home, tmp_path, monkeypatch +) -> None: + root, _keychain = home + key_file, org = _p256_policy(tmp_path, monkeypatch) + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + header = _header(run) + assert "bucket_record" not in header # never travels with the evidence + archived = json.loads( + (tmp_path / "archive" / f"{header['key_ref']['bucket_id']}.json").read_text() + ) + assert kh.ROLE_RUNTIME not in [s["role"] for s in archived["stanzas"]] + assert kh.fingerprint(org.public_key()) in [s["fpr"] for s in archived["stanzas"]] + _assert_ciphertext_only(run) + # A reviewer on another computer: the archive copy and the org key. + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "reviewer")) + at_rest.use_key_store(MemoryKeychain()) + buckets = root.parent / "reviewer" / "keys" / "buckets" + buckets.mkdir(parents=True) + (buckets / f"{header['key_ref']['bucket_id']}.json").write_text( + json.dumps(archived) + ) + monkeypatch.setenv(kh.ORG_KEY_FILE_ENV, str(key_file)) + assert sealed_set.read_bytes(run / "report.json") == TYPED + + +def test_org_mode_with_an_rsa_oaep_recipient(home, tmp_path, monkeypatch) -> None: + root, _keychain = home + org = rsa.generate_private_key(public_exponent=65537, key_size=3072) + spki = org.public_key().public_bytes( + serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo + ) + policy = tmp_path / "policy.json" + policy.write_text( + json.dumps( + { + "schema": kh.POLICY_SCHEMA, + "mode": "org", + "records": "inline", + "recipients": [ + { + "role": "org", + "type": kh.RSA_OAEP_3072, + "public_key": base64.b64encode(spki).decode(), + } + ], + } + ) + ) + monkeypatch.setenv(kh.POLICY_ENV, str(policy)) + monkeypatch.setenv(kh.TRUST_USER_POLICY_ENV, "1") + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + key_file = tmp_path / "rsa.pem" + key_file.write_bytes( + org.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "auditor")) + at_rest.use_key_store(MemoryKeychain()) + monkeypatch.setenv(kh.ORG_KEY_FILE_ENV, str(key_file)) + assert sealed_set.read_bytes(run / "report.json") == TYPED + + +def test_org_mode_fails_closed_without_its_recipient_or_archive( + home, tmp_path, monkeypatch +) -> None: + path = tmp_path / "policy.json" + monkeypatch.setenv(kh.POLICY_ENV, str(path)) + monkeypatch.setenv(kh.TRUST_USER_POLICY_ENV, "1") + path.write_text( + json.dumps({"schema": kh.POLICY_SCHEMA, "mode": "org", "key_archive": "x"}) + ) + with pytest.raises(sealed_set.SealedSetError, match="no active organization"): + _seal(home[0].parent / "a", {"report.json": b"{}"}) + _p256_policy(tmp_path, monkeypatch, key_archive=None) + with pytest.raises(sealed_set.SealedSetError, match="no key_archive"): + _seal(home[0].parent / "b", {"report.json": b"{}"}) + + +def test_a_user_owned_org_policy_is_not_trusted(home, tmp_path, monkeypatch) -> None: + if os.getuid() == 0: + pytest.skip("running as root") + _p256_policy(tmp_path, monkeypatch) + monkeypatch.delenv(kh.TRUST_USER_POLICY_ENV) + with pytest.raises(kh.KeyHierarchyError, match="not owned by root"): + kh.load_policy() + + +def test_a_machine_policy_wins_over_the_user_one(home, tmp_path, monkeypatch) -> None: + _p256_policy(tmp_path, monkeypatch) + machine = tmp_path / "ai.openadapt.policy.plist" + machine.write_bytes( + plistlib.dumps( + {"Policy": json.dumps({"schema": kh.POLICY_SCHEMA, "mode": "solo"})} + ) + ) + monkeypatch.setattr(kh, "MACHINE_POLICY_SOURCES", [str(machine)]) + policy = kh.load_policy() + assert policy.mode == "solo" and policy.source.startswith("machine:") + + +def test_an_unreachable_archive_counts_and_then_stops_recording( + home, tmp_path, monkeypatch +) -> None: + blocker = tmp_path / "not-a-dir" + blocker.write_text("") + _p256_policy(tmp_path, monkeypatch, key_archive=str(blocker), max_unarchived=1) + _seal(home[0].parent / "a", {"report.json": b"{}"}) + assert kh.unarchived_count() == 1 + with pytest.raises(sealed_set.SealedSetError, match="not reached the organization"): + _seal(home[0].parent / "b", {"report.json": b"{}"}) + + +def test_shred_in_org_mode_destroys_every_tracked_copy( + home, tmp_path, monkeypatch +) -> None: + root, _keychain = home + key_file, _org = _p256_policy(tmp_path, monkeypatch) + run = root.parent / "run" + run.mkdir() + (run / "checkpoints").mkdir() + (run / "checkpoints" / "s1.enc").write_bytes( + crypto.encrypt_bytes(b"{}", "k" * 20, aad=crypto.CHECKPOINT_AAD) + ) + writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) + writer.write("report.json", TYPED) + writer.finalize(adopt_external=True) + backup = root.parent / "backup" + import shutil + + shutil.copytree(run, backup) + record = sealed_set.shred(run) + assert sorted(record["copies_destroyed"]) == ["archive", "local"] + assert record["store_files_deleted"] == ["checkpoints/s1.enc"] + monkeypatch.setenv(kh.ORG_KEY_FILE_ENV, str(key_file)) + with pytest.raises(sealed_set.SealedSetError, match="shredded"): + sealed_set.read_bytes(run / "report.json") + # The backup copy holds only ciphertext and a header no record opens. + with pytest.raises(sealed_set.SealedSetError): + sealed_set.read_bytes(backup / "report.json") + + +# -- solo recovery -------------------------------------------------------------------- + + +def test_a_recovery_code_opens_a_backup_on_a_new_computer(home, monkeypatch) -> None: + root, _keychain = home + code, recipient = kh.new_recovery_code() + assert len(code.replace("-", "")) == 52 + kh.save_recovery_recipient(recipient) + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "new-laptop")) + at_rest.use_key_store(MemoryKeychain()) + with pytest.raises(sealed_set.SealedSetKeyError): + sealed_set.read_bytes(run / "report.json") + monkeypatch.setenv(kh.RECOVERY_CODE_ENV, code) + assert sealed_set.read_bytes(run / "report.json") == TYPED + + +def test_solo_shred_reaches_only_this_copy(home) -> None: + root, _keychain = home + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + record = sealed_set.shred(run) + assert record["records"] == "inline" + with pytest.raises(sealed_set.SealedSetError, match="shredded"): + sealed_set.read_bytes(run / "report.json") + + +# -- the opt-out ------------------------------------------------------------------------ + + +def test_encrypt_zero_turns_it_off_with_one_warning_line( + home, capsys, monkeypatch +) -> None: + root, _keychain = home + monkeypatch.setenv(at_rest.ENCRYPT_ENV, "0") + assert at_rest.seal_new("a recording", root / "rec") is False + assert at_rest.seal_new("a recording", root / "rec") is False + err = [line for line in capsys.readouterr().err.splitlines() if line] + assert len(err) == 1 and err[0].startswith("WARNING:") + ledger = (root / at_rest.LEDGER_NAME).read_text().splitlines() + assert json.loads(ledger[0])["reason"] == "OPENADAPT_ENCRYPT_AT_REST=0" + + +def test_a_mistyped_encrypt_setting_is_refused(monkeypatch) -> None: + monkeypatch.setenv(at_rest.ENCRYPT_ENV, "nope") + with pytest.raises(ValueError): + at_rest.opt_out_reason() + + +def test_strict_mode_ignores_the_opt_out(home, monkeypatch) -> None: + monkeypatch.setenv(at_rest.ENCRYPT_ENV, "0") + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + assert at_rest.seal_new("a recording", "x") is True + + +def test_new_artifacts_are_sealed_by_default(home) -> None: + assert at_rest.DEFAULT_SEALS_ARTIFACTS is True + assert at_rest.seals_by_default() is True diff --git a/packages/flow/tests/test_stream_aead.py b/packages/flow/tests/test_stream_aead.py new file mode 100644 index 0000000000..b0cd44cff3 --- /dev/null +++ b/packages/flow/tests/test_stream_aead.py @@ -0,0 +1,90 @@ +"""The sealed-set v3 payload is Tink's AES256_GCM_HKDF_1MB wire format. + +Checked both ways against Tink itself (a dev dependency) at the segment +boundaries, and for truncation and tampering. +""" + +from __future__ import annotations + +import io +import os + +import pytest + +from openadapt_flow import stream_aead + +SIZES = (0, 1, 1048535, 1048536, 1048537, 2 * 1048576 + 5) +AAD = b"openadapt-flow/sealed-set/file/run/steps/step_1_after.png" + + +def _tink(ikm: bytes): + tink = pytest.importorskip("tink") + from tink import cleartext_keyset_handle, streaming_aead + from tink.proto import aes_gcm_hkdf_streaming_pb2 as pb + from tink.proto import common_pb2, tink_pb2 + + streaming_aead.register() + key = pb.AesGcmHkdfStreamingKey( + version=0, + key_value=ikm, + params=pb.AesGcmHkdfStreamingParams( + ciphertext_segment_size=1 << 20, + derived_key_size=32, + hkdf_hash_type=common_pb2.SHA256, + ), + ) + keyset = tink_pb2.Keyset( + primary_key_id=1, + key=[ + tink_pb2.Keyset.Key( + key_data=tink_pb2.KeyData( + type_url="type.googleapis.com/google.crypto.tink.AesGcmHkdfStreamingKey", + value=key.SerializeToString(), + key_material_type=tink_pb2.KeyData.SYMMETRIC, + ), + status=tink_pb2.ENABLED, + key_id=1, + output_prefix_type=tink_pb2.RAW, + ) + ], + ) + assert tink + return cleartext_keyset_handle.from_keyset(keyset).primitive( + streaming_aead.StreamingAead + ) + + +@pytest.mark.parametrize("size", SIZES) +def test_tink_reads_ours_and_we_read_tinks(size: int) -> None: + ikm = os.urandom(32) + primitive = _tink(ikm) + plaintext = os.urandom(size) + ours = stream_aead.encrypt(ikm, plaintext, AAD) + with primitive.new_decrypting_stream(io.BytesIO(ours), AAD) as stream: + assert stream.read() == plaintext + + class Keep(io.BytesIO): + def close(self) -> None: + self.kept = self.getvalue() + super().close() + + sink = Keep() + with primitive.new_encrypting_stream(sink, AAD) as stream: + stream.write(plaintext) + assert stream_aead.decrypt(ikm, sink.kept, AAD) == plaintext + assert len(sink.kept) == len(ours) + + +def test_truncation_tampering_and_another_path_fail() -> None: + ikm = os.urandom(32) + data = stream_aead.encrypt(ikm, os.urandom(2 * 1048576), AAD) + with pytest.raises(stream_aead.StreamError): + stream_aead.decrypt(ikm, data[:1048576], AAD) # a crash mid-stream + flipped = bytearray(data) + flipped[100] ^= 1 + with pytest.raises(stream_aead.StreamError): + stream_aead.decrypt(ikm, bytes(flipped), AAD) + with pytest.raises(stream_aead.StreamError): + stream_aead.decrypt(ikm, data, b"another/path") + with pytest.raises(stream_aead.StreamError): + stream_aead.decrypt(os.urandom(32), data, AAD) diff --git a/packages/flow/uv.lock b/packages/flow/uv.lock index ea6c77f9fd..0ef3151735 100644 --- a/packages/flow/uv.lock +++ b/packages/flow/uv.lock @@ -35,6 +35,15 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/92/88/b1a7e3dd1e727245fe893bb707520ba91cc980443c0c261f730b35244b62/aardwolf-0.2.14.tar.gz", hash = "sha256:360a1a3d046dc2814c2e58339939a8f311ae330c0d1d962790edf45d726af4a6", size = 973985, upload-time = "2026-06-20T21:07:04.498Z" } +[[package]] +name = "absl-py" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/1d/58e2b5a6e4d703ccb2a029943d665974cb3d5a4fb2b3e3675dd03a9df10e/absl_py-2.5.1.tar.gz", hash = "sha256:286e71c82c1a38e75bbcf185f9b37d0305ad7786535107cb49bf4df9ff2e1f95", size = 118387, upload-time = "2026-10-09T08:38:58.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/7d/01e62f59e4166af1be6238d9f2b7f3453630c51b8044b412d05b5606532a/absl_py-2.5.1-py3-none-any.whl", hash = "sha256:721200f2f0e9960f2ca9dc3a2a706b201f5f75d812c158f059cbbe29eeafbdb8", size = 137673, upload-time = "2026-10-09T08:38:56.629Z" }, +] + [[package]] name = "aiofile" version = "3.12.3" @@ -276,6 +285,14 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b9/fa/123043af240e49752f1c4bd24da5053b6bd00cad78c2be53c0d1e8b975bc/backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34", size = 30181, upload-time = "2024-05-28T17:01:53.112Z" }, ] +[[package]] +name = "bazel-runfiles" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/c0/4fad14d8394f43b346a4a2368864fee31da0db895f0b672b6357a4c6da71/bazel_runfiles-2.5.1-py3-none-any.whl", hash = "sha256:33a31ef9912c57ef5df98db6797a7d4b6c700fd8912ccbbc23c92572c344f1e4", size = 11061, upload-time = "2026-11-13T19:20:52.457Z" }, +] + [[package]] name = "beartype" version = "0.23.1" @@ -2631,7 +2648,6 @@ dependencies = [ { name = "keyring" }, { name = "openadapt-types" }, { name = "pydantic" }, - { name = "pyrage" }, { name = "pyyaml" }, { name = "tomli", marker = "python_full_version < '3.11'" }, ] @@ -2693,6 +2709,7 @@ dev = [ { name = "ruff" }, { name = "scikit-image" }, { name = "sigstore", marker = "python_full_version >= '3.11'" }, + { name = "tink" }, { name = "uiautomation", marker = "sys_platform == 'win32'" }, { name = "uvicorn" }, ] @@ -2831,7 +2848,7 @@ requires-dist = [ { name = "cbor2", marker = "extra == 'receipts'", specifier = ">=5.6,<6" }, { name = "claude-agent-sdk", marker = "extra == 'claude-agent-sdk'", specifier = ">=0.2.174,<0.3" }, { name = "click", marker = "extra == 'privacy'", specifier = ">=8.0,<9" }, - { name = "cryptography", specifier = ">=42.0" }, + { name = "cryptography", specifier = ">=50.0" }, { name = "cryptography", marker = "extra == 'agent'", specifier = ">=50.0.0" }, { name = "cwt", marker = "extra == 'dev'", specifier = ">=3.3,<4" }, { name = "cwt", marker = "extra == 'receipts'", specifier = ">=3.3,<4" }, @@ -2889,7 +2906,6 @@ requires-dist = [ { name = "pyobjc-framework-cocoa", marker = "sys_platform == 'darwin' and extra == 'macos'", specifier = ">=10.3" }, { name = "pyobjc-framework-cocoa", marker = "sys_platform == 'darwin' and extra == 'native-ocr'", specifier = ">=10.0" }, { name = "pyobjc-framework-quartz", marker = "sys_platform == 'darwin' and extra == 'macos'", specifier = ">=10.3" }, - { name = "pyrage", specifier = ">=1.2,<2" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=5.0" }, { name = "pytest-timeout", marker = "extra == 'dev'", specifier = ">=2.2" }, @@ -2906,6 +2922,7 @@ requires-dist = [ { name = "scikit-image", marker = "extra == 'dev'", specifier = ">=0.22" }, { name = "sigstore", marker = "python_full_version >= '3.11' and extra == 'dev'", specifier = ">=4.5,<5" }, { name = "sigstore", marker = "python_full_version >= '3.11' and extra == 'registry'", specifier = ">=4.5,<5" }, + { name = "tink", marker = "extra == 'dev'", specifier = ">=1.16,<2" }, { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0" }, { name = "transformers", marker = "extra == 'service-mlx'", specifier = ">=5.14,<5.18" }, { name = "uiautomation", marker = "sys_platform == 'win32' and extra == 'dev'", specifier = ">=2.0.20" }, @@ -3860,18 +3877,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3e/b9/3766cc361d93edb2ce81e2e1f87dd98f314d7d513877a342d31b30741680/pypng-0.20220715.0-py3-none-any.whl", hash = "sha256:4a43e969b8f5aaafb2a415536c1a8ec7e341cd6a3f957fd5b5f32a4cfeed902c", size = 58057, upload-time = "2022-07-15T14:11:03.713Z" }, ] -[[package]] -name = "pyrage" -version = "1.4.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/15/a4/612910dbedf7d9fb24ec58474849438b6f88e078e1a100f73a54a605d228/pyrage-1.4.0.tar.gz", hash = "sha256:545bf188e8d217ec88c32bc8e8bf56026c8c0b1b1f96d2688cedf1427ab0e827", size = 32198, upload-time = "2026-08-23T22:48:59.906Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/13/bb/6b167a449e95ecf0eaf4277c949a89a29dfc08cc533f710a9e6f12bef513/pyrage-1.4.0-cp310-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:bcf4177aea91a9f48951db8001c1385baafbae62cc15d691ef43efebaab6b8db", size = 1701313, upload-time = "2026-08-23T22:48:53.835Z" }, - { url = "https://files.pythonhosted.org/packages/5a/cb/d88aaab0b89141802473f6139fe8e05519d1b6ac06bff8231a1378a5674f/pyrage-1.4.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f868b360ccd3f836326d42b532fae3e8eb8340a88cca0a39c0ae10fce68f6cc5", size = 882978, upload-time = "2026-08-23T22:48:55.525Z" }, - { url = "https://files.pythonhosted.org/packages/d9/f0/41da7d88cfdad2eba492f3275ec50a65916ccd3a78140fb15875569ad1ff/pyrage-1.4.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7f4eb0cbc2b4aee5deac9862c47b3895866df5554153951af822e9c581e68558", size = 924673, upload-time = "2026-08-23T22:48:57.1Z" }, - { url = "https://files.pythonhosted.org/packages/d3/8c/354fdb9ee7b45a2060272c623536b2cf9f0996de2242eaac177cff3f8003/pyrage-1.4.0-cp310-abi3-win_amd64.whl", hash = "sha256:c4a5dcd24a14b5e0d4cccff13649a2b8f1609ad45d6438bb85f35d84b0c8155e", size = 848219, upload-time = "2026-08-23T22:48:58.702Z" }, -] - [[package]] name = "pyreadline3" version = "3.5.6" @@ -5003,6 +5008,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5d/06/bd0a6097da704a7a7c34a94cfd771c3ea3c2f405dd214e790d22c93f6be1/tifffile-2025.5.10-py3-none-any.whl", hash = "sha256:e37147123c0542d67bc37ba5cdd67e12ea6fbe6e86c52bee037a9eb6a064e5ad", size = 226533, upload-time = "2025-05-10T19:22:27.279Z" }, ] +[[package]] +name = "tink" +version = "1.16.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "absl-py" }, + { name = "bazel-runfiles" }, + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d3/e2/06a2836b499abddff5127ac4a849667b721f1e1b38742572e0cf9a53f327/tink-1.16.1.tar.gz", hash = "sha256:8d82f934f31d1ba8fa6014c37edddc0b3f61cfdbbd9317eb6269cfe7eeb1fa86", size = 280107, upload-time = "2026-08-13T02:13:07.172Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ed/e8/1d47b2b70aac127fa5effbc34d255ec36d069f065c3481d169f03a84b7f8/tink-1.16.1-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:efc4dfffcd2726d7e8d581a1d5af8f5483771a14d4379abff1f7111f46c14bc7", size = 5154056, upload-time = "2026-08-13T02:12:35.551Z" }, + { url = "https://files.pythonhosted.org/packages/e8/a6/416fd989d26328c174d26108c491576d72c3a8508c1fee229067441a3319/tink-1.16.1-cp310-cp310-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:44a750cbd0a7e2e8ea9ac91e654f643f5560d829ccf6842403f16eb9ed3490cd", size = 4086382, upload-time = "2026-08-13T02:12:37.201Z" }, + { url = "https://files.pythonhosted.org/packages/06/a5/2a715de0320332d17b1774955cacdf0be18c938a6f2bdabfe714bfdf5c10/tink-1.16.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34be79d32b18f534e8979b5bfb66e8894c7d461143392f36d2647ca92d2c4143", size = 4278217, upload-time = "2026-08-13T02:12:38.672Z" }, + { url = "https://files.pythonhosted.org/packages/88/56/1b82eabcd3b39ad01d932cc10dc0243420700f5cb0fe765e1dbca3a3ce31/tink-1.16.1-cp310-cp310-win_amd64.whl", hash = "sha256:9b3e9a6755c4e208285b972a4e59beccbe7f5f033179d7028acaf201b0e62cbb", size = 2291436, upload-time = "2026-08-13T02:12:40.001Z" }, + { url = "https://files.pythonhosted.org/packages/27/15/6f154884fac4a5131d86148bd3d1fbb70671c25cb72a4d3cc696cf72a7e3/tink-1.16.1-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:d74cacf35983b214c6fee38a0b6a3ebe1a004c823ae2a1682e7e82d688f6aaa6", size = 5156354, upload-time = "2026-08-13T02:12:41.549Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2c/54642f8cf8ef98d51050ec0127c333aa5a82f55010a07cf8b2e1cfb03816/tink-1.16.1-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dc0a249f80cc677db94e54a4cbd4adfbc39be72dbcd696bf1154f5003491d4bd", size = 4087963, upload-time = "2026-08-13T02:12:42.913Z" }, + { url = "https://files.pythonhosted.org/packages/3a/98/5d89af949d5b25e5c223af6c436c53d43a824359f41f3bec3b94c48f6475/tink-1.16.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:df720eec696f57af0cb9d5649350b8a7477d2d533465a0023b111133b9438245", size = 4280245, upload-time = "2026-08-13T02:12:44.334Z" }, + { url = "https://files.pythonhosted.org/packages/fd/c0/0e1fa4c78c4dfd5e6274aaf733c22ac1b3bc9b9fb3ae79d8efc706eaf25d/tink-1.16.1-cp311-cp311-win_amd64.whl", hash = "sha256:8705e33b327237f6237fbb99690221013b44bb254fc3c886cbfac6dce435852c", size = 2292643, upload-time = "2026-08-13T02:12:45.775Z" }, + { url = "https://files.pythonhosted.org/packages/00/2b/af400c2f829ca70a691f957963dd14eb2dbc88d59bf9bc278ff2990194cc/tink-1.16.1-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:9305eaf686fc67552925ef4d1e1f5dc2254fd8d24d55f3090987d0d6803d2636", size = 5158162, upload-time = "2026-08-13T02:12:47.27Z" }, + { url = "https://files.pythonhosted.org/packages/fa/19/ad7313e5fc3750104dd1a4fd7c72314b6c1c0e466ef71861867a9c629cd8/tink-1.16.1-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e453324348208e5cb81e35d506717ed83c8c4cf2473f4b31f6269fd8bca81fb2", size = 4088392, upload-time = "2026-08-13T02:12:48.86Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ac/411c91392a2a86edb7db2637a7290ac708eec94a782b301e9806452f6373/tink-1.16.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:af3519dfa01704e9f1ae1020db6076dcff89b5f799deba08a1adf901d977fc4e", size = 4280151, upload-time = "2026-08-13T02:12:50.515Z" }, + { url = "https://files.pythonhosted.org/packages/51/f7/20136d551645883b4ac46a3ffbbaf19e27953f38742dc9a4265596daaaf0/tink-1.16.1-cp312-cp312-win_amd64.whl", hash = "sha256:99766688b84b362516488fbf371b4f801c5b2833a86cc8b70f58d607a636d951", size = 2293549, upload-time = "2026-08-13T02:12:51.941Z" }, +] + [[package]] name = "tldextract" version = "5.3.1" diff --git a/tests/conftest.py b/tests/conftest.py index 08a8e7beab..c238266d02 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -77,7 +77,5 @@ def _isolated_flow_at_rest(tmp_path_factory, monkeypatch): # Never the OS keychain from tests: no dialog, no login-keychain write. monkeypatch.setenv("OPENADAPT_FLOW_KEY_STORE", "file") monkeypatch.delenv("OPENADAPT_ENCRYPT_AT_REST", raising=False) - monkeypatch.delenv("OPENADAPT_ORG_RECIPIENTS", raising=False) - monkeypatch.setenv( - "OPENADAPT_POLICY_FILE", str(tmp_path_factory.mktemp("policy") / "none.json") - ) + monkeypatch.delenv("OPENADAPT_POLICY", raising=False) + monkeypatch.delenv("OPENADAPT_RECOVERY_CODE", raising=False) From f1b4a29b1239bb3f7a39f5fe46c3913e84c05c6c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:04:51 -0500 Subject: [PATCH 03/37] flow: report a locked encrypted run clearly; tests for the key hierarchy seal verify says report_locked, not subject_mismatch, when no key here opens an encrypted run. The quickstart makes the device key before its workers start. Tink interop and hierarchy tests; default-mode tests now expect sealed output. --- openadapt/quickstart/notices.py | 9 +++- packages/flow/openadapt_flow/__main__.py | 7 ++- packages/flow/openadapt_flow/at_rest.py | 39 ++++++++------- packages/flow/openadapt_flow/offline_seal.py | 20 +++++++- packages/flow/openadapt_flow/sealed_set.py | 2 +- packages/flow/tests/test_at_rest_default.py | 50 ++++++++++++-------- packages/flow/tests/test_key_hierarchy.py | 6 ++- tests/test_quickstart.py | 9 ++-- 8 files changed, 90 insertions(+), 52 deletions(-) diff --git a/openadapt/quickstart/notices.py b/openadapt/quickstart/notices.py index a2c7f6dc33..2670fbb1a7 100644 --- a/openadapt/quickstart/notices.py +++ b/openadapt/quickstart/notices.py @@ -42,6 +42,7 @@ def __init__(self, target: IO[str]) -> None: self.target = target self.paths: list[str] = [] self.key_created: Optional[str] = None + self.keys_created: list[str] = [] self._partial = "" self._lock = threading.Lock() @@ -58,7 +59,9 @@ def write(self, text: str) -> int: if match: self.paths.append(match.group(1) + "\0" + match.group(2)) elif created: - self.key_created = created.group(1) or created.group(2) + where = created.group(1) or created.group(2) + self.keys_created.append(where) + self.key_created = ", ".join(self.keys_created) else: self.target.write(line + "\n") return len(text) @@ -106,6 +109,10 @@ def _ensure_local_key() -> None: if at_rest.explicit_key() or at_rest.opt_out_reason() is not None: return at_rest.local_key() + from openadapt_flow import key_hierarchy + + # The device key that new runs are wrapped to, made once here. + key_hierarchy.device_keys(create=True) except Exception: # noqa: BLE001 - Flow reports it where the key is used return diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index dff13c79c8..687ae194d4 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -14229,7 +14229,7 @@ def _private_input(args: argparse.Namespace) -> bool: def _sealed_input_refusal(args: argparse.Namespace) -> Optional[str]: """Refuse a sealed path in a command that cannot keep it sealed, and a sealed path whose key is not configured, before the command runs.""" - from openadapt_flow import sealed_set + from openadapt_flow import crypto, sealed_set sealed = _sealed_paths_in(args) if not sealed: @@ -14251,7 +14251,10 @@ def _sealed_input_refusal(args: argparse.Namespace) -> Optional[str]: ) for root in sealed: kind = sealed_set.header_kind(root) - if not sealed_set.passphrase_for(kind): + version = sealed_set.read_header(root).get("version") + if version != sealed_set.ENVELOPE_VERSION and not ( + sealed_set.passphrase_for(kind) or crypto.resolve_read_key(None) + ): return sealed_set.missing_key_message(root, kind) try: # With no key configured the local key resolves; opening the set diff --git a/packages/flow/openadapt_flow/at_rest.py b/packages/flow/openadapt_flow/at_rest.py index 65684ef078..06e14505c0 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -5,22 +5,24 @@ :mod:`openadapt_flow.sealed_set` and :mod:`openadapt_flow.crypto`, by default and with no setup. -* The key is ``OPENADAPT_BUNDLE_KEY`` (or ``OPENADAPT_RECORDING_KEY``) when - set. Otherwise it is a per-user key Flow generates on first use and keeps in - the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret - Service, through ``keyring``). A small marker, - ``$OPENADAPT_HOME/keys/at-rest.key.store.json``, records which keychain - entry holds it and a check value; it holds no key material. Where no - keychain works (a headless Linux box without Secret Service, say), the key - goes to ``$OPENADAPT_HOME/keys/at-rest.key`` with mode 0600 in a 0700 - directory, with a warning. ``OPENADAPT_FLOW_KEY_STORE`` picks the store - (``auto``, the default; ``keychain``; ``file``). A key file made by an - earlier version keeps being used, so nothing it encrypted is orphaned. - ``OPENADAPT_FLOW_AT_REST_HOME`` moves the marker, the file and the ledger - (default ``$OPENADAPT_HOME``, else ``~/.openadapt``). Back the key up: what - it encrypts can't be read without it. +* New recordings, bundles and run directories are sealed-set version 3: + each has its own data key, wrapped through a per-set bucket key to the + device keys, the organization's keys and a recovery key + (:mod:`openadapt_flow.key_hierarchy`). Where this computer has no secure + hardware key, the device key is a *software* P-256 key that this module + keeps in the OS keychain through ``keyring`` (macOS Keychain, Windows + Credential Manager, Linux Secret Service), with a non-secret marker + (``keys/device-key.store.json``) naming the entry and a check value; or, + where no keychain works, in ``keys/device-software.key`` (0600) with a + warning. ``OPENADAPT_FLOW_KEY_STORE`` picks ``auto``, ``keychain`` or + ``file``. A marker whose entry is gone, locked or different fails closed. +* ``OPENADAPT_BUNDLE_KEY`` (or ``OPENADAPT_RECORDING_KEY``), when set, still + wins outside organization mode (deprecated). The local passphrase + ``keys/at-rest.key`` (0600), made by earlier versions and still used for + durable checkpoints and attended state, keeps working. + ``OPENADAPT_FLOW_AT_REST_HOME`` moves these files and the ledger. * Recordings, bundles, run directories and durable checkpoints are encrypted - under that key by default (:data:`DEFAULT_SEALS_ARTIFACTS`). + by default (:data:`DEFAULT_SEALS_ARTIFACTS`). * ``OPENADAPT_FLOW_AT_REST=strict``, the setting for healthcare and regulated deployments, also refuses the outputs that aren't encrypted yet (:func:`unsealed_write`). @@ -34,11 +36,8 @@ Each prints a one-line warning and adds a ledger line. Strict mode ignores both. Files encrypted earlier still read. -A keychain marker whose entry is gone, locked or different fails closed with -:class:`LocalKeyError`; Flow never mints a second key over it. - -Stdlib only (``keyring`` is imported lazily), so :mod:`openadapt_flow.crypto` -can import it on every load. +Stdlib only (``keyring`` and ``cryptography`` are imported lazily), so +:mod:`openadapt_flow.crypto` can import it on every load. """ from __future__ import annotations diff --git a/packages/flow/openadapt_flow/offline_seal.py b/packages/flow/openadapt_flow/offline_seal.py index 0210f90713..fe997d3958 100644 --- a/packages/flow/openadapt_flow/offline_seal.py +++ b/packages/flow/openadapt_flow/offline_seal.py @@ -91,6 +91,8 @@ "unsigned", "malformed", "subject_mismatch", + # The run directory is encrypted and no key on this computer opens it. + "report_locked", "unknown_key", "revoked_key", "key_mismatch", @@ -654,6 +656,14 @@ def _report_bytes(path: Path) -> bytes: raise OSError(str(exc)) from exc +def sealed_set_is_file(path: Path) -> bool: + """Whether ``path`` exists, opening an encrypted run directory to tell + (raises when no key here opens it).""" + from openadapt_flow import sealed_set + + return sealed_set.is_file(path) + + def _report_is_file(path: Path) -> bool: from openadapt_flow import sealed_set @@ -699,9 +709,15 @@ def verify_run( strict = strict or require_anchor for name in ("report.json",) if strict else ("report.json", "report.pre-seal.json"): path = run_dir / name - if not _report_is_file(path): + try: + present = sealed_set_is_file(path) + raw = _report_bytes(path) if present else None + except (OSError, ValueError): + # Encrypted, and no key here opens it: say so, never "mismatch". + return LocalSealVerification(False, reason="report_locked") + if raw is None: continue - digest = hashlib.sha256(_report_bytes(path)).hexdigest() + digest = hashlib.sha256(raw).hexdigest() result = verify_local_seal(seal, digest, registry) if result.reason == "subject_mismatch": continue diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index 3751d9ea58..e8fdf8e11b 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -908,7 +908,7 @@ def _explicit_passphrase(passphrase: Optional[str]) -> bool: return False from openadapt_flow import at_rest - return passphrase != at_rest.existing_key() + return at_rest.explicit_key() or passphrase != at_rest.existing_key() def _new_v3( diff --git a/packages/flow/tests/test_at_rest_default.py b/packages/flow/tests/test_at_rest_default.py index 2f30410473..16bdb34b60 100644 --- a/packages/flow/tests/test_at_rest_default.py +++ b/packages/flow/tests/test_at_rest_default.py @@ -32,8 +32,10 @@ def default_mode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: 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) home = tmp_path / "at-rest-home" @@ -138,14 +140,15 @@ def test_unsealed_write_names_the_path_or_refuses( # -- recordings and bundles ------------------------------------------------------- -def test_a_plaintext_bundle_is_named_by_default( - default_mode: Path, tmp_path: Path, capsys +def test_a_plaintext_recording_compiles_to_a_sealed_bundle_by_default( + default_mode: Path, tmp_path: Path ) -> None: - rec = _recording(tmp_path / "rec", key=None) + rec = _recording(tmp_path / "rec", key=None) # made before the default assert main(["compile", str(rec), "--out", str(tmp_path / "b"), "--name", "x"]) == 0 - assert (tmp_path / "b" / "workflow.json").is_file() - assert str(tmp_path / "b") in capsys.readouterr().err - assert _ledger(default_mode)[0]["path"] == str(tmp_path / "b") + _assert_ciphertext_only(tmp_path / "b") + assert sealed_set.read_header(tmp_path / "b")["version"] == 3 + assert Workflow.load(tmp_path / "b").name == "x" + assert _ledger(default_mode) == [] def test_strict_mode_compiles_a_plaintext_recording_to_a_sealed_bundle( @@ -214,11 +217,13 @@ def _record_args(out: Path, *, no_encrypt: bool = False) -> argparse.Namespace: return argparse.Namespace(out=str(out), no_encrypt=no_encrypt) -def test_web_recordings_are_named_by_default_and_sealed_in_strict_mode( +def test_web_recordings_are_sealed_by_default_and_in_strict_mode( default_mode: Path, tmp_path: Path, monkeypatch ) -> None: - assert _recording_encryption_key(_record_args(tmp_path / "r"), "web") is None - assert _ledger(default_mode)[0]["path"] == str(tmp_path / "r") + assert _recording_encryption_key(_record_args(tmp_path / "r"), "web") == ( + crypto.resolve_key(None) + ) + assert _ledger(default_mode) == [] monkeypatch.setenv(at_rest.MODE_ENV, "strict") assert _recording_encryption_key(_record_args(tmp_path / "r2"), "web") == ( crypto.resolve_key(None) @@ -243,13 +248,16 @@ def test_no_encrypt_is_recorded_and_strict_refuses_it( _recording_encryption_key(_record_args(tmp_path / "r2", no_encrypt=True), "web") -def test_desktop_recorders_work_by_default_and_refuse_in_strict_mode( - default_mode: Path, tmp_path: Path, monkeypatch, capsys +def test_desktop_recordings_are_sealed_by_default_and_refused_in_strict_mode( + default_mode: Path, tmp_path: Path, monkeypatch ) -> None: out = tmp_path / "desk" - assert _recording_encryption_key(_record_args(out), "windows") is None - assert str(out) in capsys.readouterr().err - assert _ledger(default_mode)[0]["path"] == str(out) + # The converted recording is sealed; the raw capture is held back in + # strict mode, which can't encrypt it while it records. + assert _recording_encryption_key(_record_args(out), "windows") == ( + crypto.resolve_key(None) + ) + assert _ledger(default_mode) == [] monkeypatch.setenv(at_rest.MODE_ENV, "strict") with pytest.raises(SystemExit, match="strict"): _recording_encryption_key(_record_args(tmp_path / "desk2"), "windows") @@ -287,18 +295,20 @@ def _mockmed_run(tmp_path: Path, bundle: Path, run_dir: Path, **kw): stop() -def test_a_run_directory_is_plaintext_by_default_and_named( - default_mode: Path, tmp_path: Path, capsys +def test_a_run_directory_is_sealed_by_default( + default_mode: Path, tmp_path: Path ) -> None: from tests.test_after_stop_mockmed import _workflow bundle = tmp_path / "bundle" - _workflow().save(bundle) + _workflow().save(bundle) # a plaintext bundle from before the default run_dir = tmp_path / "run" _mockmed_run(tmp_path, bundle, run_dir) - assert (run_dir / "report.json").is_file() - assert str(run_dir) in capsys.readouterr().err - assert any(e.get("path") == str(run_dir) for e in _ledger(default_mode)) + assert sealed_set.is_sealed(run_dir) + assert not (run_dir / "report.json").exists() + assert json.loads(sealed_set.read_text(run_dir / "report.json")) + _assert_ciphertext_only(run_dir) + assert not any(e.get("path") == str(run_dir) for e in _ledger(default_mode)) def test_strict_mode_seals_the_run_directory_of_a_plaintext_bundle( diff --git a/packages/flow/tests/test_key_hierarchy.py b/packages/flow/tests/test_key_hierarchy.py index 4fd956634d..deb23cc68b 100644 --- a/packages/flow/tests/test_key_hierarchy.py +++ b/packages/flow/tests/test_key_hierarchy.py @@ -198,7 +198,7 @@ def test_a_configured_key_keeps_the_v1_header(home, monkeypatch) -> None: assert keychain.values == {} -def test_a_legacy_plaintext_folder_and_key_file_still_work(home) -> None: +def test_a_legacy_plaintext_folder_and_key_file_still_work(home, monkeypatch) -> None: root, _keychain = home legacy = base64.urlsafe_b64encode(os.urandom(32)).decode() keys = root / "keys" @@ -207,8 +207,10 @@ def test_a_legacy_plaintext_folder_and_key_file_still_work(home) -> None: os.chmod(keys / at_rest.KEY_NAME, 0o600) assert crypto.resolve_key(None) == legacy old = root.parent / "old" - with sealed_set.writing(old, "run", legacy) as writer: # what main wrote + monkeypatch.setenv(crypto.ENV_KEY, legacy) # write the v1 set main wrote + with sealed_set.writing(old, "run", legacy) as writer: writer.write("report.json", b"old") + monkeypatch.delenv(crypto.ENV_KEY) assert _header(old)["version"] == 1 assert sealed_set.read_bytes(old / "report.json") == b"old" plain = root.parent / "plain" diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index 0dbb37b2e5..2053e0ec4f 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -873,6 +873,7 @@ def test_the_new_key_notice_is_held_for_the_finale(root, monkeypatch, tmp_path): monkeypatch.delenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", raising=False) monkeypatch.setenv("OPENADAPT_FLOW_AT_REST_HOME", str(tmp_path / "home")) + monkeypatch.setenv("OPENADAPT_FLOW_KEY_STORE", "file") err = io.StringIO() monkeypatch.setattr(sys, "stderr", err) stream = io.StringIO() @@ -882,10 +883,10 @@ def test_the_new_key_notice_is_held_for_the_finale(root, monkeypatch, tmp_path): assert at_rest.local_key_path().exists() run_story(FakeEngine(root), view, next_steps=_steps, clock=_clock()) assert err.getvalue() == "" - assert ( - f"Created a local encryption key at {at_rest.local_key_path()}" - in stream.getvalue() - ) + # The local passphrase and the device key new runs are wrapped to. + assert "Created a local encryption key at " in stream.getvalue() + assert str(at_rest.local_key_path()) in stream.getvalue() + assert str(at_rest.device_key_path()) in stream.getvalue() def test_no_key_is_created_under_the_opt_out(root, monkeypatch, tmp_path): From 4c082e3afca0ebf2466dcc94d8dc33dd222483ed Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:23:50 -0500 Subject: [PATCH 04/37] flow: sealed bundles never yield plaintext runs; legacy plaintext runs continue plaintext; desktop encryption test --- packages/flow/docs/phi_at_rest.md | 6 ++- .../runtime/durable/first_local_runtime.py | 20 ++++++++-- packages/flow/tests/test_at_rest_default.py | 10 +++-- packages/flow/tests/test_attended_at_rest.py | 14 +++++-- packages/flow/tests/test_desktop_record.py | 40 +++++++++++++++++++ 5 files changed, 79 insertions(+), 11 deletions(-) diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index 1153ef2157..e077fd5389 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -26,7 +26,7 @@ organization's key (see [Key hierarchy](#key-hierarchy)). | Cross-window recordings (`record --surface`) | Logged | Held back before the command runs | | Bundles from `compile`, `induce`, `admit` | Encrypted | Encrypted | | Run directories (report, step screenshots, crops, frames, evidence) | Encrypted | Encrypted | -| A run with an approval gate, an attended draft, a business-decision state or `--save-healed-to` | Logged, under this computer's key; refused with a configured key | Refused before it runs | +| A run with an approval gate, an attended draft, a business-decision state or `--save-healed-to` | Logged for a plaintext bundle; refused for an encrypted one (the default since this release) | Refused before it runs | | The bundle, skill library and compiled fix of `teach` | Encrypted from encrypted input; otherwise logged | Encrypted | | The sanitized review copy and approved archive of `push` | Encrypted from encrypted input; otherwise logged | Encrypted | | The receipt page (`seal.html`) beside an encrypted run | Logged: it embeds the run report | Not written | @@ -570,6 +570,10 @@ marks as logged. Also: `admission-decision.json`. - Bundles encrypted with the older `Workflow.save(encrypt=True)` library call and no `seal`: only `workflow.json` and `templates/` are encrypted there. +- Attended continuation (`execute_attended_action`, the Desktop and + console path) of an encrypted run directory is not built yet. A run + directory from before this release keeps running in plaintext (logged), + with its attended state in its own encrypted containers. - Commands outside the list above, `repair` among them, refuse sealed input rather than decrypt it to disk. Each says so before it reads anything. diff --git a/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py b/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py index d2262a409f..f46f466073 100644 --- a/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py +++ b/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py @@ -175,13 +175,27 @@ def run_with_output( # By default (docs/phi_at_rest.md) every run directory is sealed too. seal_run = at_rest.strict() or bundle_sealed or at_rest.seals_by_default() downgraded = False - if seal_run and not at_rest.strict() and not at_rest.explicit_key(): - # Under this computer's own key, a run feature whose state can't be + if ( + seal_run + and not bundle_sealed + and not at_rest.strict() + and not at_rest.explicit_key() + ): + # The run of a plaintext bundle with a feature whose state can't be # sealed yet runs in plaintext, named on stderr and in the ledger, - # rather than being refused. Strict mode and a configured key refuse. + # rather than being refused. A sealed bundle never yields a plaintext + # run; strict mode and a configured key refuse. + run_path_now = Path(run_dir) + legacy_plain = ( + run_path_now.is_dir() + and not _sealed.is_sealed(run_path_now) + and any(run_path_now.iterdir()) + ) held = ( "a healed bundle (--save-healed-to)" if save_healed_to is not None + else "plaintext state from before encryption was the default" + if legacy_plain else replayer._sealed_run_unsupported(workflow) ) if held is not None: diff --git a/packages/flow/tests/test_at_rest_default.py b/packages/flow/tests/test_at_rest_default.py index 16bdb34b60..750526f71b 100644 --- a/packages/flow/tests/test_at_rest_default.py +++ b/packages/flow/tests/test_at_rest_default.py @@ -535,18 +535,20 @@ def test_strict_holds_back_qualification_trials( ) -def test_a_local_key_bundle_under_the_opt_out_refuses_to_run( +def test_a_local_key_bundle_under_the_opt_out_still_runs_sealed( default_mode: Path, tmp_path: Path, monkeypatch ) -> None: + """The opt-out stops new encryption, not reading what was encrypted: + and a sealed bundle still runs into a sealed run directory.""" from tests.test_after_stop_mockmed import _workflow bundle = tmp_path / "bundle" with sealed_set.writing(bundle, "bundle", crypto.resolve_key(None)): _workflow().save(bundle) monkeypatch.setenv(at_rest.OPT_OUT_ENV, "desktop") - with pytest.raises(sealed_set.SealedSetError): - _mockmed_run(tmp_path, bundle, tmp_path / "run") - assert not (tmp_path / "run").exists() + _mockmed_run(tmp_path, bundle, tmp_path / "run") + assert sealed_set.is_sealed(tmp_path / "run") + _assert_ciphertext_only(tmp_path / "run") @pytest.mark.skipif(os.name != "posix" or os.geteuid() == 0, reason="POSIX perms") diff --git a/packages/flow/tests/test_attended_at_rest.py b/packages/flow/tests/test_attended_at_rest.py index ab99df6dd1..4cf3b1559a 100644 --- a/packages/flow/tests/test_attended_at_rest.py +++ b/packages/flow/tests/test_attended_at_rest.py @@ -163,9 +163,17 @@ def test_default_mode_program_continue_encrypts_receipts_and_controls( tmp_path, default_mode ): workflow = _attended_program() - _bundle, run, _backend, _store, capability = _run_attended_program_to_pause( - tmp_path, workflow - ) + # The run itself is a plaintext run directory (attended continuation of + # an encrypted run directory is not built yet, docs/phi_at_rest.md); its + # attended state is still encrypted in its own containers. + sealing = at_rest.seals_by_default + at_rest.seals_by_default = lambda: False # type: ignore[assignment] + try: + _bundle, run, _backend, _store, capability = _run_attended_program_to_pause( + tmp_path, workflow + ) + finally: + at_rest.seals_by_default = sealing # type: ignore[assignment] vision = FakeVision() vision.text_results["DONE"] = Match( point=(10, 10), region=(0, 0, 20, 20), confidence=1.0 diff --git a/packages/flow/tests/test_desktop_record.py b/packages/flow/tests/test_desktop_record.py index 1763cc3a8b..2e9b4f5399 100644 --- a/packages/flow/tests/test_desktop_record.py +++ b/packages/flow/tests/test_desktop_record.py @@ -1109,3 +1109,43 @@ def fake_record(out_dir, **kwargs): stop = captured["stop"] assert isinstance(stop, UntilCommand) assert stop.argv == ["python3", "check_awake.py"] + + +def test_an_encrypted_desktop_recording_leaves_only_ciphertext( + tmp_path: Path, +) -> None: + """With a key, the converted recording is sealed into the output and the + raw capture session and converted plaintext beside it are deleted.""" + from openadapt_flow import crypto, sealed_set + + log: list = [] + frame = b"\x89PNG\r\n\x1a\nsynthetic desktop frame" + + def fake_convert(cap_dir: Path, out_dir: Path, *, params=None) -> Path: + (Path(cap_dir) / "capture.db").write_bytes(b"raw synthetic session") + (Path(out_dir) / "frames").mkdir() + (Path(out_dir) / "frames" / "f1.png").write_bytes(frame) + (Path(out_dir) / "events.jsonl").write_text('{"text": "typed value"}\n') + (Path(out_dir) / "meta.json").write_text("{}") + return Path(out_dir) + + key = "a-deployment-key-for-tests" + out = record_desktop_capture( + tmp_path / "rec", + recorder_factory=_make(log), + convert=fake_convert, + stop=lambda: True, + announce=False, + encryption_key=key, + ) + assert out == tmp_path / "rec" and sealed_set.is_sealed(out) + leftovers = [p for p in tmp_path.rglob("*") if p.is_file()] + for path in leftovers: + data = path.read_bytes() + assert b"typed value" not in data and b"raw synthetic" not in data, path + assert not data.startswith(b"\x89PNG"), path + stray = [p for p in leftovers if not str(p).startswith(str(out))] + assert [p for p in stray if p.suffix != ".lock"] == [] # lock files only + opened = sealed_set.SealedSet.open(out, key) + assert opened.read_bytes("frames/f1.png") == frame + assert crypto.is_encrypted((out / "events.jsonl.enc").read_bytes()) From 47d035a00319031aea2bbd4d64e464c960d95d88 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:49:09 -0500 Subject: [PATCH 05/37] benchmark: quickstart timing with everything encrypted by default --- packages/flow/benchmark/at_rest/RESULTS.md | 4 ++++ .../quickstart_default_2026-11-21.json | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 packages/flow/benchmark/at_rest/quickstart_default_2026-11-21.json diff --git a/packages/flow/benchmark/at_rest/RESULTS.md b/packages/flow/benchmark/at_rest/RESULTS.md index d30b6c23bd..149a4e2ba4 100644 --- a/packages/flow/benchmark/at_rest/RESULTS.md +++ b/packages/flow/benchmark/at_rest/RESULTS.md @@ -34,3 +34,7 @@ Reproduce: ```bash python benchmark/at_rest/run.py --actions 150 --out benchmark/at_rest/results.json ``` + +## Quickstart with everything encrypted by default (2026-11-21) + +Headless `openadapt quickstart` on MockMed, before (origin/main `4d9dc90c6`: recording, bundle and run folders plaintext) and after (sealed-set v3 for all of them), interleaved on one loaded laptop. Medians of three warm runs each: 90.6 s before, 94.5 s after. The gap is within run-to-run noise at this load (25 to 37). One after run that hit a 180 s system-Chrome launch timeout is excluded. Data: [quickstart_default_2026-11-21.json](quickstart_default_2026-11-21.json). diff --git a/packages/flow/benchmark/at_rest/quickstart_default_2026-11-21.json b/packages/flow/benchmark/at_rest/quickstart_default_2026-11-21.json new file mode 100644 index 0000000000..07097adea3 --- /dev/null +++ b/packages/flow/benchmark/at_rest/quickstart_default_2026-11-21.json @@ -0,0 +1,24 @@ +{ + "schema": "openadapt.flow.benchmark.at-rest-quickstart/v1", + "what": "openadapt quickstart --headless (MockMed), wall clock per run, before (origin/main 4d9dc90c6: run folders, recording and bundle plaintext) and after (this branch: all sealed-set v3)", + "machine": "2026 MacBook (Apple silicon), shared with other agent sessions; device key in a file store (OPENADAPT_FLOW_KEY_STORE=file), so no keychain call", + "method": "interleaved before/after, one run each in turn, same venv, PYTHONPATH selects the code; each run in a fresh output folder; 1-minute load average at the end of each run", + "date": "2026-11-21", + "runs": [ + {"code": "before", "seconds": 127.1, "load_1m": 34.73, "note": "first run of the round"}, + {"code": "after", "seconds": 98.04, "load_1m": 34.85}, + {"code": "before", "seconds": 90.62, "load_1m": 24.78}, + {"code": "after", "seconds": 94.5, "load_1m": 36.72}, + {"code": "before", "seconds": 88.87, "load_1m": 29.48}, + {"code": "after", "seconds": 89.78, "load_1m": 30.24}, + {"code": "before", "seconds": 91.17, "load_1m": 32.23}, + {"code": "after", "seconds": 243.57, "load_1m": 21.91, "excluded": "system Chrome failed to launch (Playwright 180 s timeout) before the quickstart fell back to its own Chromium; unrelated to encryption"} + ], + "summary": { + "before_median_s": 90.62, + "after_median_s": 94.5, + "before_n": 3, + "after_n": 3, + "note": "medians exclude the first before run (warm-up) and the Chrome-timeout run; the machine was loaded (load 25-37), so the 4% gap is within run-to-run noise (before ranged 88.9-127.1 s). An earlier trial of the branch alone at load 32-57 took 78.1 s." + } +} From 985a83b277a1970df8260a73749ec5e044efc345 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:55:04 -0500 Subject: [PATCH 06/37] flow: refuse passphrase rewrap of v3 sets; mypy fixes --- packages/flow/openadapt_flow/at_rest.py | 8 ++++---- packages/flow/openadapt_flow/key_rotation.py | 4 ++++ packages/flow/openadapt_flow/sealed_set.py | 7 ++++--- tests/test_quickstart.py | 4 +++- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/packages/flow/openadapt_flow/at_rest.py b/packages/flow/openadapt_flow/at_rest.py index 06e14505c0..feb2a06e0e 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -399,11 +399,11 @@ def work() -> None: f"the OS keychain did not answer a {what} within " f"{_KEYCHAIN_TIMEOUT_S:.0f} s" ) - if "error" in result: - exc = result["error"] + failure = result.get("error") + if isinstance(failure, BaseException): raise KeyStoreUnavailable( - f"the OS keychain refused a {what} ({type(exc).__name__})" - ) from exc # type: ignore[misc] + f"the OS keychain refused a {what} ({type(failure).__name__})" + ) from failure value = result.get("value") return value if isinstance(value, str) else None diff --git a/packages/flow/openadapt_flow/key_rotation.py b/packages/flow/openadapt_flow/key_rotation.py index badedc25d9..e6902969a7 100644 --- a/packages/flow/openadapt_flow/key_rotation.py +++ b/packages/flow/openadapt_flow/key_rotation.py @@ -95,6 +95,10 @@ def plan_rewrap( if old_key == new_key: raise RotationError("distinct_wrapping_key_required") base = _root(root) + if sealed_set.read_header(base).get("version") == sealed_set.ENVELOPE_VERSION: + # A version 3 set has no passphrase wrap: its keys rotate by + # rewrapping its bucket record (docs/phi_at_rest.md). + raise RotationError("version_3_set_rotates_by_bucket") info = base.stat() opened, files, header = _verified(base, old_key) data_key = sealed_set._data_key(opened._header, old_key) diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index e8fdf8e11b..c9308e6898 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -652,10 +652,11 @@ def _open_v3(header: dict[str, object]) -> V3Key: raise if bucket.fpr != key_ref.get("bucket_pub_fpr"): raise SealedSetError("the bucket record does not match the set's key reference") + stanzas = header.get("stanzas") stanza = next( ( s - for s in header.get("stanzas") or [] # type: ignore[union-attr] + for s in (stanzas if isinstance(stanzas, list) else []) if isinstance(s, dict) and s.get("fpr") == bucket.fpr ), None, @@ -998,7 +999,7 @@ def _initialize(self, passphrase: Optional[str], *, resume: bool) -> None: self.root.mkdir(parents=True, exist_ok=True) created = _new_v3(kind, passphrase) if created is not None: - self._header, self._key = created + self._header, self._key = created[0], created[1] # type: ignore[assignment] self._new = True self._write_header() return @@ -1191,7 +1192,7 @@ def _close_bucket(self) -> None: A bundle keeps it: programs replay unattended.""" from openadapt_flow import key_hierarchy as kh - bucket = self._key.bucket # type: ignore[union-attr] + bucket = getattr(self._key, "bucket", None) if bucket is None: return kh.close(bucket) diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index 2053e0ec4f..2b4406319a 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -886,7 +886,9 @@ def test_the_new_key_notice_is_held_for_the_finale(root, monkeypatch, tmp_path): # The local passphrase and the device key new runs are wrapped to. assert "Created a local encryption key at " in stream.getvalue() assert str(at_rest.local_key_path()) in stream.getvalue() - assert str(at_rest.device_key_path()) in stream.getvalue() + device_key_path = getattr(at_rest, "device_key_path", None) + if device_key_path is not None: # Flow with the key hierarchy + assert str(device_key_path()) in stream.getvalue() def test_no_key_is_created_under_the_opt_out(root, monkeypatch, tmp_path): From ead21ad6e9f0d3230bbbe85d7d9fbd3c6c0d651b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:57:05 -0500 Subject: [PATCH 07/37] flow: keep __main__ growth small; RFC 9180 derivation vector; no internal references --- CAPABILITIES.md | 2 +- packages/flow/docs/design/DECOMPOSITION.md | 4 +- packages/flow/docs/phi_at_rest.md | 2 - packages/flow/openadapt_flow/__main__.py | 65 +++---------------- packages/flow/openadapt_flow/cli_at_rest.py | 37 +++++++++++ packages/flow/openadapt_flow/key_hierarchy.py | 3 +- packages/flow/tests/conftest.py | 7 +- packages/flow/tests/test_key_hierarchy.py | 11 ++++ 8 files changed, 69 insertions(+), 62 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index ea704c595f..e18b6e94b4 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -347,7 +347,7 @@ improvising or retrying when something is off. | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | -| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On this branch | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main (this PR) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 299218b7ff..9acb2024d7 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -602,11 +602,13 @@ PR #2280 raised `replayer.py` by 12 lines: the call sites of the clock-text chec PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwright_backend.py`: the dropdown choice contract, its dispatch and read-back, unexpected-dialog stops, and the recorder's choice and dialog hooks; the page-side capture code and the actuator live in `choice_capture.py` and `backends/choice.py`. The pinned dialog methods delegate to `runtime/dialog_delivery.py`, preserving the original document arm without rearming after input. +The encryption-at-rest default raised `__main__.py` by 17 lines: the five sealed-ready and strict-safe entries for `inspect report-run` and `at-rest`, the version 3 key precheck, and the encrypted desktop recording key; the `at-rest` command, `--no-encrypt` and its handling live in `cli_at_rest.py`. + | File | Line budget | |---|---:| | `packages/flow/openadapt_flow/runtime/replayer.py` | 20090 | -| `packages/flow/openadapt_flow/__main__.py` | 14331 | +| `packages/flow/openadapt_flow/__main__.py` | 14348 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | | `packages/flow/openadapt_flow/ir.py` | 6830 | | `packages/desktop/openadapt_desktop/dispatch.py` | 6524 | diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index e077fd5389..c9c0580b12 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -103,8 +103,6 @@ What stays readable is listed under [What is not encrypted](#what-is-not-encrypt ## Key hierarchy -The design is the evidence-encryption memo of 2026-11-20 -(openadapt-internal `docs/design/evidence-encryption-2026-11/MEMO.md`). Every new recording, bundle and run directory (sealed-set format version 3) has three layers of keys: diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 687ae194d4..9bc58a6347 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -98,6 +98,7 @@ from urllib.parse import urlsplit from uuid import UUID +from openadapt_flow import cli_at_rest as _at_rest_cli from openadapt_flow.cli_params import _parse_params as _parse_params from openadapt_flow.cli_params import _replay_params as _replay_params from openadapt_flow.private_file import open_binary @@ -526,10 +527,8 @@ def _recording_encryption_key(args: argparse.Namespace, backend: str) -> Optiona return None explicit = os.environ.get(sealed_set.RECORDING_ENV_KEY) or None if backend != "web": - # The raw capture session (database, video) is plaintext while - # recording; Flow encrypts the converted recording and deletes the - # raw session (docs/phi_at_rest.md, "Desktop recordings"). Strict - # mode holds the raw window back. + # The raw capture is plaintext while recording; the converted + # recording is sealed (docs/phi_at_rest.md). Strict holds it back. if at_rest.strict(): at_rest.unsealed_write(f"a {backend} raw capture session", out) if at_rest.opt_out_reason() is not None: @@ -1791,19 +1790,11 @@ def _cmd_record_surfaces(args: argparse.Namespace) -> int: "--surface WINDOW). Nothing was recorded." ) # A capture session runs for every cross-window recording, and Flow - # cannot encrypt a cross-window recording yet: it is written in - # plaintext, named on stderr and in the ledger (strict mode refuses). + # cannot encrypt a cross-window recording yet: logged (strict refuses). if _recording_encryption_key( args, surfaces[0].kind if surfaces else host_surface_kind() ): - from openadapt_flow import at_rest - - try: - at_rest.unsealed_write( - "a cross-window recording (--surface)", args.out or "--out" - ) - except at_rest.AtRestRefused as exc: - raise SystemExit(f"record: {exc}") from exc + _at_rest_cli.note_plaintext_recording("a cross-window recording", args.out) desktop_params: dict[str, str] = {} web_params: list[str] = [] for entry in args.param or (): @@ -8463,7 +8454,6 @@ def _emit_local_receipt(args: argparse.Namespace) -> int: print(f"report-run failed: no report.json in {run_dir} — nothing to report.") return 1 try: - # Decrypted in memory when the run directory is encrypted. report = RunReport.model_validate_json(artifacts.read_text(report_path)) except (OSError, ValueError, sealed_set.SealedSetError): print("report-run failed: report.json is unreadable or invalid") @@ -9799,16 +9789,7 @@ def build_parser() -> argparse.ArgumentParser: "an irreversible step on every run." ), ) - p.add_argument( - "--no-encrypt", - action="store_true", - help=( - "Write this command's output in plaintext (recorded in " - "~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is " - "encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. " - "Ignored under OPENADAPT_FLOW_AT_REST=strict" - ), - ) + _at_rest_cli.add_no_encrypt(p) p.set_defaults(func=_cmd_compile) p = sub.add_parser( @@ -10326,16 +10307,7 @@ def build_parser() -> argparse.ArgumentParser: _add_browser_session_flags(p) _add_deployment_flags(p, worklist=True) _add_attest_flags(p) - p.add_argument( - "--no-encrypt", - action="store_true", - help=( - "Write this command's output in plaintext (recorded in " - "~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is " - "encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. " - "Ignored under OPENADAPT_FLOW_AT_REST=strict" - ), - ) + _at_rest_cli.add_no_encrypt(p) p.set_defaults(func=_cmd_replay) p = sub.add_parser( @@ -10603,16 +10575,7 @@ def build_parser() -> argparse.ArgumentParser: ), ) _add_approval_flags(p) - p.add_argument( - "--no-encrypt", - action="store_true", - help=( - "Write this command's output in plaintext (recorded in " - "~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is " - "encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. " - "Ignored under OPENADAPT_FLOW_AT_REST=strict" - ), - ) + _at_rest_cli.add_no_encrypt(p) p.set_defaults(func=_cmd_run) sa = sub.add_parser( @@ -10641,9 +10604,7 @@ def build_parser() -> argparse.ArgumentParser: _register_no_outbound(sub) - from openadapt_flow.cli_at_rest import register as _register_at_rest - - _register_at_rest(sub) + _at_rest_cli.register(sub) from openadapt_flow.cli_service import register as _register_service @@ -14333,13 +14294,7 @@ def main( return 2 from openadapt_flow import at_rest - if ( - getattr(args, "no_encrypt", False) - and getattr(args, "func", None) is not _cmd_record - ): - # `compile/run/replay --no-encrypt`: this process writes plaintext, - # with the one-line warning and the ledger line at the first write. - at_rest.opt_out_for_this_process("--no-encrypt") + _at_rest_cli.apply_no_encrypt(args, _cmd_record) try: _unsealed_output_check(args) except (at_rest.AtRestRefused, ValueError) as exc: diff --git a/packages/flow/openadapt_flow/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py index d2fec9f749..1e5888966f 100644 --- a/packages/flow/openadapt_flow/cli_at_rest.py +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -114,6 +114,43 @@ def _cmd_shred(args: argparse.Namespace) -> int: return 0 +def add_no_encrypt(p: argparse.ArgumentParser) -> None: + """``--no-encrypt`` on ``compile``, ``run`` and ``replay``.""" + p.add_argument( + "--no-encrypt", + action="store_true", + help=( + "Write this command's output in plaintext (recorded in " + "~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is " + "encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. " + "Ignored under OPENADAPT_FLOW_AT_REST=strict" + ), + ) + + +def apply_no_encrypt(args: argparse.Namespace, record_func: object) -> None: + """``compile/run/replay --no-encrypt``: this process writes plaintext, with + the one-line warning and the ledger line at the first write. ``record`` + handles its own flag.""" + from openadapt_flow import at_rest + + if ( + getattr(args, "no_encrypt", False) + and getattr(args, "func", None) is not record_func + ): + at_rest.opt_out_for_this_process("--no-encrypt") + + +def note_plaintext_recording(artifact: str, out: object) -> None: + """Name and record a recording Flow can't encrypt yet (strict refuses).""" + from openadapt_flow import at_rest + + try: + at_rest.unsealed_write(artifact, str(out or "--out")) + except at_rest.AtRestRefused as exc: + raise SystemExit(f"record: {exc}") from exc + + def register(sub: argparse._SubParsersAction) -> None: p = sub.add_parser( "at-rest", diff --git a/packages/flow/openadapt_flow/key_hierarchy.py b/packages/flow/openadapt_flow/key_hierarchy.py index d7658a0c06..88b8847e53 100644 --- a/packages/flow/openadapt_flow/key_hierarchy.py +++ b/packages/flow/openadapt_flow/key_hierarchy.py @@ -1,7 +1,6 @@ """Who can open an encrypted run: the key hierarchy behind sealed-set v3. -Design: openadapt-internal ``docs/design/evidence-encryption-2026-11/MEMO.md`` -(sections 3.1 to 3.8). The layers:: +See docs/phi_at_rest.md ("Key hierarchy"). The layers:: data key (DEK, 256-bit, one per sealed set) wrapped by HPKE (P-256, HKDF-SHA256, AES-256-GCM) to diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index d980bc776e..19c135ca6c 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -2,6 +2,7 @@ from __future__ import annotations +import os import sys from pathlib import Path @@ -72,7 +73,11 @@ def _isolation_env(root: Path) -> dict[str, str | None]: "OPENADAPT_LEDGER_AUTHORITY_CONFIG": None, # Preserve the suite's recorded synthetic-data opt-out. The default # encryption and strict modes are covered by test_at_rest_default.py. - "OPENADAPT_FLOW_PLAINTEXT_AT_REST": "test suite: synthetic data", + # OPENADAPT_TEST_DEFAULT_AT_REST=1 runs the suite under the real + # default (everything sealed), to find readers that assume plaintext. + "OPENADAPT_FLOW_PLAINTEXT_AT_REST": None + if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") == "1" + else "test suite: synthetic data", "OPENADAPT_FLOW_AT_REST_HOME": str(root / ".at-rest-home"), "OPENADAPT_FLOW_AT_REST": None, # The device key goes to a file in the isolated home, never to the diff --git a/packages/flow/tests/test_key_hierarchy.py b/packages/flow/tests/test_key_hierarchy.py index deb23cc68b..25ad34d2d3 100644 --- a/packages/flow/tests/test_key_hierarchy.py +++ b/packages/flow/tests/test_key_hierarchy.py @@ -523,3 +523,14 @@ def test_strict_mode_ignores_the_opt_out(home, monkeypatch) -> None: def test_new_artifacts_are_sealed_by_default(home) -> None: assert at_rest.DEFAULT_SEALS_ARTIFACTS is True assert at_rest.seals_by_default() is True + + +def test_recovery_key_derivation_matches_rfc_9180() -> None: + """DeriveKeyPair for DHKEM(P-256, HKDF-SHA256): RFC 9180 A.3.1 (ikmE, skEm).""" + ikm = bytes.fromhex( + "4270e54ffd08d79d5928020af4686d8f6b7d35dbe470265f1f5aa22816ce860e" + ) + private = kh._hpke_derive_p256(ikm) + assert private.private_numbers().private_value.to_bytes(32, "big").hex() == ( + "4995788ef4b9d6132b249ce59a77281493eb39af373d236a1fe415cb0c2d7beb" + ) From 13cde42096bc3d8a88cca28922a8ec036ef09ebb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:06:22 -0500 Subject: [PATCH 08/37] flow: encrypt undo prior state and narration inside sealed sets; branch teach reads encrypted runs Found by running the reader suites under the real default (OPENADAPT_TEST_DEFAULT_AT_REST=1). --- llms-full.txt | 2 +- packages/flow/docs/phi_at_rest.md | 15 ++++++++++----- packages/flow/openadapt_flow/after_stop.py | 16 ++++++++++++---- .../flow/openadapt_flow/learning/branch_teach.py | 12 ++++++------ packages/flow/openadapt_flow/narration.py | 8 ++++++++ packages/flow/openadapt_flow/sealed_set.py | 2 ++ 6 files changed, 39 insertions(+), 16 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index 706c2887dd..6e3333da42 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -781,7 +781,7 @@ improvising or retrying when something is off. | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | -| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On this branch | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#key-hierarchy) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main (this PR) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index c9c0580b12..f9c34f53be 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -351,7 +351,7 @@ step with them. | `qualification-proposal.json`, `qualification-proposal.draft.json`, `qualification-admission.local-dev.json`, `qualification/*` | Qualification pins, cases and reports | Encrypted | | `admission-decision.json`, `admission.json`, `admit.json`, `jit_draft.json` | Admission records; some carry read-back values or a login name | Encrypted | | `teach-authorization/*` | The person-signed teach authorization the program was taught under; a spelled-out input or record value is in it | Encrypted | -| `openadapt-card.json`, `repair/*`, `evidence/*` | Operator card, repair candidates with anchor text, copied evidence | Encrypted | +| `openadapt-card.json`, `repair/*`, `evidence/*`, `narration.json` | Operator card, repair candidates with anchor text, copied evidence, scrubbed narration | Encrypted | | Anything else | Unknown | `seal` refuses | ### Recording @@ -364,7 +364,7 @@ step with them. | `network.jsonl` | Request URLs, form fields and bodies, response bodies (`--capture-network`) | Encrypted | | `sor_snapshots.json`, `verify.proposed.yaml` | System-of-record rows read by `record --verify`, and the effects proposed from them | Encrypted | | `check.json`, `check.proposed.json`, `readback.proposed.yaml`, `record_check.proposed.yaml`, `record_check.proof.json`, `identity.proposed.json`, `effect_contract.yaml` | Checks and proposals derived from the recording | Encrypted | -| `distill.json`, `.openadapt-approval.json`, `.openadapt-sanitization.json` | Derived reports and approvals | Encrypted | +| `distill.json`, `narration.json`, `.openadapt-approval.json`, `.openadapt-sanitization.json` | Derived reports, scrubbed narration, approvals | Encrypted | | Anything else | Unknown | Refused | ### Skill library @@ -417,12 +417,17 @@ still read. `tests/test_attended_at_rest.py` runs attended decisions under the same disk audit hook and checks that no attended file or journal row holds plaintext. -### Run directory of a sealed bundle +### Run directory Every file is encrypted except these structural ones: `.durable_run.claim` (run id and namespace), the empty `*.lock` files, `.attended_action.lease` -(nonce digests and times) and `.attended_capability.key` (a random per-run -secret, no recorded data). The durable store's checkpoints, pauses and +(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 +[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 approvals are sealed under the same key with their own AES-256-GCM containers, and the run set adopts them as ciphertext. A file written in plaintext by any other component makes the run refuse to seal its index. diff --git a/packages/flow/openadapt_flow/after_stop.py b/packages/flow/openadapt_flow/after_stop.py index 69947d0b35..a13d917799 100644 --- a/packages/flow/openadapt_flow/after_stop.py +++ b/packages/flow/openadapt_flow/after_stop.py @@ -913,6 +913,12 @@ def keep_prior_state( payload["existing_ids"] = existing payload["restore"] = restored path = prior_state_path(run_dir, step.id) + from openadapt_flow import sealed_set + + if sealed_set.is_sealed_path(run_dir): + # Record values: encrypted with the rest of an encrypted run. + sealed_set.write_text(path, json.dumps(payload)) + return path path.parent.mkdir(parents=True, exist_ok=True) staging = path.with_name(f".{path.name}.{os.getpid()}") fd = os.open(staging, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) @@ -925,12 +931,14 @@ def keep_prior_state( def read_prior_state(run_dir: Path | str, step_id: str) -> Optional[dict[str, Any]]: + from openadapt_flow import sealed_set + path = prior_state_path(run_dir, step_id) - if not path.is_file(): - return None try: - raw = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): + if not sealed_set.is_file(path): + return None + raw = json.loads(sealed_set.read_text(path)) + except (OSError, ValueError): return None if not isinstance(raw, dict) or raw.get("schema") != _PRIOR_SCHEMA: return None diff --git a/packages/flow/openadapt_flow/learning/branch_teach.py b/packages/flow/openadapt_flow/learning/branch_teach.py index 080c62362f..e6db5b1766 100644 --- a/packages/flow/openadapt_flow/learning/branch_teach.py +++ b/packages/flow/openadapt_flow/learning/branch_teach.py @@ -54,6 +54,7 @@ from pydantic import BaseModel, Field +from openadapt_flow import artifacts from openadapt_flow.ir import ( Guard, GuardSource, @@ -360,9 +361,9 @@ def _run_texts(run_dir: Path, report: RunReport) -> list[str]: if result.before_png is None: continue frame = run_dir / result.before_png - if not frame.is_file(): + if not artifacts.is_file(frame): continue - for line in ocr(frame.read_bytes()): + for line in ocr(artifacts.open_read(frame)): text = (scrub_text(line.text) or "").strip() if text: texts.append(text) @@ -375,9 +376,9 @@ def _load_negative( screen_texts: Callable[[Path, RunReport], list[str]], ) -> tuple[RunReport, list[str]]: path = Path(run_dir) / "report.json" - if not path.is_file(): + if not artifacts.is_file(path): raise TeachError(f"no run report at {path} for a normal run") - report = RunReport.model_validate_json(path.read_text(encoding="utf-8")) + report = RunReport.model_validate_json(artifacts.read_text(path)) if report.workflow_name != base.name: raise TeachError( f"the normal run at {run_dir} came from {report.workflow_name!r}, " @@ -782,8 +783,7 @@ def teach_branch( "narration_sha256": _digest(spoken[2]) if spoken_ok and spoken else None, }, "example_run_reports_sha256": [ - _digest((ex.run_dir / "report.json").read_text(encoding="utf-8")) - for ex in loaded + _digest(artifacts.read_text(ex.run_dir / "report.json")) for ex in loaded ], "runtime_model_calls": 0, } diff --git a/packages/flow/openadapt_flow/narration.py b/packages/flow/openadapt_flow/narration.py index 8213d1c687..dd38cfc61c 100644 --- a/packages/flow/openadapt_flow/narration.py +++ b/packages/flow/openadapt_flow/narration.py @@ -147,6 +147,14 @@ def write_narration(directory: Path, narration: Narration) -> Path: directory = Path(directory) directory.mkdir(parents=True, exist_ok=True) path = directory / NARRATION_FILE + from openadapt_flow import sealed_set + + if sealed_set.is_sealed_path(directory): + # What the person said: encrypted with an encrypted recording. + sealed_set.write_text( + path, narration.model_dump_json(indent=2, by_alias=True) + "\n" + ) + return path fd, tmp = tempfile.mkstemp(dir=directory, prefix=".narration-", suffix=".json") try: with os.fdopen(fd, "w", encoding="utf-8") as handle: diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index c9308e6898..dabc7ad397 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -199,6 +199,7 @@ class FileKind: ), FileKind("qualification/*", "phi", "qualification cases, inputs and reports"), FileKind("evidence/*", "phi", "run evidence a command copied into the bundle"), + FileKind("narration.json", "phi", "the recording's scrubbed narration"), ) RECORDING_FILES: Final[tuple[FileKind, ...]] = ( @@ -248,6 +249,7 @@ class FileKind: "a scaffolded effect contract with observed values", ), FileKind("distill.json", "phi", "a distillation report"), + FileKind("narration.json", "phi", "what the person said, scrubbed"), FileKind( ".openadapt-approval.json", "phi", "approval answers about recorded steps" ), From 6f2af080d5d0fc21cb32deed976024e3eaf6f534 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:06:50 -0500 Subject: [PATCH 09/37] docs: link the capability row to #2423 --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index e18b6e94b4..1e7f5a57b1 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -347,7 +347,7 @@ improvising or retrying when something is off. | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | -| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main (this PR) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | diff --git a/llms-full.txt b/llms-full.txt index 6e3333da42..f544f823ab 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -781,7 +781,7 @@ improvising or retrying when something is off. | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | -| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main (this PR) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#key-hierarchy) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | From 0b04985c1e1356a7a42e3970dcafec888ff63bed Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:44:54 -0500 Subject: [PATCH 10/37] flow: open key records with the binary-safe opener (Windows descriptor contract) --- packages/flow/openadapt_flow/key_hierarchy.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/key_hierarchy.py b/packages/flow/openadapt_flow/key_hierarchy.py index 88b8847e53..bbb82cb6ea 100644 --- a/packages/flow/openadapt_flow/key_hierarchy.py +++ b/packages/flow/openadapt_flow/key_hierarchy.py @@ -674,7 +674,9 @@ def _write_private(path: Path, data: bytes) -> None: at_rest._private_dir(path.parent) tmp = path.with_name(f".{path.name}.{secrets.token_hex(4)}.tmp") - fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + from openadapt_flow.private_file import open_binary + + fd = open_binary(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) try: os.write(fd, data) os.fsync(fd) From 54748f7f9a007061e99fc45e70159ca2c92ceecb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 04:17:42 -0500 Subject: [PATCH 11/37] flow: register the quickstart timing data in the public artifact inventory --- packages/flow/public-artifacts.json | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index c3dc9acd8f..062482a418 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -553,6 +553,7 @@ "benchmark/appliance_validation/results.json", "benchmark/appliance_validation/results_identity_full.json", "benchmark/appliance_validation/results_supplement.json", + "benchmark/at_rest/quickstart_default_2026-11-21.json", "benchmark/at_rest/results.json", "benchmark/canvas_ladder/results.json", "benchmark/choice_widgets/openemr/compose.yml", From a71c92e7851fe84f6f9b8bea269c81c57b8f328f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 04:58:43 -0500 Subject: [PATCH 12/37] flow: keep __main__.py from growing; at-rest command tables and helpers live in cli_at_rest --- packages/flow/docs/design/DECOMPOSITION.md | 4 +- packages/flow/openadapt_flow/__main__.py | 50 ++++++--------------- packages/flow/openadapt_flow/cli_at_rest.py | 41 +++++++++++++++++ 3 files changed, 57 insertions(+), 38 deletions(-) diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 9acb2024d7..965ef77110 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -602,13 +602,13 @@ PR #2280 raised `replayer.py` by 12 lines: the call sites of the clock-text chec PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwright_backend.py`: the dropdown choice contract, its dispatch and read-back, unexpected-dialog stops, and the recorder's choice and dialog hooks; the page-side capture code and the actuator live in `choice_capture.py` and `backends/choice.py`. The pinned dialog methods delegate to `runtime/dialog_delivery.py`, preserving the original document arm without rearming after input. -The encryption-at-rest default raised `__main__.py` by 17 lines: the five sealed-ready and strict-safe entries for `inspect report-run` and `at-rest`, the version 3 key precheck, and the encrypted desktop recording key; the `at-rest` command, `--no-encrypt` and its handling live in `cli_at_rest.py`. +The encryption-at-rest default lowered `__main__.py`: the `at-rest` command, `--no-encrypt`, the desktop recording key, the version 3 key precheck and their command-table entries live in `cli_at_rest.py`. | File | Line budget | |---|---:| | `packages/flow/openadapt_flow/runtime/replayer.py` | 20090 | -| `packages/flow/openadapt_flow/__main__.py` | 14348 | +| `packages/flow/openadapt_flow/__main__.py` | 14326 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | | `packages/flow/openadapt_flow/ir.py` | 6830 | | `packages/desktop/openadapt_desktop/dispatch.py` | 6524 | diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 9bc58a6347..d3fb02bc81 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -504,15 +504,9 @@ def _enforce_surface_binding( def _recording_encryption_key(args: argparse.Namespace, backend: str) -> Optional[str]: """The passphrase that encrypts this recording, or ``None`` for plaintext. - The web recorder encrypts every file from the first frame under - ``OPENADAPT_RECORDING_KEY`` or ``OPENADAPT_BUNDLE_KEY``, and under the - local key in strict mode (:mod:`openadapt_flow.at_rest`); otherwise the - plaintext recording is logged. ``--no-encrypt`` and - ``OPENADAPT_FLOW_PLAINTEXT_AT_REST`` opt out, with a warning and a ledger - line. The desktop recorders write a raw capture session through - openadapt-capture that Flow cannot encrypt yet: by default they record in - plaintext and name the directory on stderr and in the ledger; - ``OPENADAPT_FLOW_AT_REST=strict`` and a configured recording key refuse. + Recordings are encrypted by default (docs/phi_at_rest.md): the web + recorder from the first frame, a desktop recording once converted. + ``--no-encrypt`` and the opt-out record plaintext, with a warning. """ import os @@ -527,14 +521,7 @@ def _recording_encryption_key(args: argparse.Namespace, backend: str) -> Optiona return None explicit = os.environ.get(sealed_set.RECORDING_ENV_KEY) or None if backend != "web": - # The raw capture is plaintext while recording; the converted - # recording is sealed (docs/phi_at_rest.md). Strict holds it back. - if at_rest.strict(): - at_rest.unsealed_write(f"a {backend} raw capture session", out) - if at_rest.opt_out_reason() is not None: - at_rest.plaintext_allowed(f"a desktop recording at {out}") - return None - return explicit or sealed_set.recording_key() + return _at_rest_cli.desktop_recording_key(backend, out, explicit) except at_rest.AtRestRefused as exc: raise SystemExit(f"record: {exc}") from exc if explicit or os.environ.get(crypto.ENV_KEY): @@ -1480,7 +1467,7 @@ def _cmd_record_capture(args: argparse.Namespace) -> int: getattr(args, "browser_cdp_endpoint", None) or getattr(args, "browser_page_url", None) ) - recording_key = _recording_encryption_key(args, backend) + recording_key = args._recording_key = _recording_encryption_key(args, backend) if backend in ("windows", "macos", "linux", "rdp", "citrix"): if getattr(args, "capture_network", False): raise SystemExit( @@ -1492,7 +1479,7 @@ def _cmd_record_capture(args: argparse.Namespace) -> int: "record: --browser-cdp-endpoint and --browser-page-url apply " "only to --backend web" ) - return _cmd_record_desktop(args, backend, recording_key) + return _cmd_record_desktop(args, backend) if ( getattr(args, "window", None) @@ -1870,9 +1857,7 @@ def _cmd_record_surfaces(args: argparse.Namespace) -> int: return 0 -def _cmd_record_desktop( - args: argparse.Namespace, backend: str, recording_key: Optional[str] = None -) -> int: +def _cmd_record_desktop(args: argparse.Namespace, backend: str) -> int: """Record a live desktop demonstration for a native/pixel desktop backend. Reuses the tested capture stack: an ``openadapt-capture`` session captures @@ -1944,7 +1929,7 @@ def _cmd_record_desktop( replay_window_title=getattr(args, "rdp_window_title", None), readiness_text=getattr(args, "rdp_readiness_text", None), stop=_record_until_stop(args), - encryption_key=recording_key, + encryption_key=getattr(args, "_recording_key", None), ) _stamp_recording_surface(out, backend) print(f"Recording written to {out}") @@ -8444,7 +8429,7 @@ def _emit_local_receipt(args: argparse.Namespace) -> int: ``openadapt_flow.receipt``; the rich local ``REPORT.md`` -- screenshots, typed values, OCR identity text, parameters -- is never the source. """ - from openadapt_flow import artifacts, sealed_set + from openadapt_flow import artifacts from openadapt_flow.ir import RunReport from openadapt_flow.receipt import ReceiptError, build_receipt, write_receipt @@ -8455,7 +8440,7 @@ def _emit_local_receipt(args: argparse.Namespace) -> int: return 1 try: report = RunReport.model_validate_json(artifacts.read_text(report_path)) - except (OSError, ValueError, sealed_set.SealedSetError): + except (OSError, ValueError): # a SealedSetError is a ValueError print("report-run failed: report.json is unreadable or invalid") return 1 @@ -10605,7 +10590,6 @@ def build_parser() -> argparse.ArgumentParser: _register_no_outbound(sub) _at_rest_cli.register(sub) - from openadapt_flow.cli_service import register as _register_service _register_service(sub) @@ -13692,10 +13676,8 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.cli_undo:_cmd_undo_list", "openadapt_flow.cli_undo:_cmd_undo_approve", "openadapt_flow.cli_undo:_cmd_undo_run", - # Shreds a set's key only; no file is decrypted to disk. - "openadapt_flow.__main__:_cmd_report_run", - "openadapt_flow.cli_at_rest:_cmd_shred", } + | _at_rest_cli.SEALED_READY ) @@ -13741,8 +13723,6 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.cli_service:_cmd_pf_render", "openadapt_flow.cli_service:_cmd_restart", "openadapt_flow.cli_service:_cmd_run", - "openadapt_flow.cli_at_rest:_cmd_status", - "openadapt_flow.cli_at_rest:_cmd_recovery_create", "openadapt_flow.cli_no_outbound:_cmd_add", "openadapt_flow.cli_no_outbound:_cmd_derive", "openadapt_flow.cli_no_outbound:_cmd_list", @@ -13755,6 +13735,7 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.agent.seal_cli:cmd_keys_show", "openadapt_flow.agent.seal_cli:cmd_verify", } + | _at_rest_cli.STRICT_SAFE ) @@ -14190,7 +14171,7 @@ def _private_input(args: argparse.Namespace) -> bool: def _sealed_input_refusal(args: argparse.Namespace) -> Optional[str]: """Refuse a sealed path in a command that cannot keep it sealed, and a sealed path whose key is not configured, before the command runs.""" - from openadapt_flow import crypto, sealed_set + from openadapt_flow import sealed_set sealed = _sealed_paths_in(args) if not sealed: @@ -14212,10 +14193,7 @@ def _sealed_input_refusal(args: argparse.Namespace) -> Optional[str]: ) for root in sealed: kind = sealed_set.header_kind(root) - version = sealed_set.read_header(root).get("version") - if version != sealed_set.ENVELOPE_VERSION and not ( - sealed_set.passphrase_for(kind) or crypto.resolve_read_key(None) - ): + if _at_rest_cli.lacks_key(root, kind): return sealed_set.missing_key_message(root, kind) try: # With no key configured the local key resolves; opening the set diff --git a/packages/flow/openadapt_flow/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py index 1e5888966f..a757c3f345 100644 --- a/packages/flow/openadapt_flow/cli_at_rest.py +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -114,6 +114,47 @@ def _cmd_shred(args: argparse.Namespace) -> int: return 0 +#: Commands that read sealed input without decrypting it to disk: +#: ``inspect report-run`` reads the report in memory; ``shred`` touches keys. +SEALED_READY: frozenset[str] = frozenset( + { + "openadapt_flow.__main__:_cmd_report_run", + "openadapt_flow.cli_at_rest:_cmd_shred", + } +) +#: Commands that write no recorded data. +STRICT_SAFE: frozenset[str] = frozenset( + { + "openadapt_flow.cli_at_rest:_cmd_status", + "openadapt_flow.cli_at_rest:_cmd_recovery_create", + } +) + + +def desktop_recording_key(backend: str, out: object, explicit: object) -> object: + """The key for a desktop recording: its raw capture is plaintext while it + records and the converted recording is sealed (docs/phi_at_rest.md). + Strict mode holds the raw window back; the opt-out records plaintext.""" + from openadapt_flow import at_rest, sealed_set + + if at_rest.strict(): + at_rest.unsealed_write(f"a {backend} raw capture session", str(out)) + if at_rest.opt_out_reason() is not None: + at_rest.plaintext_allowed(f"a desktop recording at {out}") + return None + return explicit or sealed_set.recording_key() + + +def lacks_key(root: object, kind: str) -> bool: + """Whether no key is configured to open ``root``. A version 3 set needs + none: a key this computer holds may open it.""" + from openadapt_flow import crypto, sealed_set + + if sealed_set.read_header(root).get("version") == sealed_set.ENVELOPE_VERSION: # type: ignore[arg-type] + return False + return not (sealed_set.passphrase_for(kind) or crypto.resolve_read_key(None)) + + def add_no_encrypt(p: argparse.ArgumentParser) -> None: """``--no-encrypt`` on ``compile``, ``run`` and ``replay``.""" p.add_argument( From 874626d92bb14d5b9890b281e5c4d3fd4b5c7477 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 05:46:55 -0500 Subject: [PATCH 13/37] flow: keyring stays in the keychain extra (install weight); pip install openadapt already includes it --- llms-full.txt | 2 +- packages/flow/CHANGELOG.md | 2 +- packages/flow/docs/phi_at_rest.md | 2 +- packages/flow/pyproject.toml | 4 ---- packages/flow/uv.lock | 2 -- 5 files changed, 3 insertions(+), 9 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index f544f823ab..afe0029ff5 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -2423,7 +2423,7 @@ automation into an independently certified transaction system. plaintext `report.json`. `seal verify`, `inspect report-run`, the receipt page and the quickstart read encrypted runs. The receipt page embeds the report, so beside an encrypted run it is logged as a plaintext copy. -- Core dependencies: `cryptography>=50` (HPKE) and `keyring`. +- Core dependency: `cryptography>=50` (HPKE). The keychain store uses `keyring`, which `pip install openadapt` includes; a bare `openadapt-flow` install needs the `keychain` extra, and otherwise keeps the device key in a 0600 file with a warning. ### Features diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index a389cd2775..a6172fa130 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -48,7 +48,7 @@ plaintext `report.json`. `seal verify`, `inspect report-run`, the receipt page and the quickstart read encrypted runs. The receipt page embeds the report, so beside an encrypted run it is logged as a plaintext copy. -- Core dependencies: `cryptography>=50` (HPKE) and `keyring`. +- Core dependency: `cryptography>=50` (HPKE). The keychain store uses `keyring`, which `pip install openadapt` includes; a bare `openadapt-flow` install needs the `keychain` extra, and otherwise keeps the device key in a 0600 file with a warning. ### Features diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index f9c34f53be..9b7b21d29a 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -153,7 +153,7 @@ then on the viewer key (Touch ID or Windows Hello, on hardware) opens them. | macOS | Secure Enclave runtime key; Secure Enclave viewer key with Touch ID | Interface and test double only; **not built**, pending a check on real hardware | | Windows | TPM key through the Platform Crypto Provider; Windows Hello viewer key | Interface and test double only; **not built**, pending a check on real hardware | | Linux | TPM2 key | Interface only; **not built** | -| Everywhere today | A software P-256 key in the OS keychain through `keyring` (macOS Keychain, Windows Credential Manager with DPAPI, Linux Secret Service), else a 0600 file with a warning | Built; `at-rest status` labels it `software` | +| Everywhere today | A software P-256 key in the OS keychain through `keyring` (macOS Keychain, Windows Credential Manager with DPAPI, Linux Secret Service), else a 0600 file with a warning. `pip install openadapt` includes `keyring`; a bare `openadapt-flow` needs the `keychain` extra | Built; `at-rest status` labels it `software` | A software key protects against a copied disk, backup or ticket attachment, not against code running as you. `require_hardware_device_key: true` in the diff --git a/packages/flow/pyproject.toml b/packages/flow/pyproject.toml index a3bd1c109b..cf51fa61d0 100644 --- a/packages/flow/pyproject.toml +++ b/packages/flow/pyproject.toml @@ -57,10 +57,6 @@ dependencies = [ # 50 brings HPKE (RFC 9180), which wraps each encrypted set's data key # (docs/phi_at_rest.md, openadapt_flow.key_hierarchy). "cryptography>=50.0", - # Encryption at rest is on by default. Where this computer has no secure - # hardware key, its software device key lives in the OS keychain through - # keyring (MIT). Imported lazily, only on the encryption path. - "keyring>=24", # The portable contracts (request, result and receipt models). They live # in openadapt-types, which depends only on pydantic, so a consumer of the # models never installs this package's vision stack; openadapt_flow.contracts diff --git a/packages/flow/uv.lock b/packages/flow/uv.lock index 0ef3151735..54e421da53 100644 --- a/packages/flow/uv.lock +++ b/packages/flow/uv.lock @@ -2645,7 +2645,6 @@ dependencies = [ { name = "cryptography" }, { name = "httpx" }, { name = "idna" }, - { name = "keyring" }, { name = "openadapt-types" }, { name = "pydantic" }, { name = "pyyaml" }, @@ -2865,7 +2864,6 @@ requires-dist = [ { name = "jinja2", marker = "extra == 'service-mlx'", specifier = ">=3.1,<4" }, { name = "jsonschema", marker = "extra == 'agent'", specifier = ">=4.20.0" }, { name = "jsonschema", marker = "extra == 'dev'", specifier = ">=4.21" }, - { name = "keyring", specifier = ">=24" }, { name = "keyring", marker = "extra == 'hosted'", specifier = ">=25" }, { name = "keyring", marker = "extra == 'keychain'", specifier = ">=24" }, { name = "langchain-core", marker = "extra == 'langgraph'", specifier = ">=1.7,<2" }, From d71f29dbc5b4c9b0a501e08f44705d63d04786d3 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 06:36:47 -0500 Subject: [PATCH 14/37] tests: set the synthetic-data opt-out and the file key store session-wide Module-scoped fixtures (an e2e recording compiled once per module) ran before the per-test isolation and now sealed their output by default, under a key the per-test home could not open. --- packages/agent/tests/conftest.py | 6 ++++++ packages/flow/tests/conftest.py | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/packages/agent/tests/conftest.py b/packages/agent/tests/conftest.py index efdc27fe74..531f496c80 100644 --- a/packages/agent/tests/conftest.py +++ b/packages/agent/tests/conftest.py @@ -11,10 +11,16 @@ from __future__ import annotations import json +import os from pathlib import Path import pytest +# Session-wide, before any fixture of any scope: no sealing under a key a +# later test can't open, and never the person's OS keychain. +os.environ["OPENADAPT_FLOW_KEY_STORE"] = "file" +os.environ.setdefault("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data") + from openadapt_agent.runner import RunnerConfig diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index 19c135ca6c..5c49334dbd 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -15,6 +15,16 @@ pytest_plugins = ("tests._orders_portal",) +# Session-wide, before any fixture of any scope: module and session fixtures +# (an e2e recording compiled once per module) must not seal their output +# under a key a later per-test home can't open, and nothing may reach the +# person's OS keychain. The per-test isolation below sets these again. +os.environ["OPENADAPT_FLOW_KEY_STORE"] = "file" +if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") != "1": + os.environ.setdefault( + "OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data" + ) + from tests import lanes # noqa: E402 - needs the sys.path line above from tests._approver_keys import approver # noqa: E402,F401 - shared fixture from tests.repo_tree_guard import ( # noqa: E402 - needs the sys.path line above From e67c1b5ad56744e5eabd92d2ed1575d8fa11f99f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:11:24 -0500 Subject: [PATCH 15/37] cli: route at-rest under the setup task in both task tables --- openadapt/cli_tasks.py | 1 + packages/flow/openadapt_flow/cli_tasks.py | 1 + 2 files changed, 2 insertions(+) diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 61bb8854d7..e2fa8b59f1 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -38,6 +38,7 @@ "approve": "approve", "approve-sanitized": "approve --sanitized", "approver-grant": "setup approver-grant", + "at-rest": "setup at-rest", "attach-seal": "verify attach-seal", "bench": "research flow-bench", "benchmark": "research benchmark", diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index 8d18591838..54171ec046 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -37,6 +37,7 @@ "approve": "approve", "approve-sanitized": "approve --sanitized", "approver-grant": "setup approver-grant", + "at-rest": "setup at-rest", "attach-seal": "verify attach-seal", "bench": "research flow-bench", "benchmark": "research benchmark", From 4d0b967625b16284a562b04eb64f5b02c9c1a27e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 08:26:06 -0500 Subject: [PATCH 16/37] flow: at-rest subcommands refuse abbreviations; session test env set in pytest_configure and restored --- packages/flow/openadapt_flow/cli_at_rest.py | 16 ++++++--- packages/flow/tests/conftest.py | 38 +++++++++++++++------ 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/packages/flow/openadapt_flow/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py index a757c3f345..b02a3615d8 100644 --- a/packages/flow/openadapt_flow/cli_at_rest.py +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -202,16 +202,24 @@ def register(sub: argparse._SubParsersAction) -> None: allow_abbrev=False, ) rsub = p.add_subparsers(dest="at_rest_cmd", required=True) - s = rsub.add_parser("status", help="Where the keys are and who can open new runs") + s = rsub.add_parser( + "status", + help="Where the keys are and who can open new runs", + allow_abbrev=False, + ) s.add_argument("--json", action="store_true") s.set_defaults(func=_cmd_status) - s = rsub.add_parser("recovery", help="The solo recovery key") + s = rsub.add_parser("recovery", help="The solo recovery key", allow_abbrev=False) rec = s.add_subparsers(dest="recovery_cmd", required=True) - c = rec.add_parser("create", help="Make a recovery key; the code is shown once") + c = rec.add_parser( + "create", help="Make a recovery key; the code is shown once", allow_abbrev=False + ) c.add_argument("--replace", action="store_true") c.set_defaults(func=_cmd_recovery_create) s = rsub.add_parser( - "shred", help="Destroy an encrypted set's bucket key; nobody can open it after" + "shred", + help="Destroy an encrypted set's bucket key; nobody can open it after", + allow_abbrev=False, ) s.add_argument("dir", help="The encrypted directory") s.add_argument("--yes", action="store_true", help="Confirm; this can't be undone") diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index 5c49334dbd..5143735ffe 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -15,16 +15,6 @@ pytest_plugins = ("tests._orders_portal",) -# Session-wide, before any fixture of any scope: module and session fixtures -# (an e2e recording compiled once per module) must not seal their output -# under a key a later per-test home can't open, and nothing may reach the -# person's OS keychain. The per-test isolation below sets these again. -os.environ["OPENADAPT_FLOW_KEY_STORE"] = "file" -if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") != "1": - os.environ.setdefault( - "OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data" - ) - from tests import lanes # noqa: E402 - needs the sys.path line above from tests._approver_keys import approver # noqa: E402,F401 - shared fixture from tests.repo_tree_guard import ( # noqa: E402 - needs the sys.path line above @@ -41,6 +31,33 @@ def pytest_collection_modifyitems( lanes.deselect(config, items) +_SESSION_ENV: dict[str, str | None] = {} + + +def _configure_at_rest() -> None: + """Session-wide, before any fixture of any scope: module and session + fixtures (an e2e recording compiled once per module) must not seal their + output under a key a later per-test home can't open, and nothing may reach + the person's OS keychain. The per-test isolation sets these again.""" + + wanted = {"OPENADAPT_FLOW_KEY_STORE": "file"} + if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") != "1": + wanted["OPENADAPT_FLOW_PLAINTEXT_AT_REST"] = os.environ.get( + "OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data" + ) + for name, value in wanted.items(): + _SESSION_ENV[name] = os.environ.get(name) + os.environ[name] = value + + +def pytest_unconfigure(config: pytest.Config) -> None: + for name, value in _SESSION_ENV.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + + def pytest_sessionstart(session: pytest.Session) -> None: """Snapshot the tracked-file status before the first test runs.""" @@ -155,6 +172,7 @@ def pytest_runtest_makereport(item, call): def pytest_configure(config: pytest.Config) -> None: + _configure_at_rest() # A package-local pyproject.toml cuts off ancestor conftest discovery. if not config.pluginmanager.hasplugin("openadapt-headless"): from tests import headless_guard From 74f523b84cf26ddcd9923e5e51046e10f0fdd6ba Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:06:03 -0500 Subject: [PATCH 17/37] flow: address the Codex review of #2423 - An organization shred reports incomplete, exits non-zero and keeps a pending marker until the archive copy is deleted; shred again or at-rest archive finishes it. - A named policy file that is missing refuses; on Windows an organization policy comes only from a machine source. - at-rest archive sends pending key records after an outage, and the next set tries it before refusing at max_unarchived. - record_desktop_capture follows the at-rest policy by default and refuses a capture_dir outside its private staging folder when encrypting. --- packages/flow/docs/phi_at_rest.md | 17 ++- packages/flow/openadapt_flow/__main__.py | 2 +- packages/flow/openadapt_flow/cli_at_rest.py | 41 +++++++ .../flow/openadapt_flow/desktop_record.py | 27 ++++- packages/flow/openadapt_flow/key_hierarchy.py | 106 ++++++++++++++++-- packages/flow/openadapt_flow/sealed_set.py | 25 ++++- packages/flow/tests/test_desktop_record.py | 35 ++++++ packages/flow/tests/test_key_hierarchy.py | 80 +++++++++++++ 8 files changed, 315 insertions(+), 18 deletions(-) diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index 2080b62eac..eff260aa01 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -176,8 +176,10 @@ machine one: 3. Linux: `/etc/openadapt/policy.json`, owned by root and writable by root only; 4. `OPENADAPT_POLICY=`. It may set organization mode only when it is - owned by root (`OPENADAPT_POLICY_TRUST_USER_FILE=1` lifts that for - development, and status says so). + owned by root, so on Windows only Group Policy or the registry can set it + (`OPENADAPT_POLICY_TRUST_USER_FILE=1` lifts that for development, and + status says so). A named file that is missing or unreadable stops the + command; it never falls back to solo mode. ```json { @@ -201,6 +203,12 @@ machine one: organization recipient, or no `key_archive` stops recording and running. - If the archive is unreachable, records stay local as "not yet archived" (`at-rest status` counts them), and new sets stop after `max_unarchived`. + `openadapt-flow at-rest archive` sends them once it is back (and the next + new set tries that first), so recording resumes. +- `records: inline` in organization mode is the choice of recovery over + shredding: every header carries the record, wrapped to the organization's + keys, so the organization can open any copy, but shredding reaches only + copies you can delete, as in solo mode. - Only a local or mounted path (`file://`) is supported as `key_archive` so far; `s3://` and `smb://` refuse. - OpenAdapt Cloud never distributes the organization's key or holds any key. @@ -236,7 +244,10 @@ count. It prints no key material. ## Crypto-shredding `openadapt-flow at-rest shred DIR --yes` destroys the set's bucket key: the -local record is overwritten and deleted, and the archive copy deleted. It +local record is overwritten and deleted, and the archive copy deleted. If the +archive copy can't be deleted (an offline or read-only archive), the command +says the shred is not complete and exits non-zero; running it again, or +`at-rest archive`, finishes it once the archive is reachable. It also drops the record from the header, and deletes the durable checkpoints and other stores' ciphertext inside the set. It returns a shred record (bucket id, time, copies destroyed). The library call is diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index d3fb02bc81..3d539409ab 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -14198,7 +14198,7 @@ def _sealed_input_refusal(args: argparse.Namespace) -> Optional[str]: try: # With no key configured the local key resolves; opening the set # tells "sealed with a key that isn't set" apart before any work. - sealed_set.open_set(root) + _at_rest_cli.precheck_open(root) except sealed_set.SealedSetKeyError as exc: return str(exc) return None diff --git a/packages/flow/openadapt_flow/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py index b02a3615d8..0195e407d4 100644 --- a/packages/flow/openadapt_flow/cli_at_rest.py +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -85,6 +85,21 @@ def _cmd_recovery_create(args: argparse.Namespace) -> int: return 0 +def _cmd_archive(args: argparse.Namespace) -> int: + from openadapt_flow import key_hierarchy as kh + + try: + result = kh.archive_pending() + except kh.KeyHierarchyError as exc: + print(f"at-rest archive: {exc}", file=sys.stderr) + return 2 + print( + f"Archived {result['archived']} key record(s); {result['failed']} could " + f"not reach the archive; {result['shreds_pending']} shred(s) still pending." + ) + return 0 if not (result["failed"] or result["shreds_pending"]) else 1 + + def _cmd_shred(args: argparse.Namespace) -> int: from openadapt_flow import sealed_set @@ -105,6 +120,15 @@ def _cmd_shred(args: argparse.Namespace) -> int: print(f"at-rest shred: {exc}", file=sys.stderr) return 2 copies = ", ".join(record.get("copies_destroyed") or []) or "none tracked" # type: ignore[arg-type] + if record.get("complete") is False: + print( + f"at-rest shred: NOT COMPLETE for {root}: destroyed {copies}, but the " + "organization archive's copy of its key could not be deleted (offline " + "or read-only?). Run this again, or `openadapt-flow at-rest archive`, " + "once the archive is reachable.", + file=sys.stderr, + ) + return 1 print(f"Shredded {root}: bucket key copies destroyed: {copies}.") if record.get("records") == "inline": print( @@ -127,6 +151,7 @@ def _cmd_shred(args: argparse.Namespace) -> int: { "openadapt_flow.cli_at_rest:_cmd_status", "openadapt_flow.cli_at_rest:_cmd_recovery_create", + "openadapt_flow.cli_at_rest:_cmd_archive", } ) @@ -155,6 +180,16 @@ def lacks_key(root: object, kind: str) -> bool: return not (sealed_set.passphrase_for(kind) or crypto.resolve_read_key(None)) +def precheck_open(root: object) -> None: + """Open ``root`` before a command runs, to tell a missing key apart. A + shredded set opens for nobody by design; ``at-rest shred`` retries it.""" + from openadapt_flow import sealed_set + + if sealed_set.read_header(root).get("shredded"): # type: ignore[arg-type] + return + sealed_set.open_set(root) # type: ignore[arg-type] + + def add_no_encrypt(p: argparse.ArgumentParser) -> None: """``--no-encrypt`` on ``compile``, ``run`` and ``replay``.""" p.add_argument( @@ -209,6 +244,12 @@ def register(sub: argparse._SubParsersAction) -> None: ) s.add_argument("--json", action="store_true") s.set_defaults(func=_cmd_status) + s = rsub.add_parser( + "archive", + help="Send key records and pending shreds to the organization archive", + allow_abbrev=False, + ) + s.set_defaults(func=_cmd_archive) s = rsub.add_parser("recovery", help="The solo recovery key", allow_abbrev=False) rec = s.add_subparsers(dest="recovery_cmd", required=True) c = rec.add_parser( diff --git a/packages/flow/openadapt_flow/desktop_record.py b/packages/flow/openadapt_flow/desktop_record.py index 1f4cd06352..034b05fb22 100644 --- a/packages/flow/openadapt_flow/desktop_record.py +++ b/packages/flow/openadapt_flow/desktop_record.py @@ -244,6 +244,11 @@ def _wait_for_stop(stop: Optional[Callable[[], bool]]) -> None: print("[record] If you set --until-cmd, run that check before compile.") +#: ``encryption_key=POLICY``: decide from the at-rest policy, as ``record`` +#: does (encrypted by default; strict mode holds the raw capture back). +POLICY: object = object() + + def record_desktop_capture( out_dir: Path | str, *, @@ -260,7 +265,7 @@ def record_desktop_capture( recorder_factory: Optional[RecorderFactory] = None, convert: Optional[ConvertFn] = None, stop: Optional[Callable[[], bool]] = None, - encryption_key: Optional[str] = None, + encryption_key: Optional[str] | object = POLICY, announce: bool = True, ) -> Path: """Record a live desktop demonstration and convert it to a recording. @@ -338,6 +343,16 @@ def record_desktop_capture( # backstop. _require_capture_extra() + if encryption_key is POLICY: + encryption_key = _policy_key(out_dir) + if encryption_key and capture_dir is not None: + # The raw session would sit outside the private staging folder that + # is deleted after sealing, and stay plaintext. Refuse before recording. + raise SystemExit( + "record: capture_dir can't be combined with an encrypted desktop " + "recording: the raw capture session would be left in plaintext at " + f"{capture_dir}. Nothing was recorded. Omit capture_dir." + ) out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) final_dir = out_dir @@ -385,6 +400,16 @@ def record_desktop_capture( shutil.rmtree(staging, ignore_errors=True) +def _policy_key(out_dir: Path | str) -> Optional[str]: + from openadapt_flow import at_rest, sealed_set + + if at_rest.strict(): + at_rest.unsealed_write("a desktop raw capture session", str(out_dir)) + if not at_rest.seal_new("a desktop recording", out_dir): + return None + return sealed_set.recording_key() + + def _seal_recording(plain: Path, dest: Path, key: str) -> None: """Encrypt a converted recording into ``dest`` (a sealed set).""" from openadapt_flow import sealed_set diff --git a/packages/flow/openadapt_flow/key_hierarchy.py b/packages/flow/openadapt_flow/key_hierarchy.py index bbb82cb6ea..9260203351 100644 --- a/packages/flow/openadapt_flow/key_hierarchy.py +++ b/packages/flow/openadapt_flow/key_hierarchy.py @@ -603,13 +603,18 @@ def load_policy() -> Policy: return Policy() path = Path(configured) if not path.is_file(): - return Policy(source=f"{POLICY_ENV} names no file") + raise KeyHierarchyError( + f"{POLICY_ENV} names {path}, which is not a file. A configured policy " + "that can't be read never falls back to solo mode. Nothing was written." + ) try: raw = json.loads(path.read_text(encoding="utf-8")) except (OSError, ValueError) as exc: raise KeyHierarchyError(f"{path} is not a readable policy file") from exc policy = _parse_policy(raw, f"file: {path}") - if policy.mode == "org" and os.name == "posix" and path.stat().st_uid != 0: + # Ownership proves only on POSIX; elsewhere an org policy must come from + # a machine source (Group Policy, the registry), never a user file. + if policy.mode == "org" and (os.name != "posix" or path.stat().st_uid != 0): if os.environ.get(TRUST_USER_POLICY_ENV) != "1": raise KeyHierarchyError( f"{path} sets organization mode but is not owned by root, so it " @@ -732,6 +737,9 @@ def new_bucket(kind: str, policy: Optional[Policy] = None) -> Bucket: ) if policy.mode == "org" and policy.records == "archive": pending = unarchived_count() + if pending >= policy.max_unarchived: + archive_pending(policy) # the archive may be back + pending = unarchived_count() if pending >= policy.max_unarchived: raise KeyHierarchyError( f"{pending} encrypted sets have not reached the organization key " @@ -929,10 +937,31 @@ def open_bucket(record: dict[str, Any], *, prefer_runtime: bool = True) -> Bucke ) +def _pending_dir() -> Path: + return _home() / "keys" / "shred-pending" + + +def _delete_archive_copy(bucket_id: str, policy: Policy) -> bool: + """Delete the archive's copy; True when it is gone (or never existed).""" + try: + target = _archive_dir(policy) / f"{bucket_id}.json" + if target.is_file(): + target.unlink() + return not target.exists() + except (OSError, KeyHierarchyError): + return False + + def shred(record: dict[str, Any], policy: Optional[Policy] = None) -> dict[str, Any]: """Destroy every tracked copy of a bucket record: the local one - (overwritten, then deleted) and the archive copy. Returns the shred - record, which names the bucket and time and holds no key.""" + (overwritten, then deleted) and the archive copy. + + Returns the shred record (bucket id, time, copies destroyed; no key). + ``complete`` is False while the archive copy could not be deleted (an + offline or read-only archive): a pending marker keeps the bucket id, and + :func:`retry_shred` (``at-rest shred`` again, or ``at-rest archive``) + finishes it. + """ policy = policy or load_policy() bucket_id = str(record["bucket_id"]) removed: list[str] = [] @@ -945,23 +974,76 @@ def shred(record: dict[str, Any], policy: Optional[Policy] = None) -> dict[str, os.fsync(handle.fileno()) path.unlink() removed.append("local") - if policy.records == "archive" and policy.key_archive: - try: - target = _archive_dir(policy) / f"{bucket_id}.json" - if target.is_file(): - target.unlink() - removed.append("archive") - except (OSError, KeyHierarchyError): - pass + complete = True + if policy.records == "archive": + if _delete_archive_copy(bucket_id, policy): + removed.append("archive") + else: + complete = False + _write_private( + _pending_dir() / f"{bucket_id}.json", + json.dumps( + {"bucket_id": bucket_id, "archive": policy.key_archive} + ).encode(), + ) return { "schema": SHRED_SCHEMA, "bucket_id": bucket_id, "shredded_at": time.time(), "copies_destroyed": removed, "records": record.get("records"), + "complete": complete, } +def retry_shred(bucket_id: str, policy: Optional[Policy] = None) -> bool: + """Finish a shred whose archive deletion failed. True when done.""" + policy = policy or load_policy() + marker = _pending_dir() / f"{_record_path(bucket_id).stem}.json" + if not marker.is_file(): + return True + if not _delete_archive_copy(bucket_id, policy): + return False + marker.unlink() + return True + + +def pending_shreds() -> list[str]: + folder = _pending_dir() + return sorted(p.stem for p in folder.glob("*.json")) if folder.is_dir() else [] + + +def archive_pending(policy: Optional[Policy] = None) -> dict[str, int]: + """Archive every local record not yet archived, and finish pending shreds. + Idempotent: run it after the archive comes back.""" + policy = policy or load_policy() + done = failed = 0 + if policy.records != "archive": + return {"archived": 0, "failed": 0, "shreds_pending": len(pending_shreds())} + folder = buckets_dir() + for path in sorted(folder.glob("*.json")) if folder.is_dir() else []: + try: + record = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + failed += 1 + continue + if record.get("archived"): + continue + bucket = Bucket( + str(record["bucket_id"]), + None, + serialization.load_der_public_key(_unb64(record["bucket_pub"])), # type: ignore[arg-type] + record, + ) + if archive(bucket, policy): + done += 1 + else: + failed += 1 + for bucket_id in pending_shreds(): + retry_shred(bucket_id, policy) + return {"archived": done, "failed": failed, "shreds_pending": len(pending_shreds())} + + def describe(policy: Policy) -> dict[str, Any]: device = device_keys(create=False) runtime_label = viewer_label = None diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index dabc7ad397..d651253b4a 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -1530,6 +1530,20 @@ def shred(root: Path | str) -> dict[str, object]: removed: list[str] = [] with mutation_lock(base): header = read_header(base) + previous = header.get("shred_record") + if header.get("shredded") and isinstance(previous, dict): + # Shredded before, with the archive copy still outstanding: retry. + if previous.get("complete") is False: + done = kh.retry_shred(str(previous.get("bucket_id"))) + previous["complete"] = done + if done: + previous["copies_destroyed"] = [ + *previous.get("copies_destroyed", []), # type: ignore[list-item] + "archive", + ] + header["shred_record"] = previous + _replace_header(base, header) + return previous shred_record: dict[str, object] = {"schema": kh.SHRED_SCHEMA} if header.get("version") == ENVELOPE_VERSION and not header.get("shredded"): inline = header.get("bucket_record") @@ -1540,7 +1554,16 @@ def shred(root: Path | str) -> dict[str, object]: ) shred_record = kh.shred(record) except kh.KeyHierarchyError: - shred_record["copies_destroyed"] = [] + # No record on this computer: still delete the archive copy + # (tracked as pending when the archive can't be reached). + key_ref = header.get("key_ref") + bucket_id = ( + key_ref.get("bucket_id") if isinstance(key_ref, dict) else None + ) + if isinstance(bucket_id, str): + shred_record = kh.shred({"bucket_id": bucket_id}) + else: + shred_record["copies_destroyed"] = [] for name in ( "bucket_record", "stanzas", diff --git a/packages/flow/tests/test_desktop_record.py b/packages/flow/tests/test_desktop_record.py index 2e9b4f5399..1d8450be52 100644 --- a/packages/flow/tests/test_desktop_record.py +++ b/packages/flow/tests/test_desktop_record.py @@ -1149,3 +1149,38 @@ def fake_convert(cap_dir: Path, out_dir: Path, *, params=None) -> Path: opened = sealed_set.SealedSet.open(out, key) assert opened.read_bytes("frames/f1.png") == frame assert crypto.is_encrypted((out / "events.jsonl.enc").read_bytes()) + + +def test_direct_desktop_capture_follows_the_encryption_policy( + tmp_path: Path, monkeypatch +) -> None: + """Called directly (not through `record`), the default is the at-rest + policy: encrypted, and a capture_dir outside the staging area refused.""" + from openadapt_flow import sealed_set + + monkeypatch.delenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", raising=False) + log: list = [] + + def fake_convert(cap_dir: Path, out_dir: Path, *, params=None) -> Path: + (Path(out_dir) / "events.jsonl").write_text('{"text": "typed value"}\n') + (Path(out_dir) / "meta.json").write_text("{}") + return Path(out_dir) + + out = record_desktop_capture( + tmp_path / "rec", + recorder_factory=_make(log), + convert=fake_convert, + stop=lambda: True, + announce=False, + ) + assert sealed_set.is_sealed(out) + with pytest.raises(SystemExit, match="capture_dir"): + record_desktop_capture( + tmp_path / "rec2", + capture_dir=tmp_path / "raw", + recorder_factory=_make(log), + convert=fake_convert, + stop=lambda: True, + announce=False, + ) + assert not (tmp_path / "raw").exists() diff --git a/packages/flow/tests/test_key_hierarchy.py b/packages/flow/tests/test_key_hierarchy.py index 25ad34d2d3..c93b085306 100644 --- a/packages/flow/tests/test_key_hierarchy.py +++ b/packages/flow/tests/test_key_hierarchy.py @@ -534,3 +534,83 @@ def test_recovery_key_derivation_matches_rfc_9180() -> None: assert private.private_numbers().private_value.to_bytes(32, "big").hex() == ( "4995788ef4b9d6132b249ce59a77281493eb39af373d236a1fe415cb0c2d7beb" ) + + +# -- review fixes: shred completeness, archive recovery, policy loading ----------- + + +def test_a_shred_with_an_unreachable_archive_is_not_complete_until_retried( + home, tmp_path, monkeypatch +) -> None: + root, _keychain = home + key_file, _org = _p256_policy(tmp_path, monkeypatch) + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + bucket_id = _header(run)["key_ref"]["bucket_id"] + archived = tmp_path / "archive" / f"{bucket_id}.json" + assert archived.is_file() + os.chmod(tmp_path / "archive", 0o500) # the archive goes read-only + try: + record = sealed_set.shred(run) + assert record["complete"] is False and archived.is_file() + assert kh.pending_shreds() == [bucket_id] + assert sealed_set.shred(run)["complete"] is False # still read-only + finally: + os.chmod(tmp_path / "archive", 0o700) + assert sealed_set.shred(run)["complete"] is True + assert not archived.exists() and kh.pending_shreds() == [] + + +def test_the_cli_reports_an_incomplete_shred( + home, tmp_path, monkeypatch, capsys +) -> None: + from openadapt_flow.__main__ import main + + root, _keychain = home + _p256_policy(tmp_path, monkeypatch) + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + os.chmod(tmp_path / "archive", 0o500) + try: + assert main(["at-rest", "shred", str(run), "--yes"]) == 1 + assert "NOT COMPLETE" in capsys.readouterr().err + finally: + os.chmod(tmp_path / "archive", 0o700) + assert main(["at-rest", "shred", str(run), "--yes"]) == 0 + + +def test_after_an_outage_the_pending_records_archive_and_recording_resumes( + home, tmp_path, monkeypatch +) -> None: + blocker = tmp_path / "archive" + blocker.write_text("") # unreachable: a file where the folder should be + _p256_policy(tmp_path, monkeypatch, max_unarchived=1) + _seal(home[0].parent / "a", {"report.json": b"{}"}) + assert kh.unarchived_count() == 1 + with pytest.raises(sealed_set.SealedSetError, match="not reached the organization"): + _seal(home[0].parent / "b", {"report.json": b"{}"}) + blocker.unlink() # the archive is back + assert kh.archive_pending()["archived"] == 1 + assert kh.unarchived_count() == 0 + _seal(home[0].parent / "c", {"report.json": b"{}"}) + assert len(list((tmp_path / "archive").glob("*.json"))) == 2 + + +def test_the_next_set_archives_pending_records_itself( + home, tmp_path, monkeypatch +) -> None: + blocker = tmp_path / "archive" + blocker.write_text("") + _p256_policy(tmp_path, monkeypatch, max_unarchived=1) + _seal(home[0].parent / "a", {"report.json": b"{}"}) + blocker.unlink() + _seal(home[0].parent / "b", {"report.json": b"{}"}) # no refusal + assert kh.unarchived_count() == 0 + + +def test_a_named_policy_file_that_is_missing_refuses( + home, tmp_path, monkeypatch +) -> None: + monkeypatch.setenv(kh.POLICY_ENV, str(tmp_path / "gone.json")) + with pytest.raises(sealed_set.SealedSetError, match="never falls back"): + _seal(home[0].parent / "run", {"report.json": b"{}"}) From 5cd564b955f48293962d63e197572a7b744c7d28 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 17:34:37 -0500 Subject: [PATCH 18/37] flow: bind key records to their archive, authenticate shreds, serialize bucket changes - An archive counts as reachable only with its .openadapt-key-archive marker; Flow never creates the folder, writes records atomically, and records the archive each bucket went to (header and record). Shred and retry use that archive, never the current policy, and a missing marker is never deletion. - Shred authenticates the header with a recipient key before choosing what to destroy, keeps progress in the header and a local pending marker, and says complete only after the store files and the archive copy are gone. - One bucket lock serializes create, archive, close and shred, so a shredded record is never written back. max_unarchived is checked after the new record's own archive attempt (0 means synchronous), and a refused set leaves no record. - Organization mode requires records: archive. A record that arrives in a header opens only with this computer's device keys or a recovery key. - A lost device key no longer hides a valid recovery or organization key. - Machine policy: each platform reads only its own sources, HKLM access denied is an error, and every policy file is checked root-owned and root-writable-only on the descriptor actually read. - Refresh the eligibility connector lock. --- packages/connectors/eligibility/uv.lock | 3 +- packages/flow/openadapt_flow/key_hierarchy.py | 567 +++++++++++++----- packages/flow/openadapt_flow/sealed_set.py | 218 ++++--- packages/flow/tests/test_key_hierarchy.py | 271 ++++++++- 4 files changed, 842 insertions(+), 217 deletions(-) diff --git a/packages/connectors/eligibility/uv.lock b/packages/connectors/eligibility/uv.lock index 17a75ff020..910dd84827 100644 --- a/packages/connectors/eligibility/uv.lock +++ b/packages/connectors/eligibility/uv.lock @@ -506,7 +506,7 @@ requires-dist = [ { name = "cbor2", marker = "extra == 'receipts'", specifier = ">=5.6,<6" }, { name = "claude-agent-sdk", marker = "extra == 'claude-agent-sdk'", specifier = ">=0.2.174,<0.3" }, { name = "click", marker = "extra == 'privacy'", specifier = ">=8.0,<9" }, - { name = "cryptography", specifier = ">=42.0" }, + { name = "cryptography", specifier = ">=50.0" }, { name = "cryptography", marker = "extra == 'agent'", specifier = ">=50.0.0" }, { name = "cwt", marker = "extra == 'dev'", specifier = ">=3.3,<4" }, { name = "cwt", marker = "extra == 'receipts'", specifier = ">=3.3,<4" }, @@ -581,6 +581,7 @@ requires-dist = [ { name = "scikit-image", marker = "extra == 'dev'", specifier = ">=0.22" }, { name = "sigstore", marker = "python_full_version >= '3.11' and extra == 'dev'", specifier = ">=4.5,<5" }, { name = "sigstore", marker = "python_full_version >= '3.11' and extra == 'registry'", specifier = ">=4.5,<5" }, + { name = "tink", marker = "extra == 'dev'", specifier = ">=1.16,<2" }, { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0" }, { name = "transformers", marker = "extra == 'service-mlx'", specifier = ">=5.14,<5.18" }, { name = "uiautomation", marker = "sys_platform == 'win32' and extra == 'dev'", specifier = ">=2.0.20" }, diff --git a/packages/flow/openadapt_flow/key_hierarchy.py b/packages/flow/openadapt_flow/key_hierarchy.py index 9260203351..ab85945cee 100644 --- a/packages/flow/openadapt_flow/key_hierarchy.py +++ b/packages/flow/openadapt_flow/key_hierarchy.py @@ -48,10 +48,12 @@ import secrets import stat import sys +import threading import time +from contextlib import contextmanager from dataclasses import dataclass, field from pathlib import Path -from typing import Any, Final, Optional +from typing import Any, Final, Iterator, Optional from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa @@ -79,12 +81,27 @@ ROLE_BREAK_GLASS: Final[str] = "break-glass" ROLE_RECOVERY: Final[str] = "recovery" +def _platform_policy_sources(platform: str) -> list[str]: + """The machine-scope policy sources this platform trusts. Each platform + reads only its own administrator-controlled sources: a macOS managed + preference path means nothing on Windows, where a user could create it.""" + if platform == "darwin": + return [ + "/Library/Managed Preferences/ai.openadapt.policy.plist", + "/etc/openadapt/policy.json", + ] + if platform == "win32": + return ["HKLM\\SOFTWARE\\Policies\\OpenAdapt"] + return ["/etc/openadapt/policy.json"] + + #: Machine-scope policy locations, first match wins. Tests replace this. -MACHINE_POLICY_SOURCES: list[str] = [ - "/Library/Managed Preferences/ai.openadapt.policy.plist", - "HKLM\\SOFTWARE\\Policies\\OpenAdapt", - "/etc/openadapt/policy.json", -] +MACHINE_POLICY_SOURCES: list[str] = _platform_policy_sources(sys.platform) +#: The file an administrator puts at the root of ``key_archive``. Flow +#: treats the archive as reachable only when it is there, so an unmounted +#: share (an empty local folder at the mount point) never counts as the +#: archive, and a record missing from it never counts as deleted. +ARCHIVE_MARKER: Final[str] = ".openadapt-key-archive" _SUITE_LABEL: Final[bytes] = b"openadapt.ai/bucket/v1/wrap\0" _RECOVERY_SALT: Final[bytes] = b"openadapt.ai/recovery-key/v1" @@ -553,42 +570,79 @@ def active_org(self) -> list[Recipient]: ] +def _read_registry(subkey: str) -> Optional[dict]: # pragma: no cover - Windows + """The ``Policy`` value under ``HKLM\\``. None only when the key + does not exist; access denied or a key without the value is an error, so + a policy the account can't read never falls back to solo mode.""" + import winreg + + try: + handle = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey) + except FileNotFoundError: + return None + with handle: + value, _ = winreg.QueryValueEx(handle, "Policy") + return json.loads(value) + + +def _read_trusted_file(path: Path) -> tuple[bytes, os.stat_result]: + """Read ``path`` once and return its bytes with the status of the file + actually read (not of whatever the path names a moment later).""" + flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(path, flags) + try: + info = os.fstat(fd) + chunks = [] + while True: + chunk = os.read(fd, 1 << 16) + if not chunk: + break + chunks.append(chunk) + finally: + os.close(fd) + return b"".join(chunks), info + + +def _root_only(info: os.stat_result) -> bool: + """Owned by root and writable by nobody else (POSIX).""" + return info.st_uid == 0 and not info.st_mode & (stat.S_IWGRP | stat.S_IWOTH) + + def _read_machine_source(source: str) -> Optional[dict]: if source.startswith("HKLM\\"): if sys.platform != "win32": return None - try: # pragma: no cover - Windows only - import winreg - - with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, source[5:]) as handle: - value, _ = winreg.QueryValueEx(handle, "Policy") - return json.loads(value) - except OSError: # pragma: no cover - return None + return _read_registry(source[5:]) # pragma: no cover - Windows only path = Path(source) if not path.is_file(): return None + if os.name != "posix": + # A file path is a machine policy only where ownership can be checked. + raise KeyHierarchyError( + f"{path} can't be checked for administrator ownership on this " + "platform, so it is not trusted as a machine policy. Nothing was " + "written." + ) + raw, info = _read_trusted_file(path) + if not _root_only(info): + raise KeyHierarchyError( + f"{path} must be owned by root and writable by root only; it is " + "not, so the machine policy can't be trusted. Nothing was written." + ) if path.suffix == ".plist": import plistlib - data = plistlib.loads(path.read_bytes()) + data = plistlib.loads(raw) body = data.get("Policy", data) if isinstance(data, dict) else None return json.loads(body) if isinstance(body, (str, bytes)) else body - if os.name == "posix": - info = path.stat() - if info.st_uid != 0 or info.st_mode & (stat.S_IWGRP | stat.S_IWOTH): - raise KeyHierarchyError( - f"{path} must be owned by root and writable by root only; it is " - "not, so the machine policy can't be trusted. Nothing was written." - ) - return json.loads(path.read_text(encoding="utf-8")) + return json.loads(raw.decode("utf-8")) def load_policy() -> Policy: """The first policy found: machine sources first, then ``OPENADAPT_POLICY``. A user-writable file never overrides a machine one, and can set - organization mode only when it is root-owned (or the trust variable is - set, for development).""" + organization mode only when it is owned by root and writable by root + only (or the trust variable is set, for development).""" for source in MACHINE_POLICY_SOURCES: try: raw = _read_machine_source(source) @@ -608,23 +662,35 @@ def load_policy() -> Policy: "that can't be read never falls back to solo mode. Nothing was written." ) try: - raw = json.loads(path.read_text(encoding="utf-8")) + data, info = _read_trusted_file(path) + raw = json.loads(data.decode("utf-8")) except (OSError, ValueError) as exc: raise KeyHierarchyError(f"{path} is not a readable policy file") from exc policy = _parse_policy(raw, f"file: {path}") # Ownership proves only on POSIX; elsewhere an org policy must come from - # a machine source (Group Policy, the registry), never a user file. - if policy.mode == "org" and (os.name != "posix" or path.stat().st_uid != 0): + # a machine source (Group Policy, the registry), never a user file. The + # check is on the file actually read, and a root-owned file that others + # can write is no better than a user's. + if policy.mode == "org" and (os.name != "posix" or not _root_only(info)): if os.environ.get(TRUST_USER_POLICY_ENV) != "1": raise KeyHierarchyError( - f"{path} sets organization mode but is not owned by root, so it " - "can't be trusted (a user could swap the organization's key). " - "Install it as a machine policy. Nothing was written." + f"{path} sets organization mode but is not owned by root and " + "writable by root only, so it can't be trusted (a user could " + "swap the organization's key). Install it as a machine policy. " + "Nothing was written." ) policy.source += " (user-owned, trusted for development)" return policy +def _max_unarchived(value: Any, source: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise KeyHierarchyError( + f"{source}: max_unarchived must be a whole number, 0 or more" + ) + return value + + def _parse_policy(raw: Any, source: str) -> Policy: if not isinstance(raw, dict) or raw.get("schema") != POLICY_SCHEMA: raise KeyHierarchyError(f"{source} is not an {POLICY_SCHEMA} policy") @@ -634,6 +700,15 @@ def _parse_policy(raw: Any, source: str) -> Policy: records = raw.get("records", "archive" if mode == "org" else "inline") if records not in ("archive", "inline"): raise KeyHierarchyError(f"{source}: records must be 'archive' or 'inline'") + if mode == "org" and records != "archive": + # Organization mode promises that shredding reaches every tracked + # copy, and an organization key never opens a record a header + # supplies (anyone who knows its public key could forge one). + raise KeyHierarchyError( + f"{source}: organization mode keeps key records in the archive " + "(records: archive); records: inline is solo mode only. Recording " + "and running stop until it does." + ) entries = raw.get("recipients", []) if not isinstance(entries, list): raise KeyHierarchyError(f"{source}: recipients must be a list") @@ -643,7 +718,7 @@ def _parse_policy(raw: Any, source: str) -> Policy: recipients=[Recipient.from_policy(entry) for entry in entries], key_archive=raw.get("key_archive"), require_hardware_device_key=bool(raw.get("require_hardware_device_key", False)), - max_unarchived=int(raw.get("max_unarchived", 50)), + max_unarchived=_max_unarchived(raw.get("max_unarchived", 50), source), source=source, org=raw.get("org"), ) @@ -717,12 +792,46 @@ def _stanza(recipient: Recipient, bucket_id: str, secret: bytes) -> dict[str, st } +_BUCKET_THREAD_LOCK = threading.RLock() +_bucket_depth = threading.local() + + +@contextmanager +def bucket_lock() -> Iterator[None]: + """Serialize every change to bucket records (create, archive, close, + shred) across threads and processes, so an archive worker can't write + back a record a shred just destroyed, and two writers can't both take + the last free slot under ``max_unarchived``. Re-entrant in a thread.""" + with _BUCKET_THREAD_LOCK: + depth = getattr(_bucket_depth, "n", 0) + if depth: + _bucket_depth.n = depth + 1 + try: + yield + finally: + _bucket_depth.n = depth + else: + from openadapt_flow import at_rest + from openadapt_flow.sealed_maintenance import mutation_lock + + at_rest._private_dir(buckets_dir()) + _bucket_depth.n = 1 + try: + with mutation_lock(buckets_dir()): + yield + finally: + _bucket_depth.n = 0 + + def new_bucket(kind: str, policy: Optional[Policy] = None) -> Bucket: """A fresh bucket for one sealed set, wrapped to the policy's recipients. Organization mode refuses without its active organization recipient and - archive (fail closed), and when ``max_unarchived`` records have not - reached the archive yet. + archive (fail closed). Its record is stored locally and sent to the + archive at once; when the archive can't take it and more than + ``max_unarchived`` records would then be waiting (0 means every record + must reach the archive first), the record is destroyed again and the set + is refused before anything is written. """ policy = policy or load_policy() device = device_keys(create=True) @@ -735,18 +844,6 @@ def new_bucket(kind: str, policy: Optional[Policy] = None) -> Bucket: "the policy requires a hardware device key, and this computer has " "only a software key. Nothing was written." ) - if policy.mode == "org" and policy.records == "archive": - pending = unarchived_count() - if pending >= policy.max_unarchived: - archive_pending(policy) # the archive may be back - pending = unarchived_count() - if pending >= policy.max_unarchived: - raise KeyHierarchyError( - f"{pending} encrypted sets have not reached the organization key " - f"archive ({policy.key_archive}); the policy allows " - f"{policy.max_unarchived}. Reconnect so they archive. Nothing was " - "written." - ) private = ec.generate_private_key(ec.SECP256R1()) bucket_id = secrets.token_hex(16) secret = _scalar(private) @@ -766,7 +863,7 @@ def add(recipient: Recipient) -> None: recovery = recovery_recipient() if recovery is not None: add(recovery) - record = { + record: dict[str, Any] = { "schema": BUCKET_SCHEMA, "bucket_id": bucket_id, "kind": kind, @@ -779,8 +876,30 @@ def add(recipient: Recipient) -> None: "stanzas": [_stanza(r, bucket_id, secret) for r in recipients], } bucket = Bucket(bucket_id, private, private.public_key(), record) - if policy.records == "archive": + if policy.records != "archive": + return bucket + # The archive this record goes to is fixed now: archiving and shredding + # later use it, whatever the policy says by then. + record["key_archive"] = policy.key_archive + with bucket_lock(): _store_local(record) + if _archive_locked(bucket): + if unarchived_count(): + _archive_pending_locked() # the archive is back: send the rest + return bucket + waiting = unarchived_count() + if waiting > policy.max_unarchived: + _archive_pending_locked() # the archive may be back + waiting = unarchived_count() + if waiting > policy.max_unarchived: + _destroy_local(bucket_id) + raise KeyHierarchyError( + f"{waiting - 1} encrypted sets have not reached the organization " + f"key archive ({policy.key_archive}), and the policy allows " + f"{policy.max_unarchived} waiting. Reconnect the archive (it " + f"needs its {ARCHIVE_MARKER} file) and run `openadapt-flow " + "at-rest archive`. Nothing was written." + ) return bucket @@ -796,47 +915,127 @@ def _store_local(record: dict[str, Any]) -> None: ) -def _archive_dir(policy: Policy) -> Path: - target = policy.key_archive or "" +def _read_local(bucket_id: str) -> Optional[dict[str, Any]]: + path = _record_path(bucket_id) + if not path.is_file(): + return None + data = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(data, dict) or data.get("bucket_id") != bucket_id: + raise KeyHierarchyError(f"the local key record {path} is malformed") + return data + + +def _destroy_local(bucket_id: str) -> bool: + """Overwrite, then delete, this computer's record. True if there was one.""" + path = _record_path(bucket_id) + if not path.is_file(): + return False + size = path.stat().st_size + with open(path, "r+b") as handle: + handle.write(b"\0" * size) + handle.flush() + os.fsync(handle.fileno()) + path.unlink() + return True + + +def _archive_root(location: Optional[str]) -> Path: + """The archive folder, only when it is reachable: it must already exist + and hold :data:`ARCHIVE_MARKER`. Flow never creates it, so a missing + mount is never mistaken for an empty archive.""" + target = location or "" if target.startswith("file://"): target = target[len("file://") :] + if not target: + raise KeyHierarchyError("no key_archive is recorded for this bucket") if "://" in target: raise KeyHierarchyError( - f"key_archive {policy.key_archive}: only a local or mounted path " + f"key_archive {location}: only a local or mounted path " "(file://) is supported yet; s3:// and smb:// are not built." ) - return Path(target) + root = Path(target) + if not (root / ARCHIVE_MARKER).is_file(): + raise KeyHierarchyError( + f"the key archive {location} is not reachable (no {ARCHIVE_MARKER} " + "file at its root: unmounted or not set up)" + ) + return root -def archive(bucket: Bucket, policy: Optional[Policy] = None) -> bool: - """Copy the bucket record to the organization's archive. The runtime - stanza is never archived. Returns False (and keeps the record local, as - unarchived) when the archive is unreachable.""" - policy = policy or load_policy() - if policy.records != "archive": +def _intended_archive(record: dict[str, Any], policy: Optional[Policy]) -> Optional[str]: + location = record.get("key_archive") + if isinstance(location, str) and location: + return location + return policy.key_archive if policy is not None else None + + +def _archive_locked(bucket: Bucket, policy: Optional[Policy] = None) -> bool: + on_disk = _read_local(bucket.bucket_id) + if on_disk is None: + # Shredded (or never stored): never write a destroyed key back. return False - copy = dict(bucket.record) + record = dict(bucket.record) + location = _intended_archive(on_disk, policy) or _intended_archive(record, None) + copy = dict(record) + copy["key_archive"] = location + copy["archived"] = True copy["stanzas"] = [s for s in copy["stanzas"] if s["role"] != ROLE_RUNTIME] try: - folder = _archive_dir(policy) - folder.mkdir(parents=True, exist_ok=True) - target = folder / f"{bucket.bucket_id}.json" - target.write_text(json.dumps(copy, indent=2), encoding="utf-8") - except OSError: + root = _archive_root(location) + target = root / f"{bucket.bucket_id}.json" + tmp = root / f".{bucket.bucket_id}.{secrets.token_hex(4)}.tmp" + try: + with open(tmp, "xb") as handle: + handle.write(json.dumps(copy, indent=2).encode("utf-8")) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp, target) # never a truncated archive record + finally: + if os.path.lexists(tmp): + os.unlink(tmp) + except (OSError, KeyHierarchyError): return False - bucket.record["archived"] = True + record["key_archive"] = location + record["archived"] = True + bucket.record.update(record) _store_local(bucket.record) return True +def archive(bucket: Bucket, policy: Optional[Policy] = None) -> bool: + """Copy the bucket record to the archive recorded for it (atomically). + The runtime stanza is never archived. Returns False (and keeps the + record local, as unarchived) when that archive is unreachable, and when + the record was shredded meanwhile (it is never written back).""" + if bucket.record.get("records") != "archive": + return False + with bucket_lock(): + return _archive_locked(bucket, policy) + + def close(bucket: Bucket) -> None: """The set is written: drop the runtime stanza, so only the viewer, - organization or recovery key opens it from now on.""" + organization or recovery key opens it from now on. An archive-mode + record that was shredded while the set was written is not brought back: + that refuses.""" bucket.record["stanzas"] = [ s for s in bucket.record["stanzas"] if s["role"] != ROLE_RUNTIME ] - if bucket.record.get("records") == "archive": + if bucket.record.get("records") != "archive": + return + with bucket_lock(): + on_disk = _read_local(bucket.bucket_id) + if on_disk is None: + raise KeyHierarchyError( + "this set's key record was shredded while the set was being " + "written; it is not written back" + ) + bucket.record["archived"] = bool(on_disk.get("archived")) + if on_disk.get("key_archive"): + bucket.record["key_archive"] = on_disk["key_archive"] _store_local(bucket.record) + if not bucket.record["archived"]: + _archive_locked(bucket) def unarchived_count() -> int: @@ -849,28 +1048,43 @@ def unarchived_count() -> int: if not json.loads(path.read_text(encoding="utf-8")).get("archived"): count += 1 except (OSError, ValueError): - continue + count += 1 # unreadable: count it as waiting, never as archived return count def find_record( key_ref: dict[str, Any], inline: Optional[dict[str, Any]] ) -> dict[str, Any]: + """This computer's record for the bucket, else the one the header + carries. A record from a header is opened only by this computer's + device keys or a recovery key (:func:`open_bucket`).""" bucket_id = str(key_ref.get("bucket_id")) + local = _read_local(bucket_id) + if local is not None: + return local if inline is not None: return inline - path = _record_path(bucket_id) - if path.is_file(): - return json.loads(path.read_text(encoding="utf-8")) raise NoRecipientKey( f"this computer has no key record for bucket {bucket_id}. Open it as the " - "organization (its archive copy and key), or it was shredded." + "organization (copy its archive record into " + f"{buckets_dir()} and set {ORG_KEY_FILE_ENV}), or it was shredded." ) -def _candidates() -> list[Unwrapper]: +def _candidates( + *, from_header: bool +) -> tuple[list[Unwrapper], Optional[BaseException]]: + """The keys this computer can try, and the error reading the device key + raised (kept, so a lost keychain entry doesn't hide a valid recovery or + organization key). An organization key never opens a record a header + supplied: anyone who knows the organization's public key could have + made it.""" out: list[Unwrapper] = [] - device = device_keys(create=False) + deferred: Optional[BaseException] = None + try: + device = device_keys(create=False) + except (KeyHierarchyError, RuntimeError) as exc: + device, deferred = None, exc if device is not None: runtime, viewer = device out.append(runtime) @@ -880,7 +1094,7 @@ def _candidates() -> list[Unwrapper]: if code: out.append(recovery_code_to_key(code)) org_file = os.environ.get(ORG_KEY_FILE_ENV) - if org_file: + if org_file and not from_header: try: private = serialization.load_pem_private_key( Path(org_file).read_bytes(), password=None @@ -890,11 +1104,23 @@ def _candidates() -> list[Unwrapper]: f"{ORG_KEY_FILE_ENV}: {org_file} can't be read" ) from exc out.append(SoftwareKey(private, ROLE_ORG, label="organization (file)")) - return out + return out, deferred + + +_HEADER_ROLES: Final[frozenset[str]] = frozenset( + {ROLE_RUNTIME, ROLE_VIEWER, ROLE_DEVICE_SOFTWARE, ROLE_RECOVERY} +) + +def open_bucket( + record: dict[str, Any], *, prefer_runtime: bool = True, from_header: bool = False +) -> Bucket: + """Unwrap a bucket's private half with the first key this computer holds. -def open_bucket(record: dict[str, Any], *, prefer_runtime: bool = True) -> Bucket: - """Unwrap a bucket's private half with the first key this computer holds.""" + ``from_header``: the record came from the set's own header, not from + this computer's key store. Only a device key or a recovery key may open + it then, through a stanza of that role. + """ if record.get("schema") != BUCKET_SCHEMA: raise KeyHierarchyError("not a bucket record") if record.get("shredded"): @@ -906,7 +1132,8 @@ def open_bucket(record: dict[str, Any], *, prefer_runtime: bool = True) -> Bucke "the bucket record's public key does not match its fingerprint" ) stanzas = {s.get("fpr"): s for s in record.get("stanzas") or []} - for key in _candidates(): + keys, deferred = _candidates(from_header=from_header) + for key in keys: try: fpr = key.fpr except KeyHierarchyError: @@ -914,6 +1141,8 @@ def open_bucket(record: dict[str, Any], *, prefer_runtime: bool = True) -> Bucke stanza = stanzas.get(fpr) if stanza is None: continue + if from_header and str(stanza.get("role")) not in _HEADER_ROLES: + continue info = _stanza_info(bucket_id, str(stanza["role"]), fpr) try: secret = key.unwrap(_unb64(stanza["ct"]), info) @@ -929,6 +1158,8 @@ def open_bucket(record: dict[str, Any], *, prefer_runtime: bool = True) -> Bucke "the unwrapped bucket key does not match the record" ) return Bucket(bucket_id, private, private.public_key(), record) # type: ignore[arg-type] + if deferred is not None: + raise deferred raise NoRecipientKey( "no key on this computer opens this encrypted set: it is wrapped for " + ", ".join(f"{s.get('role')} {s.get('fpr')}" for s in stanzas.values()) @@ -941,71 +1172,105 @@ def _pending_dir() -> Path: return _home() / "keys" / "shred-pending" -def _delete_archive_copy(bucket_id: str, policy: Policy) -> bool: - """Delete the archive's copy; True when it is gone (or never existed).""" +def _pending_path(bucket_id: str) -> Path: + return _pending_dir() / f"{_record_path(bucket_id).stem}.json" + + +def _delete_archive_copy(bucket_id: str, location: Optional[str]) -> bool: + """Delete the archive's copy. True only when the archive is reachable + (its marker is there) and the copy is gone from it.""" try: - target = _archive_dir(policy) / f"{bucket_id}.json" + target = _archive_root(location) / f"{bucket_id}.json" if target.is_file(): target.unlink() - return not target.exists() + return not os.path.lexists(target) except (OSError, KeyHierarchyError): return False -def shred(record: dict[str, Any], policy: Optional[Policy] = None) -> dict[str, Any]: +def shred( + bucket_id: str, + *, + records: Optional[str], + key_archive: Optional[str], +) -> dict[str, Any]: """Destroy every tracked copy of a bucket record: the local one - (overwritten, then deleted) and the archive copy. + (overwritten, then deleted) and the copy in the archive it was sent to. + + ``records`` and ``key_archive`` come from the set's authenticated header + (the local record's own archive wins). The current policy plays no part: + a later switch to another archive or to solo mode must not leave the + original archive's copy behind. Returns the shred record (bucket id, time, copies destroyed; no key). ``complete`` is False while the archive copy could not be deleted (an - offline or read-only archive): a pending marker keeps the bucket id, and + offline, unmounted or read-only archive): a pending marker in this + computer's key store keeps the bucket id and that archive, and :func:`retry_shred` (``at-rest shred`` again, or ``at-rest archive``) finishes it. """ - policy = policy or load_policy() - bucket_id = str(record["bucket_id"]) + _record_path(bucket_id) # validates the id removed: list[str] = [] - path = _record_path(bucket_id) - if path.is_file(): - size = path.stat().st_size - with open(path, "r+b") as handle: - handle.write(b"\0" * size) - handle.flush() - os.fsync(handle.fileno()) - path.unlink() - removed.append("local") - complete = True - if policy.records == "archive": - if _delete_archive_copy(bucket_id, policy): - removed.append("archive") - else: - complete = False - _write_private( - _pending_dir() / f"{bucket_id}.json", - json.dumps( - {"bucket_id": bucket_id, "archive": policy.key_archive} - ).encode(), - ) + with bucket_lock(): + local = _read_local(bucket_id) + if local is not None: + records = str(local.get("records") or records) + key_archive = _intended_archive(local, None) or key_archive + if _destroy_local(bucket_id): + removed.append("local") + complete = True + if records == "archive": + if key_archive and _delete_archive_copy(bucket_id, key_archive): + removed.append("archive") + else: + complete = False + _write_private( + _pending_path(bucket_id), + json.dumps( + {"bucket_id": bucket_id, "key_archive": key_archive} + ).encode(), + ) return { "schema": SHRED_SCHEMA, "bucket_id": bucket_id, "shredded_at": time.time(), "copies_destroyed": removed, - "records": record.get("records"), + "records": records, + "key_archive": key_archive, "complete": complete, } -def retry_shred(bucket_id: str, policy: Optional[Policy] = None) -> bool: - """Finish a shred whose archive deletion failed. True when done.""" - policy = policy or load_policy() - marker = _pending_dir() / f"{_record_path(bucket_id).stem}.json" - if not marker.is_file(): - return True - if not _delete_archive_copy(bucket_id, policy): - return False - marker.unlink() - return True +def retry_shred(bucket_id: str) -> bool: + """Finish a shred whose archive deletion failed, in the archive its + pending marker names. True when that copy is gone. The marker stays + until :func:`clear_pending_shred`, so a crash before the caller records + completion is retried rather than forgotten. Without a marker on this + computer nothing is deleted and the answer is False: completion is never + assumed.""" + with bucket_lock(): + marker = _pending_path(bucket_id) + if not marker.is_file(): + return False + try: + data = json.loads(marker.read_text(encoding="utf-8")) + except (OSError, ValueError): + return False + location = data.get("key_archive") if isinstance(data, dict) else None + if not isinstance(location, str) or not location: + return False + return _delete_archive_copy(bucket_id, location) + + +def clear_pending_shred(bucket_id: str) -> None: + with bucket_lock(): + marker = _pending_path(bucket_id) + if marker.is_file(): + marker.unlink() + + +def has_pending_shred(bucket_id: str) -> bool: + return _pending_path(bucket_id).is_file() def pending_shreds() -> list[str]: @@ -1013,35 +1278,55 @@ def pending_shreds() -> list[str]: return sorted(p.stem for p in folder.glob("*.json")) if folder.is_dir() else [] -def archive_pending(policy: Optional[Policy] = None) -> dict[str, int]: - """Archive every local record not yet archived, and finish pending shreds. - Idempotent: run it after the archive comes back.""" - policy = policy or load_policy() +def _archive_pending_locked() -> tuple[int, int]: done = failed = 0 - if policy.records != "archive": - return {"archived": 0, "failed": 0, "shreds_pending": len(pending_shreds())} folder = buckets_dir() for path in sorted(folder.glob("*.json")) if folder.is_dir() else []: try: record = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): + if record.get("archived") or record.get("records") != "archive": + continue + bucket = Bucket( + str(record["bucket_id"]), + None, + serialization.load_der_public_key(_unb64(record["bucket_pub"])), # type: ignore[arg-type] + record, + ) + except (OSError, ValueError, KeyError, KeyHierarchyError): failed += 1 continue - if record.get("archived"): - continue - bucket = Bucket( - str(record["bucket_id"]), - None, - serialization.load_der_public_key(_unb64(record["bucket_pub"])), # type: ignore[arg-type] - record, - ) - if archive(bucket, policy): + if _archive_locked(bucket): done += 1 else: failed += 1 - for bucket_id in pending_shreds(): - retry_shred(bucket_id, policy) - return {"archived": done, "failed": failed, "shreds_pending": len(pending_shreds())} + return done, failed + + +def archive_pending(policy: Optional[Policy] = None) -> dict[str, int]: + """Archive every local record not yet archived (each to the archive + recorded for it), and finish pending shreds. Idempotent: run it after + the archive comes back. A shred finished here is complete in the key + store; ``at-rest shred DIR`` again also marks the set's header.""" + with bucket_lock(): + done, failed = _archive_pending_locked() + for bucket_id in pending_shreds(): + retry_shred(bucket_id) + still = [b for b in pending_shreds() if not _archive_copy_gone(b)] + return {"archived": done, "failed": failed, "shreds_pending": len(still)} + + +def _archive_copy_gone(bucket_id: str) -> bool: + try: + data = json.loads(_pending_path(bucket_id).read_text(encoding="utf-8")) + except (OSError, ValueError): + return False + location = data.get("key_archive") if isinstance(data, dict) else None + if not isinstance(location, str) or not location: + return False + try: + return not os.path.lexists(_archive_root(location) / f"{bucket_id}.json") + except KeyHierarchyError: + return False def describe(policy: Policy) -> dict[str, Any]: @@ -1076,7 +1361,11 @@ def describe(policy: Policy) -> dict[str, Any]: "Policy", "Recipient", "SoftwareKey", + "ARCHIVE_MARKER", "archive", + "archive_pending", + "bucket_lock", + "clear_pending_shred", "close", "describe", "device_keys", diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index d651253b4a..d684a0d0bd 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -519,6 +519,7 @@ def _wrapping_aad(header: dict[str, object]) -> bytes: _V3_PAYLOAD: Final[bytes] = b"openadapt.ai/sealed-set/v3/payload\0" _V3_HEADER: Final[bytes] = b"openadapt.ai/sealed-set/v3/header" _V3_BUCKET_MAC: Final[bytes] = b"openadapt.ai/sealed-set/v3/bucket-mac" +_V3_STORE: Final[bytes] = b"openadapt.ai/sealed-set/v3/store\0" PAYLOAD: Final[str] = "tink-aes256-gcm-hkdf-1mb" _MAC_EXCLUDED: Final[frozenset[str]] = frozenset({"mac", "bucket_mac", "set_digest"}) @@ -553,8 +554,17 @@ class V3Key: def __init__(self, dek: bytes, set_id: str, bucket: object = None) -> None: self._payload = _hkdf(dek, _V3_PAYLOAD + set_id.encode()) self._header_key = _hkdf(dek, _V3_HEADER) + self._store = _hkdf(dek, _V3_STORE + set_id.encode()) self.bucket = bucket + @property + def store_passphrase(self) -> str: + """The passphrase of the stores that keep their own containers inside + this set (durable checkpoints, approvals, transition evidence). It + comes from the set's data key, so shredding the bucket makes those + containers unreadable too, in backups as well.""" + return base64.urlsafe_b64encode(self._store).decode("ascii") + def seal(self, plaintext: bytes, *, aad: bytes) -> bytes: from openadapt_flow import stream_aead @@ -637,11 +647,14 @@ def _open_v3(header: dict[str, object]) -> V3Key: ): raise SealedSetError("sealed-set version 3 header is malformed") inline = header.get("bucket_record") + inline = inline if isinstance(inline, dict) else None try: - record = kh.find_record(key_ref, inline if isinstance(inline, dict) else None) + record = kh.find_record(key_ref, inline) if record.get("bucket_id") != key_ref.get("bucket_id"): raise SealedSetError("the bucket record belongs to another set") - bucket = kh.open_bucket(record) + # A record the header supplies proves nothing about who wrote the + # set: only this computer's device keys or a recovery key open it. + bucket = kh.open_bucket(record, from_header=record is inline) except kh.NoRecipientKey as exc: raise SealedSetKeyError(str(exc)) from exc except kh.KeyHierarchyError as exc: @@ -927,8 +940,6 @@ def _new_v3( if _explicit_passphrase(passphrase) and policy.mode != "org": return None bucket = kh.new_bucket(kind, policy) - if policy.records == "archive": - kh.archive(bucket, policy) except kh.KeyHierarchyError as exc: raise SealedSetError(f"Not writing an encrypted {kind}: {exc}") from exc set_id = secrets.token_hex(16) @@ -941,7 +952,12 @@ def _new_v3( "cipher": "AES-256-GCM", "payload": PAYLOAD, "key_ref": bucket.key_ref(), + # Authenticated by the header MACs: shredding deletes the archive + # copy from this archive, whatever the policy says by then. + "records": policy.records, } + if policy.records == "archive": + header["key_archive"] = policy.key_archive header["stanzas"] = [ { "type": kh.STANZA_TYPE, @@ -1197,11 +1213,12 @@ def _close_bucket(self) -> None: bucket = getattr(self._key, "bucket", None) if bucket is None: return - kh.close(bucket) + try: + kh.close(bucket) + except kh.KeyHierarchyError as exc: + raise SealedSetError(f"refusing to seal {self.root}: {exc}") from exc if "bucket_record" in self._header: self._header["bucket_record"] = bucket.record - elif bucket.record.get("records") == "archive": - kh.archive(bucket) self._new = False @@ -1512,92 +1529,141 @@ def key_record_of(root: Path | str) -> Optional[dict[str, object]]: return None +_SHRED_HEADER_FIELDS: Final[tuple[str, ...]] = ( + "bucket_record", + "stanzas", + "wrapped_key", + "salt", + "kdf", + "kdf_n", + "kdf_r", + "kdf_p", + "mac", + "bucket_mac", +) + + +def _delete_store_files(base: Path) -> list[str]: + """Delete the other stores' ciphertext inside a shredded set (durable + checkpoints, approvals). Idempotent; the set's own files stay, as + ciphertext nobody can open.""" + removed: list[str] = [] + for rel in _disk_files(base): + path = base / rel + try: + data = path.read_bytes() + except OSError: + continue + if data[: len(crypto.SET_FILE_MAGIC)] in ( + crypto.SET_FILE_MAGIC, + crypto.SET3_FILE_MAGIC, + ): + continue # the set's own ciphertext, now unopenable + if crypto.is_encrypted(data): + path.unlink() + removed.append(rel) + return removed + + +def _finish_shred(base: Path, header: dict[str, object]) -> dict[str, object]: + """Carry an interrupted or incomplete shred forward: delete any store + ciphertext still there, and retry the archive deletion this computer + recorded as pending. The header of a shredded set has no MAC, so nothing + here is chosen by it: the archive retry acts only on this computer's own + pending marker.""" + from openadapt_flow import key_hierarchy as kh + + previous = header.get("shred_record") + record: dict[str, object] = dict(previous) if isinstance(previous, dict) else {} + deleted = [*record.get("store_files_deleted", []), *_delete_store_files(base)] # type: ignore[misc] + record["store_files_deleted"] = deleted + record["stores_deleted"] = True + bucket_id = record.get("bucket_id") + archive_done = record.get("archive_complete", record.get("complete")) is not False + if not archive_done and isinstance(bucket_id, str): + try: + archive_done = kh.retry_shred(bucket_id) + except kh.KeyHierarchyError: + archive_done = False + if archive_done: + record["copies_destroyed"] = [ + *record.get("copies_destroyed", []), # type: ignore[misc] + "archive", + ] + record["archive_complete"] = archive_done + record["complete"] = archive_done + header["shred_record"] = record + _replace_header(base, header) + if archive_done and isinstance(bucket_id, str): + try: + kh.clear_pending_shred(bucket_id) + except kh.KeyHierarchyError: + pass + return record + + def shred(root: Path | str) -> dict[str, object]: """Crypto-shred a sealed set. - A version 3 set: destroy its bucket key's tracked copies (this - computer's record, overwritten then deleted, and the organization - archive's copy), drop the record and data-key stanza from the header, - and delete the durable checkpoints and other stores' ciphertext inside - it. In solo mode (record inline) this reaches only the copy on this disk: - backups still hold a record the recovery key opens. An older set loses - its salt (v1) or wrapped key (v2) instead. Returns the shred record. It - can't be undone. + A version 3 set: authenticate its header with a key this computer holds + (so a changed header can't point the deletion at another set's key), + then destroy its bucket key's tracked copies (this computer's record, + overwritten then deleted, and the copy in the archive the set was + written to), drop the record and data-key stanza from the header, and + delete the durable checkpoints and other stores' ciphertext inside it. + The shred record says ``complete`` only after the last of these. In solo + mode (record inline) this reaches only the copy on this disk: backups + still hold a record the recovery key opens. An older set loses its salt + (v1) or wrapped key (v2) instead. Returns the shred record. It can't be + undone. """ from openadapt_flow import key_hierarchy as kh base = Path(_abs(root)) - removed: list[str] = [] with mutation_lock(base): header = read_header(base) - previous = header.get("shred_record") - if header.get("shredded") and isinstance(previous, dict): - # Shredded before, with the archive copy still outstanding: retry. - if previous.get("complete") is False: - done = kh.retry_shred(str(previous.get("bucket_id"))) - previous["complete"] = done - if done: - previous["copies_destroyed"] = [ - *previous.get("copies_destroyed", []), # type: ignore[list-item] - "archive", - ] - header["shred_record"] = previous - _replace_header(base, header) - return previous - shred_record: dict[str, object] = {"schema": kh.SHRED_SCHEMA} - if header.get("version") == ENVELOPE_VERSION and not header.get("shredded"): - inline = header.get("bucket_record") + if header.get("shredded"): + return _finish_shred(base, header) + shred_record: dict[str, object] = { + "schema": kh.SHRED_SCHEMA, + "copies_destroyed": [], + "complete": True, + } + if header.get("version") == ENVELOPE_VERSION: try: - record = kh.find_record( - header.get("key_ref") or {}, # type: ignore[arg-type] - inline if isinstance(inline, dict) else None, - ) - shred_record = kh.shred(record) - except kh.KeyHierarchyError: - # No record on this computer: still delete the archive copy - # (tracked as pending when the archive can't be reached). - key_ref = header.get("key_ref") - bucket_id = ( - key_ref.get("bucket_id") if isinstance(key_ref, dict) else None + key = _open_v3(header) + except SealedSetKeyError as exc: + raise SealedSetKeyError( + f"Not shredding {base}: no key this computer holds " + f"authenticates its header ({exc}), so Flow can't tell which " + "key it may destroy. Nothing was destroyed. Shred it where " + "it was written, or as the organization (its archive record " + f"in {kh.buckets_dir()} and {kh.ORG_KEY_FILE_ENV})." + ) from exc + bucket = key.bucket + records = header.get("records") or bucket.record.get("records") # type: ignore[attr-defined] + location = header.get("key_archive") + try: + shred_record = kh.shred( + bucket.bucket_id, # type: ignore[attr-defined] + records=str(records) if records else None, + key_archive=str(location) if location else None, ) - if isinstance(bucket_id, str): - shred_record = kh.shred({"bucket_id": bucket_id}) - else: - shred_record["copies_destroyed"] = [] - for name in ( - "bucket_record", - "stanzas", - "wrapped_key", - "salt", - "kdf", - "kdf_n", - "kdf_r", - "kdf_p", - "mac", - "bucket_mac", - ): + except kh.KeyHierarchyError as exc: + raise SealedSetError(f"Not shredding {base}: {exc}") from exc + for name in _SHRED_HEADER_FIELDS: header.pop(name, None) header["shredded"] = True header["version"] = ENVELOPE_VERSION header.setdefault("set_id", secrets.token_hex(16)) + # Durable progress: not complete until the store files are gone too. + shred_record["archive_complete"] = shred_record.get("complete") is not False + shred_record["complete"] = False + shred_record["stores_deleted"] = False + shred_record["store_files_deleted"] = [] header["shred_record"] = shred_record _replace_header(base, header) - for rel in _disk_files(base): - path = base / rel - try: - data = path.read_bytes() - except OSError: - continue - if data[: len(crypto.SET_FILE_MAGIC)] in ( - crypto.SET_FILE_MAGIC, - crypto.SET3_FILE_MAGIC, - ): - continue # the set's own ciphertext, now unopenable - if crypto.is_encrypted(data): - path.unlink() - removed.append(rel) - shred_record["store_files_deleted"] = removed - return shred_record + return _finish_shred(base, header) __all__ = [ diff --git a/packages/flow/tests/test_key_hierarchy.py b/packages/flow/tests/test_key_hierarchy.py index c93b085306..990e2beb0d 100644 --- a/packages/flow/tests/test_key_hierarchy.py +++ b/packages/flow/tests/test_key_hierarchy.py @@ -89,9 +89,18 @@ def _assert_ciphertext_only(root: Path) -> None: assert TYPED not in data and not data.startswith(PNG[:8]), path +def _make_archive(folder: Path) -> Path: + """An organization key archive as an administrator sets it up.""" + folder.mkdir(parents=True, exist_ok=True) + (folder / kh.ARCHIVE_MARKER).write_text("") + return folder + + def _p256_policy( tmp_path: Path, monkeypatch, **extra ) -> tuple[Path, ec.EllipticCurvePrivateKey]: + if "key_archive" not in extra and not (tmp_path / "archive").exists(): + _make_archive(tmp_path / "archive") org = ec.generate_private_key(ec.SECP256R1()) spki = org.public_key().public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo @@ -356,7 +365,6 @@ def test_org_mode_with_an_rsa_oaep_recipient(home, tmp_path, monkeypatch) -> Non { "schema": kh.POLICY_SCHEMA, "mode": "org", - "records": "inline", "recipients": [ { "role": "org", @@ -364,6 +372,7 @@ def test_org_mode_with_an_rsa_oaep_recipient(home, tmp_path, monkeypatch) -> Non "public_key": base64.b64encode(spki).decode(), } ], + "key_archive": str(_make_archive(tmp_path / "archive")), } ) ) @@ -371,6 +380,8 @@ def test_org_mode_with_an_rsa_oaep_recipient(home, tmp_path, monkeypatch) -> Non monkeypatch.setenv(kh.TRUST_USER_POLICY_ENV, "1") run = root.parent / "run" _seal(run, {"report.json": TYPED}) + bucket_id = _header(run)["key_ref"]["bucket_id"] + archived = (tmp_path / "archive" / f"{bucket_id}.json").read_text() key_file = tmp_path / "rsa.pem" key_file.write_bytes( org.private_bytes( @@ -381,6 +392,9 @@ def test_org_mode_with_an_rsa_oaep_recipient(home, tmp_path, monkeypatch) -> Non ) monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "auditor")) at_rest.use_key_store(MemoryKeychain()) + buckets = root.parent / "auditor" / "keys" / "buckets" + buckets.mkdir(parents=True) + (buckets / f"{bucket_id}.json").write_text(archived) monkeypatch.setenv(kh.ORG_KEY_FILE_ENV, str(key_file)) assert sealed_set.read_bytes(run / "report.json") == TYPED @@ -419,6 +433,11 @@ def test_a_machine_policy_wins_over_the_user_one(home, tmp_path, monkeypatch) -> ) ) monkeypatch.setattr(kh, "MACHINE_POLICY_SOURCES", [str(machine)]) + if os.name == "posix" and os.getuid() != 0: + # A machine policy a user owns is refused, plist or not. + with pytest.raises(kh.KeyHierarchyError, match="owned by root"): + kh.load_policy() + monkeypatch.setattr(kh, "_root_only", lambda info: True) # as installed by MDM policy = kh.load_policy() assert policy.mode == "solo" and policy.source.startswith("machine:") @@ -590,6 +609,7 @@ def test_after_an_outage_the_pending_records_archive_and_recording_resumes( with pytest.raises(sealed_set.SealedSetError, match="not reached the organization"): _seal(home[0].parent / "b", {"report.json": b"{}"}) blocker.unlink() # the archive is back + _make_archive(blocker) assert kh.archive_pending()["archived"] == 1 assert kh.unarchived_count() == 0 _seal(home[0].parent / "c", {"report.json": b"{}"}) @@ -604,6 +624,7 @@ def test_the_next_set_archives_pending_records_itself( _p256_policy(tmp_path, monkeypatch, max_unarchived=1) _seal(home[0].parent / "a", {"report.json": b"{}"}) blocker.unlink() + _make_archive(blocker) _seal(home[0].parent / "b", {"report.json": b"{}"}) # no refusal assert kh.unarchived_count() == 0 @@ -614,3 +635,251 @@ def test_a_named_policy_file_that_is_missing_refuses( monkeypatch.setenv(kh.POLICY_ENV, str(tmp_path / "gone.json")) with pytest.raises(sealed_set.SealedSetError, match="never falls back"): _seal(home[0].parent / "run", {"report.json": b"{}"}) + + +# -- review round 3: archive evidence, shred authentication, races ------------- + + +def test_an_unmounted_archive_is_never_the_archive(home, tmp_path, monkeypatch) -> None: + """A mount point with nothing mounted is an empty local folder: records + are not delivered there, and a record missing from it is not deleted.""" + root, _keychain = home + mount = tmp_path / "mnt" + mount.mkdir() # no marker: the share is not mounted + _p256_policy(tmp_path, monkeypatch, key_archive=str(mount)) + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + assert kh.unarchived_count() == 1 and list(mount.iterdir()) == [] + record = sealed_set.shred(run) + assert record["complete"] is False and "archive" not in record["copies_destroyed"] + + +def test_shred_uses_the_archive_the_set_was_written_to( + home, tmp_path, monkeypatch +) -> None: + root, _keychain = home + _p256_policy(tmp_path, monkeypatch) + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + bucket_id = _header(run)["key_ref"]["bucket_id"] + original = tmp_path / "archive" / f"{bucket_id}.json" + (tmp_path / "archive" / kh.ARCHIVE_MARKER).unlink() # the share drops + assert sealed_set.shred(run)["complete"] is False + # The organization moves to a new archive, then to solo mode: neither + # may stand in for the archive that still holds the key. + _make_archive(tmp_path / "new-archive") + _p256_policy(tmp_path, monkeypatch, key_archive=str(tmp_path / "new-archive")) + assert sealed_set.shred(run)["complete"] is False + monkeypatch.delenv(kh.POLICY_ENV) + assert kh.archive_pending()["shreds_pending"] == 1 + assert sealed_set.shred(run)["complete"] is False and original.is_file() + _make_archive(tmp_path / "archive") # the original share is back + assert sealed_set.shred(run)["complete"] is True + assert not original.exists() and kh.pending_shreds() == [] + + +def test_shred_refuses_a_header_pointed_at_another_sets_key( + home, tmp_path, monkeypatch +) -> None: + root, _keychain = home + _p256_policy(tmp_path, monkeypatch) + a, b = root.parent / "a", root.parent / "b" + _seal(a, {"report.json": TYPED}) + _seal(b, {"report.json": TYPED}) + header = _header(a) + header["key_ref"] = _header(b)["key_ref"] + (a / sealed_set.HEADER).write_text(json.dumps(header)) + with pytest.raises(sealed_set.SealedSetError): + sealed_set.shred(a) + assert sealed_set.read_bytes(b / "report.json") == TYPED + + +def test_an_interrupted_shred_finishes_its_cleanup_on_retry( + home, tmp_path, monkeypatch +) -> None: + root, _keychain = home + _p256_policy(tmp_path, monkeypatch) + run = root.parent / "run" + run.mkdir() + (run / "checkpoints").mkdir() + (run / "checkpoints" / "s1.enc").write_bytes( + crypto.encrypt_bytes(b"{}", "k" * 20, aad=crypto.CHECKPOINT_AAD) + ) + writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) + writer.write("report.json", TYPED) + writer.finalize(adopt_external=True) + real = sealed_set._delete_store_files + + def crash(base: Path) -> list[str]: + raise KeyboardInterrupt # the process dies before the stores go + + monkeypatch.setattr(sealed_set, "_delete_store_files", crash) + with pytest.raises(KeyboardInterrupt): + sealed_set.shred(run) + assert _header(run)["shred_record"]["complete"] is False + assert (run / "checkpoints" / "s1.enc").exists() + monkeypatch.setattr(sealed_set, "_delete_store_files", real) + record = sealed_set.shred(run) + assert record["complete"] is True + assert record["store_files_deleted"] == ["checkpoints/s1.enc"] + + +def test_a_shredded_record_is_never_written_back(home, tmp_path, monkeypatch) -> None: + """A writer still finalizing, or an archive worker holding the record in + memory, must not resurrect a key that a shred destroyed.""" + root, _keychain = home + _p256_policy(tmp_path, monkeypatch) + run = root.parent / "run" + writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) + writer.write("report.json", TYPED) + bucket = writer._key.bucket + kh.shred(bucket.bucket_id, records="archive", key_archive=str(tmp_path / "archive")) + assert kh.archive(bucket) is False + with pytest.raises(sealed_set.SealedSetError, match="shredded"): + writer.finalize() + assert not (kh.buckets_dir() / f"{bucket.bucket_id}.json").exists() + assert not (tmp_path / "archive" / f"{bucket.bucket_id}.json").exists() + + +def test_a_whole_replacement_set_does_not_open_with_the_org_key( + home, tmp_path, monkeypatch +) -> None: + """Anyone who knows the organization's public key can wrap a bucket to it. + A record that arrives in a header is never opened with that key.""" + root, _keychain = home + key_file, org = _p256_policy(tmp_path, monkeypatch) + forged_policy = kh.Policy( + mode="solo", + records="inline", + recipients=[kh.Recipient(kh.ROLE_ORG, kh.HPKE_P256, org.public_key())], + ) + monkeypatch.setattr(kh, "load_policy", lambda: forged_policy) + forged = root.parent / "forged" + _seal(forged, {"report.json": b"forged evidence"}) + org_fprs = [s["fpr"] for s in _header(forged)["bucket_record"]["stanzas"]] + assert kh.fingerprint(org.public_key()) in org_fprs + # The reviewer, on another computer, with the organization's key. + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "reviewer")) + at_rest.use_key_store(MemoryKeychain()) + monkeypatch.setenv(kh.ORG_KEY_FILE_ENV, str(key_file)) + with pytest.raises(sealed_set.SealedSetKeyError): + sealed_set.read_bytes(forged / "report.json") + + +def test_organization_mode_requires_the_archive(home, tmp_path, monkeypatch) -> None: + _p256_policy(tmp_path, monkeypatch, records="inline") + with pytest.raises(kh.KeyHierarchyError, match="solo mode only"): + kh.load_policy() + + +def test_a_zero_backlog_needs_the_archive_for_every_set( + home, tmp_path, monkeypatch +) -> None: + _p256_policy(tmp_path, monkeypatch, max_unarchived=0) + _seal(home[0].parent / "a", {"report.json": b"{}"}) # healthy archive + assert kh.unarchived_count() == 0 + (tmp_path / "archive" / kh.ARCHIVE_MARKER).unlink() + with pytest.raises(sealed_set.SealedSetError, match="allows 0 waiting"): + _seal(home[0].parent / "b", {"report.json": b"{}"}) + assert kh.unarchived_count() == 0 # the refused set left no record + + +def test_concurrent_writers_cannot_share_the_last_backlog_slot( + home, tmp_path, monkeypatch +) -> None: + import threading + + mount = tmp_path / "mnt" + mount.mkdir() + _p256_policy(tmp_path, monkeypatch, key_archive=str(mount), max_unarchived=1) + kh.load_policy() # warm imports outside the race + results: list[str] = [] + barrier = threading.Barrier(4) + + def write(index: int) -> None: + barrier.wait() + try: + kh.new_bucket("run") + results.append("ok") + except kh.KeyHierarchyError: + results.append("refused") + + threads = [threading.Thread(target=write, args=(i,)) for i in range(4)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert sorted(results) == ["ok", "refused", "refused", "refused"] + assert kh.unarchived_count() == 1 + + +def test_a_lost_keychain_entry_does_not_hide_the_recovery_code( + home, monkeypatch +) -> None: + root, keychain = home + code, recipient = kh.new_recovery_code() + kh.save_recovery_recipient(recipient) + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + keychain.values.clear() # a restored home: the marker, not the entry + with pytest.raises(sealed_set.SealedSetError, match="missing"): + sealed_set.read_bytes(run / "report.json") + monkeypatch.setenv(kh.RECOVERY_CODE_ENV, code) + assert sealed_set.read_bytes(run / "report.json") == TYPED + # Writing still needs the device key, and still fails closed without it. + with pytest.raises((sealed_set.SealedSetError, at_rest.LocalKeyError)): + _seal(root.parent / "new", {"report.json": b"{}"}) + + +def test_each_platform_reads_only_its_own_policy_sources() -> None: + assert kh._platform_policy_sources("win32") == ["HKLM\\SOFTWARE\\Policies\\OpenAdapt"] + assert all( + not s.startswith("HKLM") for s in kh._platform_policy_sources("darwin") + ) + assert kh._platform_policy_sources("linux") == ["/etc/openadapt/policy.json"] + + +def test_a_root_owned_policy_others_can_write_is_not_trusted() -> None: + def info(mode: int, uid: int = 0) -> os.stat_result: + return os.stat_result((mode, 0, 0, 1, uid, 0, 0, 0, 0, 0)) + + assert kh._root_only(info(0o100644)) is True + assert kh._root_only(info(0o100664)) is False # group-writable + assert kh._root_only(info(0o100646)) is False # world-writable + assert kh._root_only(info(0o100644, uid=501)) is False + + +def test_a_registry_policy_the_account_cannot_read_is_an_error(monkeypatch) -> None: + """Access denied under HKLM never reads as "no policy" (solo fallback).""" + import sys + import types + + class Handle: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def open_key(hive, subkey): + if subkey.endswith("Missing"): + raise FileNotFoundError(subkey) + if subkey.endswith("Denied"): + raise PermissionError("access denied") + return Handle() + + fake = types.SimpleNamespace( + HKEY_LOCAL_MACHINE=object(), + OpenKey=open_key, + QueryValueEx=lambda handle, name: ( + json.dumps({"schema": kh.POLICY_SCHEMA, "mode": "solo"}), + 1, + ), + ) + monkeypatch.setitem(sys.modules, "winreg", fake) + monkeypatch.setattr(kh.sys, "platform", "win32") + assert kh._read_machine_source("HKLM\\SOFTWARE\\Missing") is None + assert kh._read_machine_source("HKLM\\SOFTWARE\\Present")["mode"] == "solo" + monkeypatch.setattr(kh, "MACHINE_POLICY_SOURCES", ["HKLM\\SOFTWARE\\Denied"]) + with pytest.raises(kh.KeyHierarchyError, match="can't be read"): + kh.load_policy() From f4b25e345e027f85445d533921a96462c0a3cdf7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 17:52:23 -0500 Subject: [PATCH 19/37] flow: keep run state, exports and recorders inside the at-rest policy - Durable checkpoints (and rollback state) in a version 3 run use a key derived from the run's data key, whoever constructs the store, so a shred reaches them in backups too. A store without a key encrypts by default, and a downgraded run still sets its checkpoint key. - --no-encrypt lasts for one command: the environment is restored however the command ends. - Recorder and InteractiveRecorder default to the at-rest policy; an explicit encryption_key=None is refused in strict mode and ledgered otherwise. Direct desktop capture applies strict mode, the ledger and the organization policy before the recorder starts, and a plaintext staging folder that survives cleanup is an error, not a success. - report-run --receipt writes records.json only inside an encrypted run (or under the recorded opt-out). - local-seal verify reads an encrypted run's report in memory and is sealed-ready (and strict-safe on plaintext runs). - api.replay reads the report through the sealed set. - Hosted success reporting parses the bytes it decrypted; the client run id of an encrypted run is a structural file in its sealed index. - Retention planning refuses a passphrase check on a version 3 run, where the passphrase plays no part. --- packages/flow/openadapt_flow/__main__.py | 101 +++++---- packages/flow/openadapt_flow/api.py | 12 +- packages/flow/openadapt_flow/at_rest.py | 78 ++++++- packages/flow/openadapt_flow/cli_at_rest.py | 23 +- .../flow/openadapt_flow/cli_local_seal.py | 26 ++- .../flow/openadapt_flow/desktop_record.py | 70 +++++- packages/flow/openadapt_flow/hosted.py | 45 +++- .../openadapt_flow/interactive_recorder.py | 3 +- packages/flow/openadapt_flow/key_hierarchy.py | 46 +++- packages/flow/openadapt_flow/recorder.py | 8 +- packages/flow/openadapt_flow/records/run.py | 15 +- packages/flow/openadapt_flow/retention.py | 5 + .../flow/openadapt_flow/rollback_durable.py | 5 +- .../runtime/durable/checkpoint.py | 17 +- .../runtime/durable/first_local_runtime.py | 24 +- packages/flow/openadapt_flow/sealed_set.py | 52 +++++ packages/flow/tests/test_at_rest_default.py | 30 ++- .../flow/tests/test_at_rest_review_round3.py | 210 ++++++++++++++++++ packages/flow/tests/test_desktop_record.py | 118 ++++++++++ packages/flow/tests/test_key_hierarchy.py | 55 +++++ 20 files changed, 833 insertions(+), 110 deletions(-) create mode 100644 packages/flow/tests/test_at_rest_review_round3.py diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 003d6d392c..286842477b 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13883,7 +13883,10 @@ def _unsealed_output_check(args: argparse.Namespace) -> None: "patient data encrypted, and this one writes files outside an " "encrypted set. Nothing was run." ) - if command in _SEALED_READY_COMMANDS and command not in _STRICT_SELF_SEALING: + if ( + command in _SEALED_READY_COMMANDS + and command not in _STRICT_SELF_SEALING | _at_rest_cli.READ_ONLY + ): # These keep sealed input sealed; given plaintext input they # re-save or write beside it in plaintext. So every directory # they are given must already be encrypted. @@ -14183,53 +14186,55 @@ def main( return 2 from openadapt_flow import at_rest - _at_rest_cli.apply_no_encrypt(args, _cmd_record) - try: - _unsealed_output_check(args) - except (at_rest.AtRestRefused, ValueError) as exc: - print(f"REFUSED: {safe_errors.message(exc)}", file=sys.stderr) - return 2 - try: - # Inject only after the ordinary input/output argument guards. This - # object is not a CLI flag, path exemption or serialized capability. - if record_check_proof_source is not None: - args._record_check_proof_source = record_check_proof_source - code = args.func(args) - if getattr(args, "command", None) in ("run", "replay"): - # Terminal handlers sign receipts. Keep the old Seal here for one release. - from openadapt_flow.receipt_record import after_run_notes - - run_dir = getattr(args, "run_dir", None) - folder = Path(run_dir) if run_dir else None - for note in after_run_notes(folder, include_receipt=False): - print(note, file=sys.stderr) - return code - except (sealed_set.SealedSetError, at_rest.AtRestRefused) as exc: - # A sealed bundle or encrypted recording that is missing its key, - # was changed after sealing, or holds an unknown file, or a write - # strict mode refuses: fail closed. - print(f"REFUSED: {safe_errors.message(exc)}", file=sys.stderr) - return 2 - except BrowserSupportMissing as exc: - # Missing optional browser support is a setup decision, not a crash. - print(f"Browser setup required:\n{exc}", file=sys.stderr) - return 2 - except Exception as exc: - from openadapt_flow.runtime.known_ids import KnownIdAdmissionHalt - - if not isinstance(exc, KnownIdAdmissionHalt): - if _private_input(args): - # A traceback would quote what the command read from sealed - # input: name the kind of error only. - print(f"FAILED: {safe_errors.withheld(exc)}", file=sys.stderr) - return 1 - raise - # The configured known-ID list may not be used: halt before any step - # runs, with the named reason. - print( - f"replay halted before start: {exc.reason}: {exc.detail}", file=sys.stderr - ) - return 3 + # --no-encrypt holds for this command only: an application that calls + # main() in-process gets the environment back however the command ends. + with _at_rest_cli.no_encrypt_scope(args, _cmd_record): + try: + _unsealed_output_check(args) + except (at_rest.AtRestRefused, ValueError) as exc: + print(f"REFUSED: {safe_errors.message(exc)}", file=sys.stderr) + return 2 + try: + # Inject only after the ordinary input/output argument guards. This + # object is not a CLI flag, path exemption or serialized capability. + if record_check_proof_source is not None: + args._record_check_proof_source = record_check_proof_source + code = args.func(args) + if getattr(args, "command", None) in ("run", "replay"): + # Terminal handlers sign receipts. Keep the old Seal here for one release. + from openadapt_flow.receipt_record import after_run_notes + + run_dir = getattr(args, "run_dir", None) + folder = Path(run_dir) if run_dir else None + for note in after_run_notes(folder, include_receipt=False): + print(note, file=sys.stderr) + return code + except (sealed_set.SealedSetError, at_rest.AtRestRefused) as exc: + # A sealed bundle or encrypted recording that is missing its key, + # was changed after sealing, or holds an unknown file, or a write + # strict mode refuses: fail closed. + print(f"REFUSED: {safe_errors.message(exc)}", file=sys.stderr) + return 2 + except BrowserSupportMissing as exc: + # Missing optional browser support is a setup decision, not a crash. + print(f"Browser setup required:\n{exc}", file=sys.stderr) + return 2 + except Exception as exc: + from openadapt_flow.runtime.known_ids import KnownIdAdmissionHalt + + if not isinstance(exc, KnownIdAdmissionHalt): + if _private_input(args): + # A traceback would quote what the command read from sealed + # input: name the kind of error only. + print(f"FAILED: {safe_errors.withheld(exc)}", file=sys.stderr) + return 1 + raise + # The configured known-ID list may not be used: halt before any step + # runs, with the named reason. + print( + f"replay halted before start: {exc.reason}: {exc.detail}", file=sys.stderr + ) + return 3 if __name__ == "__main__": diff --git a/packages/flow/openadapt_flow/api.py b/packages/flow/openadapt_flow/api.py index 7ff72ba518..cb0b7274b6 100644 --- a/packages/flow/openadapt_flow/api.py +++ b/packages/flow/openadapt_flow/api.py @@ -96,8 +96,12 @@ def replay( argv += ["--param", f"{key}={value}"] from openadapt_flow.__main__ import main - main(argv) + code = main(argv) + from openadapt_flow import sealed_set + + # The run directory is encrypted by default: read the report through the + # sealed set, in memory, rather than looking for a plaintext file. report_path = Path(run_dir) / "report.json" - if not report_path.exists(): - raise FlowCommandFailed("replay", 1) - return RunReport.model_validate_json(report_path.read_text(encoding="utf-8")) + if not sealed_set.is_file(report_path): + raise FlowCommandFailed("replay", code or 1) + return RunReport.model_validate_json(sealed_set.read_text(report_path)) diff --git a/packages/flow/openadapt_flow/at_rest.py b/packages/flow/openadapt_flow/at_rest.py index feb2a06e0e..215ee77a9b 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -50,8 +50,9 @@ import sys import threading import time +from contextlib import contextmanager from pathlib import Path -from typing import Final, Optional +from typing import Final, Iterator, Optional from openadapt_flow.private_file import open_binary @@ -114,14 +115,24 @@ def encrypt_setting() -> bool: raise ValueError(f"{ENCRYPT_ENV} takes 1 or 0, not {value!r}") -def opt_out_for_this_process(source: str) -> None: - """Turn encryption off for this process and its children (``--no-encrypt``). - - The one-line warning and the ledger line follow at the first write. - """ +@contextmanager +def opted_out(source: str) -> Iterator[None]: + """Turn encryption off for one command (``--no-encrypt``): in this + process and the children it starts, until the block ends, however it + ends. The one-line warning and the ledger line follow at the first + write.""" + saved = {name: os.environ.get(name) for name in (ENCRYPT_ENV, OPT_OUT_ENV)} os.environ[ENCRYPT_ENV] = "0" - if not (os.environ.get(OPT_OUT_ENV) or "").strip(): + if not (saved[OPT_OUT_ENV] or "").strip(): os.environ[OPT_OUT_ENV] = source + try: + yield + finally: + for name, value in saved.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value def explicit_key() -> bool: @@ -767,6 +778,59 @@ def seal_new(artifact: str, path: Path | str) -> bool: return False +#: ``encryption_key=POLICY``, the default of the library recording entry +#: points: decide from the at-rest policy, as ``record`` does (encrypted by +#: default; plaintext only under the recorded opt-out). +POLICY: Final[object] = object() + + +def plaintext_by_caller(artifact: str, path: Path | str) -> None: + """A library caller passed ``encryption_key=None``: ``artifact`` at + ``path`` is written in plaintext. Strict mode refuses before anything is + written; otherwise stderr names it and a ledger line records it (once + per artifact and path in a process), never silently.""" + if strict(): + raise AtRestRefused( + f"Not writing {artifact} at {path} in plaintext " + f"(encryption_key=None): {MODE_ENV}=strict refuses plaintext. " + "Nothing was written." + ) + purpose = f"{artifact} at {path}" + reason = opt_out_reason() + if reason is not None: + record_plaintext(purpose, reason) + return + _record( + purpose, + "the caller passed encryption_key=None", + path=str(path), + warning=( + f"WARNING: writing {artifact} in plaintext at {path}: the caller " + "turned encryption off (encryption_key=None). It can hold patient " + f"data. Set {MODE_ENV}=strict to refuse instead." + ), + ) + + +def new_artifact_key( + explicit: Optional[str] | object, artifact: str, path: Path | str +) -> Optional[str]: + """The key for a new recording a library entry point writes: the + caller's key; under :data:`POLICY`, the policy's (None, plaintext, only + under the recorded opt-out); an explicit ``None`` is plaintext through + :func:`plaintext_by_caller` (refused in strict mode, else recorded).""" + if explicit is POLICY: + if not seal_new(artifact, path): + return None + from openadapt_flow import sealed_set + + return sealed_set.recording_key() + if not explicit: + plaintext_by_caller(artifact, path) + return None + return str(explicit) + + def seals_by_default() -> bool: """Whether new artifacts are sealed now, without recording anything: strict mode, or the default mode without the opt-out.""" diff --git a/packages/flow/openadapt_flow/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py index 0195e407d4..582cb00c67 100644 --- a/packages/flow/openadapt_flow/cli_at_rest.py +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -18,6 +18,7 @@ import json import sys from pathlib import Path +from typing import Any RECOVERY_WARNING = ( "Anyone with this code can open every recording and run on this computer, " @@ -139,13 +140,18 @@ def _cmd_shred(args: argparse.Namespace) -> int: #: Commands that read sealed input without decrypting it to disk: -#: ``inspect report-run`` reads the report in memory; ``shred`` touches keys. +#: ``inspect report-run`` and ``local-seal verify`` read the report in +#: memory; ``shred`` touches keys. SEALED_READY: frozenset[str] = frozenset( { "openadapt_flow.__main__:_cmd_report_run", "openadapt_flow.cli_at_rest:_cmd_shred", + "openadapt_flow.cli_local_seal:_cmd_verify", } ) +#: Sealed-ready commands that write nothing, so strict mode runs them on +#: plaintext input too (verifying a receipt over a plaintext run). +READ_ONLY: frozenset[str] = frozenset({"openadapt_flow.cli_local_seal:_cmd_verify"}) #: Commands that write no recorded data. STRICT_SAFE: frozenset[str] = frozenset( { @@ -204,17 +210,22 @@ def add_no_encrypt(p: argparse.ArgumentParser) -> None: ) -def apply_no_encrypt(args: argparse.Namespace, record_func: object) -> None: - """``compile/run/replay --no-encrypt``: this process writes plaintext, with - the one-line warning and the ledger line at the first write. ``record`` - handles its own flag.""" +def no_encrypt_scope(args: argparse.Namespace, record_func: object) -> Any: + """``compile/run/replay --no-encrypt``: this command writes plaintext, with + the one-line warning and the ledger line at the first write. The opt-out + lasts for the ``with`` block only (and the children it starts), so a + later command in the same process is encrypted again. ``record`` handles + its own flag.""" + from contextlib import nullcontext + from openadapt_flow import at_rest if ( getattr(args, "no_encrypt", False) and getattr(args, "func", None) is not record_func ): - at_rest.opt_out_for_this_process("--no-encrypt") + return at_rest.opted_out("--no-encrypt") + return nullcontext() def note_plaintext_recording(artifact: str, out: object) -> None: diff --git a/packages/flow/openadapt_flow/cli_local_seal.py b/packages/flow/openadapt_flow/cli_local_seal.py index 3734ccf484..3115ed3825 100644 --- a/packages/flow/openadapt_flow/cli_local_seal.py +++ b/packages/flow/openadapt_flow/cli_local_seal.py @@ -80,6 +80,30 @@ def _looks_like_web_page(raw: bytes) -> bool: ) +def _input_report(path: Path) -> Any: + """A run's ``report.json``: read in memory through its encrypted run + directory when there is one (runs are encrypted by default), else from + disk like any input.""" + from openadapt_flow import sealed_set + + if not sealed_set.is_sealed_path(path): + return _input_json(path) + from openadapt_flow.offline_seal import loads_strict + + try: + if not sealed_set.is_file(path): + raise InputError(f"{path}: no such file") + raw = sealed_set.read_bytes(path) + except sealed_set.SealedSetError as exc: + raise InputError(f"{path} can't be read: {exc}") from exc + if not raw.strip(): + raise InputError(f"{path} is empty") + try: + return loads_strict(raw) + except ValueError as exc: + raise InputError(f"{path} is not valid JSON: {exc}") from exc + + def _input_json(path: Path) -> Any: """Parse an input file as JSON (repeated keys refused), or explain in one line.""" from openadapt_flow.offline_seal import loads_strict @@ -354,7 +378,7 @@ def _check_verify_inputs(args: argparse.Namespace, target: Path) -> None: seal: Optional[Path] if target.is_dir(): - _input_json(target / "report.json") + _input_report(target / "report.json") seal = target / "seal.json" else: _input_bytes(target) diff --git a/packages/flow/openadapt_flow/desktop_record.py b/packages/flow/openadapt_flow/desktop_record.py index 034b05fb22..7dd0450daa 100644 --- a/packages/flow/openadapt_flow/desktop_record.py +++ b/packages/flow/openadapt_flow/desktop_record.py @@ -45,6 +45,7 @@ import functools import importlib.util import json +import os import shlex import subprocess import sys @@ -52,6 +53,8 @@ from pathlib import Path from typing import Any, Callable, ContextManager, Optional, Protocol +from openadapt_flow.at_rest import POLICY as _POLICY + # Platforms where openadapt-capture's window-scoped capture is implemented # (openadapt_capture.window_capture.resolve_window / capture_window). Kept in # lock-step with that module: recording ONE window in its own pixel space needs @@ -246,7 +249,7 @@ def _wait_for_stop(stop: Optional[Callable[[], bool]]) -> None: #: ``encryption_key=POLICY``: decide from the at-rest policy, as ``record`` #: does (encrypted by default; strict mode holds the raw capture back). -POLICY: object = object() +POLICY: object = _POLICY def record_desktop_capture( @@ -343,8 +346,9 @@ def record_desktop_capture( # backstop. _require_capture_extra() - if encryption_key is POLICY: - encryption_key = _policy_key(out_dir) + # Every policy decision is made here, before the recorder starts: the raw + # capture session is plaintext while it records, whatever key is given. + encryption_key = _policy_key(out_dir, encryption_key) if encryption_key and capture_dir is not None: # The raw session would sit outside the private staging folder that # is deleted after sealing, and stay plaintext. Refuse before recording. @@ -353,6 +357,12 @@ def record_desktop_capture( "recording: the raw capture session would be left in plaintext at " f"{capture_dir}. Nothing was recorded. Omit capture_dir." ) + if encryption_key: + # Organization policy (recipients, archive, backlog, hardware key) is + # checked before anything is captured, not first at sealing time. + from openadapt_flow import sealed_set + + sealed_set.preflight_new("recording", encryption_key) out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) final_dir = out_dir @@ -392,22 +402,58 @@ def record_desktop_capture( if staging is None: return recording _seal_recording(Path(recording), final_dir, encryption_key) # type: ignore[arg-type] - return final_dir - finally: + except BaseException: if staging is not None: - import shutil + left = _remove_staging(staging) + if left: + print( + f"ERROR: the plaintext capture staging at {staging} could " + f"not be fully deleted ({', '.join(left[:3])}). Delete it " + "by hand: it can hold patient data.", + file=sys.stderr, + ) + raise + left = _remove_staging(staging) + if left: + # The recording is sealed, but plaintext survived beside it: that is + # not a successful encrypted recording. + raise RuntimeError( + f"record: the recording is sealed at {final_dir}, but its plaintext " + f"capture staging at {staging} could not be deleted " + f"({', '.join(left[:3])}). Delete it by hand: it can hold patient data." + ) + return final_dir + + +def _remove_staging(staging: Path) -> list[str]: + """Delete the private plaintext staging folder; the paths that survived.""" + import shutil + + failed: list[str] = [] + + def note(_func: Any, path: str, _exc: Any) -> None: + failed.append(path) + + if sys.version_info >= (3, 12): + shutil.rmtree(staging, onexc=note) + else: # pragma: no cover - Python 3.10 and 3.11 + shutil.rmtree(staging, onerror=note) + if os.path.lexists(staging) and not failed: + failed.append(str(staging)) + return failed - shutil.rmtree(staging, ignore_errors=True) +def _policy_key(out_dir: Path | str, explicit: Optional[str] | object) -> Optional[str]: + """The key for a desktop recording, from the policy or the caller. -def _policy_key(out_dir: Path | str) -> Optional[str]: - from openadapt_flow import at_rest, sealed_set + Strict mode refuses any desktop capture (its raw session is plaintext + while it records), whether or not a key was passed. An explicit ``None`` + is a plaintext recording, recorded in the ledger.""" + from openadapt_flow import at_rest if at_rest.strict(): at_rest.unsealed_write("a desktop raw capture session", str(out_dir)) - if not at_rest.seal_new("a desktop recording", out_dir): - return None - return sealed_set.recording_key() + return at_rest.new_artifact_key(explicit, "a desktop recording", out_dir) def _seal_recording(plain: Path, dest: Path, key: str) -> None: diff --git a/packages/flow/openadapt_flow/hosted.py b/packages/flow/openadapt_flow/hosted.py index 1d7e60696c..a9484dc1be 100644 --- a/packages/flow/openadapt_flow/hosted.py +++ b/packages/flow/openadapt_flow/hosted.py @@ -1932,6 +1932,44 @@ def _coarse_status_for_outcome( raise HostedError("report contains an unknown execution outcome") +def _sealed_client_run_id(run_path: Path, id_path: Path) -> str: + """The client run id of an encrypted run directory, kept in its sealed + index (a random UUID, so a structural file), never as a stray plaintext + file the set's readers would refuse. Created once, under its own lock, + so a retry reports the same id.""" + import hashlib + import uuid + + from openadapt_flow import at_rest, sealed_set + from openadapt_flow.sealed_maintenance import mutation_lock + + # Its own lock (a private folder per run path), not the set's: the + # sealed write below takes the set's lock itself. + lock_dir = ( + at_rest._home() + / "locks" + / ( + "report-run-id-" + + hashlib.sha256(os.fsencode(os.path.abspath(run_path))).hexdigest()[:32] + ) + ) + try: + at_rest._private_dir(lock_dir.parent) + at_rest._private_dir(lock_dir) + with mutation_lock(lock_dir): + if sealed_set.is_file(id_path): + raw = sealed_set.read_text(id_path) + parsed = str(UUID(raw.strip())) + if raw not in {parsed, f"{parsed}\n"}: + raise ValueError("run report id is not canonical") + return parsed + fresh = str(uuid.uuid4()) + sealed_set.write_text(id_path, fresh + "\n") + return fresh + except (OSError, ValueError) as exc: # a SealedSetError is a ValueError + raise HostedError("run report id is unreadable or invalid") from exc + + def _client_run_id(run_path: Path) -> str: """The stable, client-generated UUID for this run directory. @@ -1943,6 +1981,10 @@ def _client_run_id(run_path: Path) -> str: import uuid id_path = run_path / _RUN_REPORT_ID_FILE + from openadapt_flow import sealed_set + + if sealed_set.is_sealed_path(run_path): + return _sealed_client_run_id(run_path, id_path) def read_existing(metadata: os.stat_result) -> str: """Read one exact existing entry, allowing its creator to finish. @@ -2445,7 +2487,8 @@ def report_run( f"report.json exceeds the {_MAX_RUN_REPORT_BYTES}-byte reporting limit" ) try: - report = RunReport.model_validate_json(report_path.read_text(encoding="utf-8")) + # The bytes already read (decrypted in memory for an encrypted run). + report = RunReport.model_validate_json(report_bytes.decode("utf-8")) except (OSError, ValueError) as exc: raise HostedError("report.json is unreadable or invalid") from exc diff --git a/packages/flow/openadapt_flow/interactive_recorder.py b/packages/flow/openadapt_flow/interactive_recorder.py index 417fcffe4c..b65e953281 100644 --- a/packages/flow/openadapt_flow/interactive_recorder.py +++ b/packages/flow/openadapt_flow/interactive_recorder.py @@ -87,6 +87,7 @@ from PIL import Image +from openadapt_flow import at_rest as _at_rest from openadapt_flow import choice_capture as _choice_capture from openadapt_flow import recorder_document as _documents from openadapt_flow import sealed_set as _sealed @@ -2334,7 +2335,7 @@ def __init__( stop_when: Optional[Callable[[], bool]] = None, surface: str = "web", capture_network: bool = False, - encryption_key: Optional[str] = None, + encryption_key: Optional[str] | object = _at_rest.POLICY, event_clock: Optional[list[float]] = None, ) -> None: self._url = url diff --git a/packages/flow/openadapt_flow/key_hierarchy.py b/packages/flow/openadapt_flow/key_hierarchy.py index ab85945cee..eb0077f3e9 100644 --- a/packages/flow/openadapt_flow/key_hierarchy.py +++ b/packages/flow/openadapt_flow/key_hierarchy.py @@ -823,6 +823,41 @@ def bucket_lock() -> Iterator[None]: _bucket_depth.n = 0 +def _device_for(policy: Policy) -> tuple[Unwrapper, Unwrapper]: + device = device_keys(create=True) + assert device is not None + runtime, viewer = device + if policy.require_hardware_device_key and ( + is_software(runtime) or is_software(viewer) + ): + raise KeyHierarchyError( + "the policy requires a hardware device key, and this computer has " + "only a software key. Nothing was written." + ) + return runtime, viewer + + +def preflight(policy: Optional[Policy] = None) -> None: + """Refuse now what :func:`new_bucket` would refuse later, without making + a record: for a capture whose raw session is plaintext while it records, + so a policy that won't let it be sealed stops it before it starts.""" + policy = policy or load_policy() + _device_for(policy) + if policy.records != "archive": + return + try: + _archive_root(policy.key_archive) + return + except KeyHierarchyError as exc: + unreachable = exc + if unarchived_count() + 1 > policy.max_unarchived: + raise KeyHierarchyError( + f"{unreachable}; {unarchived_count()} encrypted sets are waiting for " + f"it and the policy allows {policy.max_unarchived}. Nothing was " + "recorded." + ) + + def new_bucket(kind: str, policy: Optional[Policy] = None) -> Bucket: """A fresh bucket for one sealed set, wrapped to the policy's recipients. @@ -834,16 +869,7 @@ def new_bucket(kind: str, policy: Optional[Policy] = None) -> Bucket: is refused before anything is written. """ policy = policy or load_policy() - device = device_keys(create=True) - assert device is not None - runtime, viewer = device - if policy.require_hardware_device_key and ( - is_software(runtime) or is_software(viewer) - ): - raise KeyHierarchyError( - "the policy requires a hardware device key, and this computer has " - "only a software key. Nothing was written." - ) + runtime, viewer = _device_for(policy) private = ec.generate_private_key(ec.SECP256R1()) bucket_id = secrets.token_hex(16) secret = _scalar(private) diff --git a/packages/flow/openadapt_flow/recorder.py b/packages/flow/openadapt_flow/recorder.py index caa720d3b8..aeae259143 100644 --- a/packages/flow/openadapt_flow/recorder.py +++ b/packages/flow/openadapt_flow/recorder.py @@ -61,6 +61,7 @@ from PIL import Image, ImageDraw +from openadapt_flow import at_rest as _at_rest from openadapt_flow import sealed_set as _sealed from openadapt_flow.backend import ( Backend, @@ -227,7 +228,7 @@ def __init__( surface_id: str = PRIMARY_SURFACE_ID, surface_kind: Optional[str] = None, page_backend_factory: Optional[Callable[[Any], Backend]] = None, - encryption_key: Optional[str] = None, + encryption_key: Optional[str] | object = _at_rest.POLICY, finalize_on_finish: bool = True, capture_hover: bool = False, event_clock: Optional[list[float]] = None, @@ -272,6 +273,11 @@ def __init__( # sealed set that is finalized (indexed) when the recording finishes. self._sealed_writer: Optional[_sealed.SealedSetWriter] = None self._finalize_on_finish = finalize_on_finish + # Encrypted by default (the at-rest policy decides); an explicit + # ``None`` is plaintext that strict mode refuses and the ledger records. + encryption_key = _at_rest.new_artifact_key( + encryption_key, "a recording", self._dir + ) if encryption_key: self._sealed_writer = _sealed.SealedSetWriter( self._dir, "recording", encryption_key diff --git a/packages/flow/openadapt_flow/records/run.py b/packages/flow/openadapt_flow/records/run.py index 0272f18118..92e62feec2 100644 --- a/packages/flow/openadapt_flow/records/run.py +++ b/packages/flow/openadapt_flow/records/run.py @@ -109,10 +109,21 @@ def write_sealed_reads(report: Any, receipt_json: Path | str) -> Optional[Path]: out = Path(receipt_json).parent / "records.json" import json - from openadapt_flow import sealed_set + from openadapt_flow import at_rest, sealed_set # The values read are record data: encrypted when written beside an - # encrypted run (a "*" run file), plaintext otherwise. + # encrypted run (a "*" run file). Anywhere else they would be plaintext, + # which only the recorded opt-out allows; strict and default modes refuse. + if not sealed_set.is_sealed_path(out) and not at_rest.plaintext_allowed( + f"the field values a run read (records.json) at {out}" + ): + raise at_rest.AtRestRefused( + at_rest.refusal( + f"the field values this run read at {out}", + "that folder is not an encrypted run directory", + ) + + " Or write the receipt into the encrypted run directory." + ) sealed_set.write_text( out, json.dumps([r.model_dump(mode="json") for r in sealed], indent=2) + "\n" ) diff --git a/packages/flow/openadapt_flow/retention.py b/packages/flow/openadapt_flow/retention.py index 37c91faac8..e69c0883ff 100644 --- a/packages/flow/openadapt_flow/retention.py +++ b/packages/flow/openadapt_flow/retention.py @@ -211,6 +211,11 @@ def plan_retention( raise RetentionError("encrypted_run_required") header = _snapshot(root, sealed_set.HEADER, disk[sealed_set.HEADER]) try: + if sealed_set.read_header(root).get("version") == sealed_set.ENVELOPE_VERSION: + # A version 3 set opens with a recipient key this computer holds; + # the passphrase given here plays no part, so a successful open + # would prove nothing about it. Refuse rather than accept any key. + raise RetentionError("explicit_key_does_not_open_version_3_run") opened = sealed_set.SealedSet.open(root, key, expect="run") authenticated = sealed_set._open_index(root, opened._header, opened._key) # A live run may reconcile external checkpoints and locks. Retention diff --git a/packages/flow/openadapt_flow/rollback_durable.py b/packages/flow/openadapt_flow/rollback_durable.py index aebb68a895..f977360ac7 100644 --- a/packages/flow/openadapt_flow/rollback_durable.py +++ b/packages/flow/openadapt_flow/rollback_durable.py @@ -67,7 +67,10 @@ def __init__(self, run_dir: Path | str, key: str) -> None: if not key: raise SealedStateError("sealed rollback state needs a key") self.run_dir = Path(run_dir) - self.key = key + from openadapt_flow import sealed_set + + # Inside a version 3 run, the run's own store key (a shred reaches it). + self.key = sealed_set.store_passphrase(self.run_dir) or key self.dir = self.run_dir / ROLLBACK_DIRNAME # -- files ------------------------------------------------------------ diff --git a/packages/flow/openadapt_flow/runtime/durable/checkpoint.py b/packages/flow/openadapt_flow/runtime/durable/checkpoint.py index f9ab6757d1..9c1bffcf84 100644 --- a/packages/flow/openadapt_flow/runtime/durable/checkpoint.py +++ b/packages/flow/openadapt_flow/runtime/durable/checkpoint.py @@ -492,9 +492,14 @@ class CheckpointStore: def __init__(self, run_dir: Path | str, *, key: Optional[str] = None) -> None: self.run_dir = Path(run_dir) self.checkpoints_dir = self.run_dir / CHECKPOINTS_DIRNAME - # None => plaintext (unchanged default). A non-empty passphrase turns on - # AEAD sealing for writes and decryption for reads. - self.key = key + # A non-empty passphrase turns on AEAD sealing for writes and + # decryption for reads. Inside a version 3 run the passphrase is + # always the run's own (derived from its data key, so a shred reaches + # these containers too), whatever the caller resolved. + from openadapt_flow import sealed_set as _sealed + + bound = _sealed.store_passphrase(self.run_dir) + self.key = bound or key # Reuse one public salt for containers this store seals; each # container records the salt and gets its own random nonce. self._salt: Optional[bytes] = None @@ -529,6 +534,12 @@ def _write_model(self, path: Path, model: BaseModel) -> Path: sealed with AES-256-GCM when a key is configured. Returns the path actually written; removes the counterpart form if it lingers.""" data = model.model_dump_json(indent=2).encode("utf-8") + if not self.key: + # No key given: encrypted by default with this computer's key + # (docs/phi_at_rest.md); plaintext only under the recorded opt-out. + from openadapt_flow import crypto as _crypto + + self.key = _crypto.resolve_key(None) if self.key: from openadapt_flow import crypto as _crypto diff --git a/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py b/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py index f46f466073..07a0754c09 100644 --- a/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py +++ b/packages/flow/openadapt_flow/runtime/durable/first_local_runtime.py @@ -255,18 +255,28 @@ def run_with_output( if _sealed.active_writer(run_path) is None and not downgraded: if not at_rest.plaintext_allowed("a run directory"): at_rest.unsealed_write("a run directory", run_dir) - if replayer.checkpoint_key is None: - # Durable checkpoints can still be encrypted here. - from openadapt_flow import crypto as _crypto + if replayer.checkpoint_key is None: + # A plaintext run directory (including a downgraded one) + # still encrypts its durable checkpoints, unless the opt-out + # is on (recorded). + from openadapt_flow import crypto as _crypto - replayer.checkpoint_key = _crypto.resolve_key(None) + replayer.checkpoint_key = ( + _sealed.store_passphrase(run_path) + or _crypto.resolve_key(None) + ) return replayer._run_unsealed(workflow, **kwargs) - if replayer.checkpoint_key is None: - # A sealed bundle's run keeps its durable state under the same key. - replayer.checkpoint_key = passphrase writer = _sealed.SealedSetWriter( run_path, "run", passphrase, resume=_sealed.is_sealed(run_path) ) + bound = _sealed.store_passphrase_of(writer) + if bound is not None: + # A version 3 run keeps its durable state under a key derived + # from its own data key, so shredding the run reaches it too. + replayer.checkpoint_key = bound + elif replayer.checkpoint_key is None: + # An older sealed run keeps its durable state under the same key. + replayer.checkpoint_key = passphrase _sealed.register_writer(writer) try: report = replayer._run_unsealed(workflow, **kwargs) diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index d684a0d0bd..8574fa4a7a 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -270,6 +270,11 @@ class FileKind: "a random per-run capability secret (no recorded data)", ), FileKind(".attended_action.lease", "structural", "an action lease marker"), + FileKind( + ".report_run_id", + "structural", + "the random UUID that makes reporting this run to Cloud idempotent", + ), FileKind("*.lock", "structural", "a lock file"), # The receipt files stay readable without the key: they hold signatures, # outcomes, counts and SHA-256 digests over the plaintext report.json, @@ -972,6 +977,21 @@ def _new_v3( return header, V3Key(dek, set_id, bucket) +def preflight_new(kind: str, passphrase: Optional[str]) -> None: + """Refuse, before a capture starts, a new set :func:`_new_v3` would + refuse at sealing time (organization recipients, archive and backlog, + hardware key). Makes no record.""" + from openadapt_flow import key_hierarchy as kh + + try: + policy = kh.load_policy() + if _explicit_passphrase(passphrase) and policy.mode != "org": + return + kh.preflight(policy) + except kh.KeyHierarchyError as exc: + raise SealedSetError(f"Not recording an encrypted {kind}: {exc}") from exc + + class SealedSetWriter: """Write a sealed set file by file, ciphertext only, then finalize it. @@ -1312,6 +1332,37 @@ def open_set(root: Path | str, key: Optional[str] = None) -> SealedSet: raise +def store_passphrase_of(writer: "SealedSetWriter") -> Optional[str]: + """:func:`store_passphrase` of an open writer's set.""" + key = getattr(writer, "_key", None) + return key.store_passphrase if isinstance(key, V3Key) else None + + +def store_passphrase(run_dir: Path | str) -> Optional[str]: + """The passphrase for another store's containers inside a version 3 run + (durable checkpoints, approvals, transition evidence), or None when + ``run_dir`` is not one. + + It is derived from the set's data key, so it is the same for every + process and every leg of a run, and a shred of the set's bucket makes + those containers unreadable everywhere, backups included. Only the + header is opened (and authenticated), so a run that has not been + finalized yet, such as one paused mid-leg, still resolves it. A shredded + set, or one no key here opens, refuses: nothing falls back to the + long-lived local passphrase. + """ + base = _abs(run_dir) + writer = active_writer(base) + if writer is not None: + return store_passphrase_of(writer) + if not is_sealed(base): + return None + header = read_header(base) + if header.get("version") != ENVELOPE_VERSION: + return None + return _open_v3(header).store_passphrase + + def _configured(kind: str) -> bool: return bool(os.environ.get(crypto.ENV_KEY) or os.environ.get(RECORDING_ENV_KEY)) @@ -1672,6 +1723,7 @@ def shred(root: Path | str) -> dict[str, object]: "V3Key", "key_record_of", "shred", + "store_passphrase", "HEADER", "LIBRARY_FILES", "RECORDING_ENV_KEY", diff --git a/packages/flow/tests/test_at_rest_default.py b/packages/flow/tests/test_at_rest_default.py index 750526f71b..9131456691 100644 --- a/packages/flow/tests/test_at_rest_default.py +++ b/packages/flow/tests/test_at_rest_default.py @@ -45,6 +45,16 @@ def default_mode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: at_rest._reset_for_tests() +def _legacy_recording(rec_dir: Path) -> Path: + """A plaintext recording an earlier version made. Making it now is a + recorded plaintext write (encryption_key=None); that ledger line belongs + to the setup, not to the command under test.""" + rec = _recording(rec_dir, key=None) + at_rest.ledger_path().unlink(missing_ok=True) + at_rest._reset_for_tests() + return rec + + def _ledger(home: Path) -> list[dict]: path = home / at_rest.LEDGER_NAME if not path.exists(): @@ -143,7 +153,7 @@ def test_unsealed_write_names_the_path_or_refuses( def test_a_plaintext_recording_compiles_to_a_sealed_bundle_by_default( default_mode: Path, tmp_path: Path ) -> None: - rec = _recording(tmp_path / "rec", key=None) # made before the default + rec = _legacy_recording(tmp_path / "rec") # made before the default assert main(["compile", str(rec), "--out", str(tmp_path / "b"), "--name", "x"]) == 0 _assert_ciphertext_only(tmp_path / "b") assert sealed_set.read_header(tmp_path / "b")["version"] == 3 @@ -154,7 +164,7 @@ def test_a_plaintext_recording_compiles_to_a_sealed_bundle_by_default( def test_strict_mode_compiles_a_plaintext_recording_to_a_sealed_bundle( default_mode: Path, tmp_path: Path, monkeypatch ) -> None: - rec = _recording(tmp_path / "rec", key=None) # made before strict mode + rec = _legacy_recording(tmp_path / "rec") # made before strict mode monkeypatch.setenv(at_rest.MODE_ENV, "strict") assert main(["compile", str(rec), "--out", str(tmp_path / "b"), "--name", "x"]) == 0 _assert_ciphertext_only(tmp_path / "b") @@ -167,7 +177,7 @@ def test_compile_under_the_opt_out_stays_plaintext( default_mode: Path, tmp_path: Path, monkeypatch ) -> None: monkeypatch.setenv(at_rest.OPT_OUT_ENV, "fixtures") - rec = _recording(tmp_path / "rec", key=None) + rec = _legacy_recording(tmp_path / "rec") assert main(["compile", str(rec), "--out", str(tmp_path / "b"), "--name", "x"]) == 0 assert (tmp_path / "b" / "workflow.json").is_file() assert any(e["purpose"] == "a compiled bundle" for e in _ledger(default_mode)) @@ -387,7 +397,10 @@ def test_default_mode_checkpoints_are_encrypted_on_disk( replayer.run(Workflow.load(bundle), bundle_dir=bundle, run_dir=run_dir) except Exception: # noqa: BLE001 - no app is listening; the key is what counts pass - assert replayer.checkpoint_key == at_rest.local_key() + # A version 3 run keys its checkpoints from its own data key (a shred + # reaches them), not from the long-lived local passphrase. + assert replayer.checkpoint_key == sealed_set.store_passphrase(run_dir) + assert replayer.checkpoint_key != at_rest.local_key() store = CheckpointStore(run_dir, key=replayer.checkpoint_key) marker = secrets.token_hex(16) probe = run_dir / "checkpoints" / "probe.json" @@ -400,9 +413,14 @@ def test_default_mode_checkpoints_are_encrypted_on_disk( restored = store._read_json(probe) assert restored is not None assert Workflow.model_validate(restored).name == marker - wrong_store = CheckpointStore(run_dir, key="synthetic-wrong-checkpoint-key") + # Any key a caller passes is replaced by the run's own. + assert CheckpointStore(run_dir, key="synthetic-wrong-key").key == store.key with pytest.raises(crypto.DecryptionError): - wrong_store._read_json(probe) + crypto.decrypt_bytes( + probe.with_name("probe.json.enc").read_bytes(), + at_rest.local_key(), + aad=crypto.CHECKPOINT_AAD, + ) def test_a_recording_only_key_reads_back_from_the_environment( diff --git a/packages/flow/tests/test_at_rest_review_round3.py b/packages/flow/tests/test_at_rest_review_round3.py new file mode 100644 index 0000000000..1e5b96e3fd --- /dev/null +++ b/packages/flow/tests/test_at_rest_review_round3.py @@ -0,0 +1,210 @@ +"""Encryption at rest by default, round 3 of the #2423 review: the paths +around a default encrypted run directory (export, verify, the Python API, +Cloud reporting, retention, ``--no-encrypt`` and the library recorders). + +Synthetic data only; no browser, keychain or network. +""" + +from __future__ import annotations + +import json +import os +from datetime import datetime, timedelta, timezone +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openadapt_flow import at_rest, crypto, sealed_set +from openadapt_flow import key_hierarchy as kh + +TYPED = b"a synthetic typed value" + + +@pytest.fixture +def default_mode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + for name in ( + at_rest.OPT_OUT_ENV, + at_rest.MODE_ENV, + at_rest.ENCRYPT_ENV, + crypto.ENV_KEY, + sealed_set.RECORDING_ENV_KEY, + kh.POLICY_ENV, + ): + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(kh, "MACHINE_POLICY_SOURCES", []) + home = tmp_path / "at-rest-home" + monkeypatch.setenv(at_rest.HOME_ENV, str(home)) + at_rest._reset_for_tests() + yield home + at_rest._reset_for_tests() + + +def _run(root: Path, files: dict[str, bytes]) -> Path: + with sealed_set.writing(root, "run", sealed_set.passphrase_for("run")) as writer: + for rel, data in files.items(): + writer.write(rel, data) + assert sealed_set.read_header(root)["version"] == sealed_set.ENVELOPE_VERSION + return root + + +def test_no_encrypt_lasts_for_one_command(default_mode: Path, tmp_path: Path) -> None: + from openadapt_flow.__main__ import main + + before = {n: os.environ.get(n) for n in (at_rest.ENCRYPT_ENV, at_rest.OPT_OUT_ENV)} + with pytest.raises(FileNotFoundError): # the command fails ... + main( + [ + "compile", + str(tmp_path / "missing"), + "--out", + str(tmp_path / "b"), + "--name", + "x", + "--no-encrypt", + ] + ) + after = {n: os.environ.get(n) for n in (at_rest.ENCRYPT_ENV, at_rest.OPT_OUT_ENV)} + assert after == before # ... and the opt-out did not outlive it + assert at_rest.seals_by_default() is True + + +def test_opted_out_restores_the_environment_on_error(default_mode: Path) -> None: + with pytest.raises(RuntimeError): + with at_rest.opted_out("--no-encrypt"): + assert at_rest.opt_out_reason() is not None + raise RuntimeError("the command failed") + assert at_rest.opt_out_reason() is None + + +def test_records_json_outside_an_encrypted_run_is_refused( + default_mode: Path, tmp_path: Path, monkeypatch +) -> None: + from openadapt_flow.records import run as records_run + + read = SimpleNamespace(model_dump=lambda mode="json": {"value": TYPED.decode()}) + monkeypatch.setattr(records_run, "field_reads_from_report", lambda report: [read]) + monkeypatch.setattr(records_run, "seal_field_reads", lambda reads, receipt: reads) + receipt = tmp_path / "new-receipt-dir" / "receipt.json" + receipt.parent.mkdir() + with pytest.raises(at_rest.AtRestRefused, match="field values"): + records_run.write_sealed_reads(object(), receipt) + assert not (receipt.parent / "records.json").exists() + # Inside the encrypted run directory, the values are sealed. + run = _run(tmp_path / "run", {"report.json": b"{}"}) + out = records_run.write_sealed_reads(object(), run / "receipt.json") + assert out is not None and not out.exists() # only ciphertext on disk + assert TYPED in sealed_set.read_bytes(out) + # The recorded opt-out still allows plaintext, with a ledger line. + monkeypatch.setenv(at_rest.OPT_OUT_ENV, "synthetic test data") + assert records_run.write_sealed_reads(object(), receipt) == ( + receipt.parent / "records.json" + ) + + +def test_local_seal_verify_reads_an_encrypted_runs_report( + default_mode: Path, tmp_path: Path +) -> None: + from openadapt_flow import cli_at_rest, cli_local_seal + + run = _run(tmp_path / "run", {"report.json": b'{"success": true}'}) + assert not (run / "report.json").exists() + assert cli_local_seal._input_report(run / "report.json") == {"success": True} + assert "openadapt_flow.cli_local_seal:_cmd_verify" in cli_at_rest.SEALED_READY + args = SimpleNamespace( + seal=None, + require_anchor=False, + require_timestamp=False, + authorization=None, + ) + # The report reads; what is missing is the Seal itself. + with pytest.raises(cli_local_seal.InputError, match="seal.json"): + cli_local_seal._check_verify_inputs(args, run) + + +def test_the_python_replay_api_reads_an_encrypted_report( + default_mode: Path, tmp_path: Path, monkeypatch +) -> None: + import openadapt_flow.__main__ as cli + from openadapt_flow import api + + run_dir = tmp_path / "run" + + def fake_main(argv): + _run(run_dir, {"report.json": b'{"replayed": true}'}) + return 0 + + class Report: + @staticmethod + def model_validate_json(text: str) -> dict: + return json.loads(text) + + monkeypatch.setattr(cli, "main", fake_main) + monkeypatch.setattr(api, "RunReport", Report) + assert api.replay("bundle", url="http://127.0.0.1:9", run_dir=run_dir) == { + "replayed": True + } + + +def test_cloud_report_ids_live_in_the_sealed_index( + default_mode: Path, tmp_path: Path +) -> None: + from openadapt_flow import hosted + + run = _run(tmp_path / "run", {"report.json": b"{}"}) + first = hosted._client_run_id(run) + assert hosted._client_run_id(run) == first # a retry reports the same run + opened = sealed_set.SealedSet.open(run) + indexed = sealed_set._open_index(run, opened._header, opened._key) + assert ".report_run_id" in indexed # indexed, not merely tolerated + opened.verify_all() + + +def test_retention_refuses_a_passphrase_check_on_a_version_3_run( + default_mode: Path, tmp_path: Path +) -> None: + from openadapt_flow.retention import RetentionError, plan_retention + from tests.test_retention import POLICY + + run = _run(tmp_path / "run", {"report.json": b"{}"}) + with pytest.raises(RetentionError, match="does_not_open_version_3"): + plan_retention( + run, + POLICY, + b"{}", + [], + key="any passphrase at all", + now=datetime.now(timezone.utc) + timedelta(days=1), + ) + + +class _Backend: + """Enough of a backend for constructing a recorder.""" + + page = None + + def screenshot(self): # pragma: no cover - not reached + raise AssertionError + + +def test_the_library_recorder_seals_by_default(default_mode: Path, tmp_path: Path) -> None: + from openadapt_flow.recorder import Recorder + + out = tmp_path / "rec" + recorder = Recorder(_Backend(), out) + assert recorder._sealed_writer is not None and sealed_set.is_sealed(out) + + +def test_an_explicit_none_recorder_is_refused_in_strict_and_ledgered_otherwise( + default_mode: Path, tmp_path: Path, monkeypatch +) -> None: + from openadapt_flow.recorder import Recorder + + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + with pytest.raises(at_rest.AtRestRefused): + Recorder(_Backend(), tmp_path / "a", encryption_key=None) + assert not (tmp_path / "a" / "events.jsonl").exists() + monkeypatch.delenv(at_rest.MODE_ENV) + Recorder(_Backend(), tmp_path / "b", encryption_key=None) + ledger = at_rest.ledger_path().read_text() + assert str(tmp_path / "b") in ledger and "encryption_key=None" in ledger diff --git a/packages/flow/tests/test_desktop_record.py b/packages/flow/tests/test_desktop_record.py index 1d8450be52..1c560a517d 100644 --- a/packages/flow/tests/test_desktop_record.py +++ b/packages/flow/tests/test_desktop_record.py @@ -1184,3 +1184,121 @@ def fake_convert(cap_dir: Path, out_dir: Path, *, params=None) -> Path: announce=False, ) assert not (tmp_path / "raw").exists() + + +def _plain_convert(cap_dir: Path, out_dir: Path, *, params=None) -> Path: + (Path(cap_dir) / "capture.db").write_bytes(b"raw synthetic session") + (Path(out_dir) / "events.jsonl").write_text('{"text": "typed value"}\n') + (Path(out_dir) / "meta.json").write_text("{}") + return Path(out_dir) + + +def test_strict_mode_refuses_direct_capture_whatever_key_is_passed( + tmp_path: Path, monkeypatch +) -> None: + """The raw session is plaintext while it records: strict mode refuses it + before the recorder starts, with an explicit key, None, or the default.""" + from openadapt_flow import at_rest + + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + for key in ("an-explicit-key", None, at_rest.POLICY): + log: list = [] + with pytest.raises(at_rest.AtRestRefused): + record_desktop_capture( + tmp_path / "rec", + recorder_factory=_make(log), + convert=_plain_convert, + stop=lambda: True, + announce=False, + encryption_key=key, + ) + assert log == [] # the recorder never started + + +def test_an_explicit_none_key_is_recorded_in_the_ledger( + tmp_path: Path, monkeypatch +) -> None: + from openadapt_flow import at_rest + + monkeypatch.delenv(at_rest.OPT_OUT_ENV, raising=False) + at_rest._reset_for_tests() + out = record_desktop_capture( + tmp_path / "rec", + recorder_factory=_make([]), + convert=_plain_convert, + stop=lambda: True, + announce=False, + encryption_key=None, + ) + lines = at_rest.ledger_path().read_text().splitlines() + assert any(str(out) in line and "encryption_key=None" in line for line in lines) + + +def test_organization_policy_is_checked_before_capture_starts( + tmp_path: Path, monkeypatch +) -> None: + import base64 + import json + + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec + + from openadapt_flow import at_rest + from openadapt_flow import key_hierarchy as kh + + monkeypatch.delenv(at_rest.OPT_OUT_ENV, raising=False) + monkeypatch.setattr(kh, "MACHINE_POLICY_SOURCES", []) + org = ec.generate_private_key(ec.SECP256R1()).public_key() + spki = org.public_bytes( + serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo + ) + (tmp_path / "unmounted").mkdir() + policy = tmp_path / "policy.json" + policy.write_text( + json.dumps( + { + "schema": kh.POLICY_SCHEMA, + "mode": "org", + "recipients": [ + { + "role": "org", + "type": kh.HPKE_P256, + "public_key": base64.b64encode(spki).decode(), + } + ], + "key_archive": str(tmp_path / "unmounted"), + "max_unarchived": 0, + } + ) + ) + monkeypatch.setenv(kh.POLICY_ENV, str(policy)) + monkeypatch.setenv(kh.TRUST_USER_POLICY_ENV, "1") + log: list = [] + with pytest.raises(Exception, match="not reachable"): + record_desktop_capture( + tmp_path / "rec", + recorder_factory=_make(log), + convert=_plain_convert, + stop=lambda: True, + announce=False, + ) + assert log == [] + + +def test_a_capture_staging_that_survives_is_not_a_success( + tmp_path: Path, monkeypatch +) -> None: + from openadapt_flow import desktop_record + + monkeypatch.setattr( + desktop_record, "_remove_staging", lambda staging: [str(staging / "capture.db")] + ) + with pytest.raises(RuntimeError, match="could not be deleted"): + record_desktop_capture( + tmp_path / "rec", + recorder_factory=_make([]), + convert=_plain_convert, + stop=lambda: True, + announce=False, + encryption_key="a-deployment-key-for-tests", + ) diff --git a/packages/flow/tests/test_key_hierarchy.py b/packages/flow/tests/test_key_hierarchy.py index 990e2beb0d..52aeaaeec5 100644 --- a/packages/flow/tests/test_key_hierarchy.py +++ b/packages/flow/tests/test_key_hierarchy.py @@ -883,3 +883,58 @@ def open_key(hive, subkey): monkeypatch.setattr(kh, "MACHINE_POLICY_SOURCES", ["HKLM\\SOFTWARE\\Denied"]) with pytest.raises(kh.KeyHierarchyError, match="can't be read"): kh.load_policy() + + +def test_a_v3_runs_checkpoints_are_keyed_to_the_run_and_die_with_it( + home, tmp_path, monkeypatch +) -> None: + import shutil + + from pydantic import BaseModel + + from openadapt_flow.runtime.durable.checkpoint import CheckpointStore + + class Bindings(BaseModel): + typed: str + + root, _keychain = home + _p256_policy(tmp_path, monkeypatch) + run = root.parent / "run" + writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) + local = at_rest.local_key() + store = CheckpointStore(run, key=local) # whatever key the caller resolved + assert store.key == sealed_set.store_passphrase_of(writer) != local + (run / "checkpoints").mkdir() + written = store._write_model( + run / "checkpoints" / "s1.json", Bindings(typed=TYPED.decode()) + ) + sealed = written.read_bytes() + assert TYPED not in sealed + with pytest.raises(crypto.CryptoError): # the long-lived key never opens it + crypto.decrypt_bytes(sealed, local, aad=crypto.CHECKPOINT_AAD) + writer.write("report.json", TYPED) + writer.finalize(adopt_external=True) + backup = root.parent / "backup" + shutil.copytree(run, backup) + sealed_set.shred(run) + # Organization mode: the backup's header names a bucket whose every + # tracked key copy is gone, so its checkpoints are gone too. + with pytest.raises(sealed_set.SealedSetError): + CheckpointStore(backup, key=local) + + +def test_a_checkpoint_store_without_a_key_encrypts_by_default(home) -> None: + from pydantic import BaseModel + + from openadapt_flow.runtime.durable.checkpoint import CheckpointStore + + class Bindings(BaseModel): + typed: str + + root, _keychain = home + plain = root.parent / "plain-run" + plain.mkdir() + written = CheckpointStore(plain)._write_model( + plain / "s1.json", Bindings(typed=TYPED.decode()) + ) + assert written.name.endswith(".enc") and TYPED not in written.read_bytes() From 540b1fe43c536cc77415f6ccafed09a4b4ba3adf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 18:00:04 -0500 Subject: [PATCH 20/37] docs: archive marker, archive-only organization mode, shred authentication and run-keyed checkpoints Move the encryption-at-rest changelog section to Unreleased: v3.4.0 shipped without it. --- CAPABILITIES.md | 2 +- packages/flow/CHANGELOG.md | 47 +++++++----- packages/flow/docs/phi_at_rest.md | 84 +++++++++++++++------ packages/flow/openadapt_flow/cli_at_rest.py | 7 +- 4 files changed, 96 insertions(+), 44 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index fcdd3102e3..d76630952e 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -365,7 +365,7 @@ improvising or retrying when something is off. | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | -| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` authenticates the set's header, then destroys its tracked bucket-key copies, in the archive the set was written to (an archive counts only with its marker file), and the run's checkpoints, which are keyed from the run's own data key. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred, unmounted and moved archive, whole-set substitution, backlog race and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](packages/flow/docs/RECEIPTS.md); [vectors](packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 09ec68d12c..2b26f98612 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -17,25 +17,6 @@ ## Unreleased -### Features - -- Effect locations (`openadapt.effect-location/v1`, - `openadapt_flow/effect_location/`): the place a careful person would look - again to see an intended value, stored as pack data. Each record holds the - demonstration path and start condition (`same_screen`, `fresh_navigation`, - `new_session`, `other_channel`), a locator (label, row key or region), the - expected value, a codec (including a `template` codec that reads one - summary row as two values and a `split_date` codec), the expected count - and an optional baseline. `evaluate_all` judges every planned value as - `held`, `refuted` or `not_checked`. A location that can't be reached, - found or read is `not_checked`, never a pass. The check level comes from - the start condition; the receipt word comes from - `check_level.outcome_word` when it is available. The engine holds no - application vocabulary: month names, yes and no words, currency signs and - tables come from the pack. See docs/EFFECT_LOCATION.md. - -## v3.4.0 (2026-11-21) - ### Encryption at rest by default - Recordings (web, the quickstart and tutorial, and desktop once converted), @@ -68,6 +49,34 @@ page and the quickstart read encrypted runs. The receipt page embeds the report, so beside an encrypted run it is logged as a plaintext copy. - Core dependency: `cryptography>=50` (HPKE). The keychain store uses `keyring`, which `pip install openadapt` includes; a bare `openadapt-flow` install needs the `keychain` extra, and otherwise keeps the device key in a 0600 file with a warning. +- Fail-closed key lifecycle: an organization key archive counts as + reachable only with its `.openadapt-key-archive` marker, each record and + header names the archive it went to, and shredding authenticates the + header first and reports complete only once every tracked copy and store + file is gone. Organization mode requires `records: archive`. Durable + checkpoints in an encrypted run are keyed from the run's own data key. + `--no-encrypt` lasts for one command, and the Python recorders follow the + at-rest policy by default. + + +### Features + +- Effect locations (`openadapt.effect-location/v1`, + `openadapt_flow/effect_location/`): the place a careful person would look + again to see an intended value, stored as pack data. Each record holds the + demonstration path and start condition (`same_screen`, `fresh_navigation`, + `new_session`, `other_channel`), a locator (label, row key or region), the + expected value, a codec (including a `template` codec that reads one + summary row as two values and a `split_date` codec), the expected count + and an optional baseline. `evaluate_all` judges every planned value as + `held`, `refuted` or `not_checked`. A location that can't be reached, + found or read is `not_checked`, never a pass. The check level comes from + the start condition; the receipt word comes from + `check_level.outcome_word` when it is available. The engine holds no + application vocabulary: month names, yes and no words, currency signs and + tables come from the pack. See docs/EFFECT_LOCATION.md. + +## v3.4.0 (2026-11-21) ### Features diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index eff260aa01..d72e74ac2c 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -44,8 +44,16 @@ A sealed bundle always runs into a sealed run directory, in every mode. `record`, `compile`, `run` and `replay`, writes plaintext. So does `OPENADAPT_FLOW_PLAINTEXT_AT_REST=''`, which records the reason. Each process prints a one-line warning and adds a ledger line. Strict mode ignores -all of them. Files encrypted earlier still read under the opt-out, with the -key that encrypted them. +all of them. `--no-encrypt` lasts for its one command: an application that +runs Flow in-process gets encryption back for the next one. Files encrypted +earlier still read under the opt-out, with the key that encrypted them. + +From Python, `Recorder`, `InteractiveRecorder` and `record_desktop_capture` +follow the same policy by default. Passing `encryption_key=None` writes a +plaintext recording: strict mode refuses it before anything is written, and +otherwise stderr names it and a ledger line records it. `report-run --receipt +DIR` writes the field values a run read (`records.json`) only inside an +encrypted run directory, or under the opt-out. **Healthcare and other regulated deployments:** set `OPENADAPT_FLOW_AT_REST=strict` and an organization policy @@ -137,7 +145,7 @@ bucket key pair (P-256, one per set) | | Solo (default, no policy) | Organization mode (`mode: org`) | | --- | --- | --- | -| Record | Inside the set's header (`records: inline`), so it travels with backups | `~/.openadapt/keys/buckets/.json` plus a copy in the organization's `key_archive` (`records: archive`); never in the header | +| Record | Inside the set's header (`records: inline`), so it travels with backups | `~/.openadapt/keys/buckets/.json` plus a copy in the organization's `key_archive` (`records: archive`, the only choice in organization mode); never in the header | | Wrapped to | Device viewer key (and runtime key while open), recovery key if one exists | Device viewer key (runtime while open, local copy only), organization keys, recovery key if set | | Lost laptop | Backups open with the recovery key; without one they can't be opened | Every set whose record reached the archive opens with the organization key | | Crypto-shredding | This disk's copy only: a backup still opens with the recovery key | Every tracked copy: the local record (overwritten, then deleted) and the archive copy | @@ -201,21 +209,43 @@ machine one: - In organization mode, a missing or unreadable policy, no active organization recipient, or no `key_archive` stops recording and running. + Organization mode keeps records in the archive only: `records: inline` + is refused there, so shredding always reaches every tracked copy. +- The archive counts as reachable only when an empty file named + `.openadapt-key-archive` is at its root. The administrator creates it + once; Flow never creates the archive folder. An unmounted share (an empty + local folder at the mount point) is therefore never mistaken for the + archive: records are not written there, and a record missing from it is + not taken as deleted. Records are written atomically. +- Each record notes the archive it was sent to, and so does the set's + header (under its MACs). Archiving and shredding use that archive, never + the policy in force later, so moving the archive or switching to solo mode + never leaves a key copy behind. - If the archive is unreachable, records stay local as "not yet archived" - (`at-rest status` counts them), and new sets stop after `max_unarchived`. - `openadapt-flow at-rest archive` sends them once it is back (and the next - new set tries that first), so recording resumes. -- `records: inline` in organization mode is the choice of recovery over - shredding: every header carries the record, wrapped to the organization's - keys, so the organization can open any copy, but shredding reaches only - copies you can delete, as in solo mode. + (`at-rest status` counts them). A new set whose own record can't reach the + archive is refused (and its record destroyed) when more than + `max_unarchived` would then be waiting; `max_unarchived: 0` means every + record must reach the archive before its set is written. Concurrent + writers can't share the last slot. `openadapt-flow at-rest archive` sends + waiting records once the archive is back, and the next new set that + reaches it sends them too, so recording resumes. +- Machine policy sources are platform-specific: macOS reads the managed + preferences profile and `/etc/openadapt/policy.json`, Windows reads only + HKLM, Linux reads only `/etc/openadapt/policy.json`. Every policy file + must be owned by root and writable by root only, checked on the file + actually read. A registry key the account can't read is an error, never + "no policy". - Only a local or mounted path (`file://`) is supported as `key_archive` so far; `s3://` and `smb://` refuse. - OpenAdapt Cloud never distributes the organization's key or holds any key. A reviewer opens a set with the archive copy of its record in `~/.openadapt/keys/buckets/` and `OPENADAPT_ORG_KEY_FILE` (a PEM private -key). Unwrapping through the KMS itself (`Decrypt`, `DeriveSharedSecret`) is +key). An organization key never opens a record that a set's own header +carries: anyone who knows the organization's public key could make such a +set. A record from a header opens only with this computer's device keys or a +recovery key. If the device key's keychain entry is missing, Flow still +tries the recovery code and organization key before it reports that. Unwrapping through the KMS itself (`Decrypt`, `DeriveSharedSecret`) is not built yet. ### Solo recovery @@ -233,8 +263,11 @@ encrypted runs can't be opened. organization mode: Flow writes the version 1 header it always wrote, keyed by that passphrase (scrypt N=2^15, r=8, p=1). They are deprecated. - `~/.openadapt/keys/at-rest.key` (mode 0600), the key earlier versions - made, still opens what it encrypted, and is still the local passphrase of - durable checkpoints and attended state, which keep their own containers. + made, still opens what it encrypted. It is the local passphrase of + durable checkpoints and attended state in a plaintext or version 1 or 2 + run directory. In a version 3 run, durable checkpoints and rollback state + use a key derived from the run's own data key instead, so shredding the + run reaches them, backups included. - Version 1 and 2 sets, and plaintext folders, still read. `openadapt-flow at-rest status` shows the mode, the policy source, the device @@ -243,13 +276,18 @@ count. It prints no key material. ## Crypto-shredding -`openadapt-flow at-rest shred DIR --yes` destroys the set's bucket key: the -local record is overwritten and deleted, and the archive copy deleted. If the -archive copy can't be deleted (an offline or read-only archive), the command -says the shred is not complete and exits non-zero; running it again, or -`at-rest archive`, finishes it once the archive is reachable. It -also drops the record from the header, and deletes the durable checkpoints -and other stores' ciphertext inside the set. It returns a shred record +`openadapt-flow at-rest shred DIR --yes` first authenticates the set's +header with a key this computer holds, so a changed header can't point the +deletion at another set's key; a set no key here opens is refused, and +nothing is destroyed. It then destroys the set's bucket key: the local +record is overwritten and deleted, and the copy deleted from the archive the +set was written to. If that copy can't be deleted (an offline, unmounted or +read-only archive), the command says the shred is not complete and exits +non-zero; running it again on the same computer, or `at-rest archive`, +finishes it once the archive is reachable. It also drops the record from the +header, and deletes the durable checkpoints and other stores' ciphertext +inside the set. The header says complete only after the last of these, so an +interrupted shred is finished by running it again. It returns a shred record (bucket id, time, copies destroyed). The library call is `openadapt_flow.sealed_set.shred`, for a retention job. In solo mode it reaches only this disk's copy, and says so. @@ -282,7 +320,11 @@ The desktop recorders capture through openadapt-capture, which writes its raw session (input database and screen video) in plaintext while recording, in a private 0700 folder beside the output. When recording stops, Flow converts it, encrypts the converted recording into the output, and deletes -the raw session and the converted plaintext. Until then, and if the process +the raw session and the converted plaintext. If any of it can't be deleted, +the recording fails and names the folder, rather than return as if it were +encrypted. The organization policy (recipients, archive and backlog, +hardware key) is checked before capture starts, and strict mode refuses +desktop capture, whatever key a caller passes. Until then, and if the process is killed before it converts, they are plaintext on disk; deleting them is not a secure erase. So crypto-shredding can't be claimed for a desktop recording (NIST SP 800-88r2 3.2.2). Record on an encrypted volume. Encrypting inside the diff --git a/packages/flow/openadapt_flow/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py index 582cb00c67..2e24441e72 100644 --- a/packages/flow/openadapt_flow/cli_at_rest.py +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -124,9 +124,10 @@ def _cmd_shred(args: argparse.Namespace) -> int: if record.get("complete") is False: print( f"at-rest shred: NOT COMPLETE for {root}: destroyed {copies}, but the " - "organization archive's copy of its key could not be deleted (offline " - "or read-only?). Run this again, or `openadapt-flow at-rest archive`, " - "once the archive is reachable.", + "copy of its key in the organization archive it was written to could " + "not be deleted (offline, unmounted or read-only?). Run this again on " + "this computer, or `openadapt-flow at-rest archive`, once that " + "archive is reachable.", file=sys.stderr, ) return 1 From 9eaca4eec84f3bbbce1ca8947a748533aaf4dec7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 18:03:30 -0500 Subject: [PATCH 21/37] Regenerate the flow CLI surface snapshot (at-rest commands, --no-encrypt) and llms-full.txt --- llms-full.txt | 35 +-- packages/flow/tests/fixtures/cli_surface.json | 244 +++++++++++++++++- 2 files changed, 241 insertions(+), 38 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index 701fe9ef78..ada7ba2711 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -826,7 +826,7 @@ improvising or retrying when something is off. | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | -| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` destroys a set's tracked bucket-key copies. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#key-hierarchy) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` authenticates the set's header, then destroys its tracked bucket-key copies, in the archive the set was written to (an archive counts only with its marker file), and the run's checkpoints, which are keyed from the run's own data key. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred, unmounted and moved archive, whole-set substitution, backlog race and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECEIPTS.md); [vectors](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | @@ -2450,39 +2450,6 @@ automation into an independently certified transaction system. ## What changed in openadapt-flow 3.4.0 -### Encryption at rest by default - -- Recordings (web, the quickstart and tutorial, and desktop once converted), - compiled bundles and every run directory (report, step screenshots, crops, - frames, evidence, `REPORT.md`) are now encrypted at rest by default, with - no setup, as sealed-set version 3: a data key per set, wrapped with HPKE - (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, and files as - Tink AES-256-GCM-HKDF 1 MiB streams. The bucket key is wrapped to the - device runtime key (only while the set is written; bundles keep it), the - device viewer key, organization keys and a recovery key. -- Organization mode, from a machine policy (MDM profile, Group Policy, a - root-owned `/etc/openadapt/policy.json`): organization recipients (P-256 - or RSA-OAEP-3072) and a key archive are required, and recording stops - without them. Solo users can make a recovery key - (`openadapt-flow at-rest recovery create`). -- `openadapt-flow at-rest status` shows the keys and policy; - `at-rest shred` destroys a set's tracked bucket-key copies. -- The device key is a software P-256 key in the OS keychain through - `keyring` (a 0600 file with a warning where there is none). Secure - Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test - doubles, not built yet. -- A configured `OPENADAPT_BUNDLE_KEY` or `OPENADAPT_RECORDING_KEY` still wins - outside organization mode (deprecated), and `~/.openadapt/keys/at-rest.key` - keeps working. Version 1 and 2 sets and plaintext folders still read. -- `OPENADAPT_ENCRYPT_AT_REST=0`, or `--no-encrypt` on `record`, `compile`, - `run` and `replay`, turns it off with a one-line warning and a ledger line. -- Receipts (`seal.json`, `receipt.*`, `public-seal.json`) stay plaintext and - are now written for encrypted runs too; their digests are over the - plaintext `report.json`. `seal verify`, `inspect report-run`, the receipt - page and the quickstart read encrypted runs. The receipt page embeds the - report, so beside an encrypted run it is logged as a plaintext copy. -- Core dependency: `cryptography>=50` (HPKE). The keychain store uses `keyring`, which `pip install openadapt` includes; a bare `openadapt-flow` install needs the `keychain` extra, and otherwise keeps the device key in a 0600 file with a warning. - ### Features - Agent-to-agent handoffs. `openadapt-flow handoff send` attaches a run's diff --git a/packages/flow/tests/fixtures/cli_surface.json b/packages/flow/tests/fixtures/cli_surface.json index bf392fb273..f028eb4066 100644 --- a/packages/flow/tests/fixtures/cli_surface.json +++ b/packages/flow/tests/fixtures/cli_surface.json @@ -1,7 +1,7 @@ { "columns": 100, "help": { - "openadapt-flow": "usage: openadapt-flow [-h] [--version] {command} ...\n\nRecord a task and compile it into a program that runs on this computer. With a record check\nconfigured, a governed run confirms each save by reading the record back, and a run that can't\nconfirm a save stops and asks a person. When the screen changes, it finds the same field again or\nstops, and a lasting fix needs a person's approval.\n\noptions:\n -h, --help show this help message and exit\n --version Show the version and exit\n\ncommands:\n {command}\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n\nNew here? Run 'openadapt-flow demo' to see a checked run and a stopped run side by side on one\npage.\n\nLegacy commands (original spellings):\n admit\n api\n approve\n approve-sanitized\n approver-grant\n attach-seal\n bench\n benchmark\n bind-record-checks\n browser-accessibility\n business-decisions\n certify\n check\n cleanup\n compile\n compile-agent\n compose\n confirm-surfaces\n connect\n connector\n console\n countersign\n deferred\n demo\n demo-record\n disambiguate\n emit-mcp\n emit-skill\n encrypt\n exceptions\n explain\n fleet\n flight\n for-each\n guard\n handoff\n hooks\n induce\n intake\n item-approval\n jit\n known-ids\n learn\n ledger\n lint\n local-seal\n login\n materialize-approved\n narration\n no-outbound\n plan\n process\n propose-qualification\n proxy\n pull\n push\n qualify\n readiness\n receipt\n reconcile\n record\n redact-report\n repair\n replay\n report-break\n report-run\n resume\n review-sanitized\n rollback\n route\n run\n sanitize\n scaffold-verifier\n sections\n serve-execute\n serve-reward\n service\n shadow\n silent-saves\n skill\n teach\n teach-authorization\n teach-branch\n triage\n tutorial\n undo\n validate-hosted\n variants\n verify-run\n visualize\n wrap-dispatch\n", + "openadapt-flow": "usage: openadapt-flow [-h] [--version] {command} ...\n\nRecord a task and compile it into a program that runs on this computer. With a record check\nconfigured, a governed run confirms each save by reading the record back, and a run that can't\nconfirm a save stops and asks a person. When the screen changes, it finds the same field again or\nstops, and a lasting fix needs a person's approval.\n\noptions:\n -h, --help show this help message and exit\n --version Show the version and exit\n\ncommands:\n {command}\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n\nNew here? Run 'openadapt-flow demo' to see a checked run and a stopped run side by side on one\npage.\n\nLegacy commands (original spellings):\n admit\n api\n approve\n approve-sanitized\n approver-grant\n at-rest\n attach-seal\n bench\n benchmark\n bind-record-checks\n browser-accessibility\n business-decisions\n certify\n check\n cleanup\n compile\n compile-agent\n compose\n confirm-surfaces\n connect\n connector\n console\n countersign\n deferred\n demo\n demo-record\n disambiguate\n emit-mcp\n emit-skill\n encrypt\n exceptions\n explain\n fleet\n flight\n for-each\n guard\n handoff\n hooks\n induce\n intake\n item-approval\n jit\n known-ids\n learn\n ledger\n lint\n local-seal\n login\n materialize-approved\n narration\n no-outbound\n plan\n process\n propose-qualification\n proxy\n pull\n push\n qualify\n readiness\n receipt\n reconcile\n record\n redact-report\n repair\n replay\n report-break\n report-run\n resume\n review-sanitized\n rollback\n route\n run\n sanitize\n scaffold-verifier\n sections\n serve-execute\n serve-reward\n service\n shadow\n silent-saves\n skill\n teach\n teach-authorization\n teach-branch\n triage\n tutorial\n undo\n validate-hosted\n variants\n verify-run\n visualize\n wrap-dispatch\n", "openadapt-flow admit": "usage: openadapt-flow admit [-h] {run,decide,status} ...\n\npositional arguments:\n {run,decide,status}\n run Compile, induce, propose checks, and stop once for a person's decision (the\n default form: `admit `)\n decide Show a stopped admission's summary and decide it (a person, at a terminal)\n status Print admitted vs not-admitted for Flow from the public ledger. Never mints\n a signature.\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow run --task-admit\n", "openadapt-flow admit decide": "usage: openadapt-flow admit decide [-h] [--by BY] admission\n\npositional arguments:\n admission Admission directory from `admit`\n\noptions:\n -h, --help show this help message and exit\n --by BY Your name for the record\n\nAlso available as: openadapt-flow run --task-admit decide\n", "openadapt-flow admit run": "usage: openadapt-flow admit run [-h] [--candidate ID] [--candidates-root CANDIDATES_ROOT] --out\n OUT --name NAME [--policy-pack {community,cloud,regulated}]\n [--by BY]\n [recordings ...]\n\npositional arguments:\n recordings Recording directories (or compiled bundles) of the same task\n\noptions:\n -h, --help show this help message and exit\n --candidate ID A shadow candidate id under --candidates-root, or its folder. Its\n recordings/ folder is used when no recordings are given\n --candidates-root CANDIDATES_ROOT\n Where shadow candidates are kept (default: ./shadow-candidates)\n --out OUT New admission directory\n --name NAME Workflow name\n --policy-pack {community,cloud,regulated}\n --by BY Your name for the record (default: your login name)\n\nAlso available as: openadapt-flow run --task-admit run\n", @@ -15,6 +15,12 @@ "openadapt-flow approver-grant": "usage: openadapt-flow approver-grant [-h] {sign,verify} ...\n\npositional arguments:\n {sign,verify}\n sign Sign a grant with your policy-signer key\n verify Check a signed grant against the registry\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup approver-grant\n", "openadapt-flow approver-grant sign": "usage: openadapt-flow approver-grant sign [-h] --key KEY --out OUT [--key-dir KEY_DIR] grant\n\npositional arguments:\n grant Unsigned openadapt-flow/approver-grant/v1 JSON\n\noptions:\n -h, --help show this help message and exit\n --key KEY Your encrypted policy-signer key\n --out OUT\n --key-dir KEY_DIR\n\nAlso available as: openadapt-flow setup approver-grant sign\n", "openadapt-flow approver-grant verify": "usage: openadapt-flow approver-grant verify [-h] [--key-dir KEY_DIR] grant\n\npositional arguments:\n grant Signed grant JSON\n\noptions:\n -h, --help show this help message and exit\n --key-dir KEY_DIR\n\nAlso available as: openadapt-flow setup approver-grant verify\n", + "openadapt-flow at-rest": "usage: openadapt-flow at-rest [-h] {status,archive,recovery,shred} ...\n\npositional arguments:\n {status,archive,recovery,shred}\n status Where the keys are and who can open new runs\n archive Send key records and pending shreds to the organization archive\n recovery The solo recovery key\n shred Destroy an encrypted set's bucket key; nobody can open it after\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup at-rest\n", + "openadapt-flow at-rest archive": "usage: openadapt-flow at-rest archive [-h]\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup at-rest archive\n", + "openadapt-flow at-rest recovery": "usage: openadapt-flow at-rest recovery [-h] {create} ...\n\npositional arguments:\n {create}\n create Make a recovery key; the code is shown once\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup at-rest recovery\n", + "openadapt-flow at-rest recovery create": "usage: openadapt-flow at-rest recovery create [-h] [--replace]\n\noptions:\n -h, --help show this help message and exit\n --replace\n\nAlso available as: openadapt-flow setup at-rest recovery create\n", + "openadapt-flow at-rest shred": "usage: openadapt-flow at-rest shred [-h] [--yes] dir\n\npositional arguments:\n dir The encrypted directory\n\noptions:\n -h, --help show this help message and exit\n --yes Confirm; this can't be undone\n\nAlso available as: openadapt-flow setup at-rest shred\n", + "openadapt-flow at-rest status": "usage: openadapt-flow at-rest status [-h] [--json]\n\noptions:\n -h, --help show this help message and exit\n --json\n\nAlso available as: openadapt-flow setup at-rest status\n", "openadapt-flow attach-seal": "usage: openadapt-flow attach-seal [-h] --execution-id EXECUTION_ID [--cloud-url CLOUD_URL] run_dir\n\npositional arguments:\n run_dir Run directory holding a VERIFIED report.json\n\noptions:\n -h, --help show this help message and exit\n --execution-id EXECUTION_ID\n Cloud Execute execution id\n --cloud-url CLOUD_URL\n Cloud base URL (or OPENADAPT_CLOUD_URL; default https://app.openadapt.ai)\n\nAlso available as: openadapt-flow verify attach-seal\n", "openadapt-flow bench": "usage: openadapt-flow bench [-h] [--n N] [--drift DRIFT] --run-root RUN_ROOT [--param K=V]\n [--headed]\n bundle\n\npositional arguments:\n bundle Workflow bundle directory\n\noptions:\n -h, --help show this help message and exit\n --n N Number of iterations\n --drift DRIFT Comma-separated drift modes forwarded to the demo URL\n --run-root RUN_ROOT Directory for per-iteration runs\n --param K=V Parameter substitution (repeatable)\n --headed Run the browser headed\n\nAlso available as: openadapt-flow research flow-bench\n", "openadapt-flow benchmark": "usage: openadapt-flow benchmark [-h] [--n-compiled N_COMPILED] [--n-agent N_AGENT] [--out OUT]\n [--note-text NOTE_TEXT] [--headed]\n\noptions:\n -h, --help show this help message and exit\n --n-compiled N_COMPILED\n Compiled-replay iterations\n --n-agent N_AGENT Agent iterations\n --out OUT Output directory for results.json / BENCHMARK.md / chart\n --note-text NOTE_TEXT\n Note text both arms enter\n --headed Run the browsers headed\n\nAlso available as: openadapt-flow research benchmark\n", @@ -30,7 +36,7 @@ "openadapt-flow check show": "usage: openadapt-flow check show [-h] [--json] bundle\n\npositional arguments:\n bundle Bundle directory\n\noptions:\n -h, --help show this help message and exit\n --json\n\nAlso available as: openadapt-flow verify check show\n", "openadapt-flow cleanup": "usage: openadapt-flow cleanup [-h] {qualify} ...\n\npositional arguments:\n {qualify}\n qualify Stop the run after every step on a declared test copy, clean up, and check the start\n screen comes back\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup cleanup\n", "openadapt-flow cleanup qualify": "usage: openadapt-flow cleanup qualify [-h] --config CONFIG [--from-recording FROM_RECORDINGS]\n [--work-dir WORK_DIR] [--report REPORT] [--no-write]\n bundle\n\npositional arguments:\n bundle Workflow bundle directory\n\noptions:\n -h, --help show this help message and exit\n --config CONFIG Deployment file that declares a test copy (test_copy.declared: true)\n --from-recording FROM_RECORDINGS\n Another compiled bundle whose cancel or close controls to use\n --work-dir WORK_DIR Keep the test-copy runs here\n --report REPORT Write the report (JSON) here\n --no-write Qualify, but don't store it\n\nAlso available as: openadapt-flow setup cleanup qualify\n", - "openadapt-flow compile": "usage: openadapt-flow compile [-h] --out OUT --name NAME [--accept-params NAME1,NAME2]\n [--params-from FILE] [--no-confirm-params] [--pixel-verify-enabled]\n recording\n\npositional arguments:\n recording Recording directory\n\noptions:\n -h, --help show this help message and exit\n --out OUT Output bundle directory\n --name NAME Workflow name\n --accept-params NAME1,NAME2\n Non-interactive confirm pass: accept these flagged field-label parameter\n proposals as-is (comma-separated proposed names; see param_proposals.json\n in the bundle). Proposals not listed stay demonstrated constants. Unknown\n names fail loud.\n --params-from FILE Non-interactive confirm pass: JSON decision file mapping each proposed\n name to {\"action\": \"confirm\"|\"rename\"|\"secret\"|\"constant\", \"name\": \"\"}. Unlisted proposals stay constants (fail-closed).\n --no-confirm-params Skip the interactive parameter review even on a TTY; flagged proposals\n stay demonstrated constants.\n --pixel-verify-enabled\n The runtime that will run this bundle sets runtime.pixel_verify_enabled.\n Lets the compiler give an unlabeled button a pixel identifier crop as its\n identity check. Without it the compiler doesn't, because a crop that can't\n be verified halts an irreversible step on every run.\n\nRelated operations (immediately after the task name): --induce, --compose, --variants, --scaffold-\nverifier, --bind-record-checks, --disambiguate, --sanitize, --materialize-approved, --api, --jit,\n--agent\n", + "openadapt-flow compile": "usage: openadapt-flow compile [-h] --out OUT --name NAME [--accept-params NAME1,NAME2]\n [--params-from FILE] [--no-confirm-params] [--pixel-verify-enabled]\n [--no-encrypt]\n recording\n\npositional arguments:\n recording Recording directory\n\noptions:\n -h, --help show this help message and exit\n --out OUT Output bundle directory\n --name NAME Workflow name\n --accept-params NAME1,NAME2\n Non-interactive confirm pass: accept these flagged field-label parameter\n proposals as-is (comma-separated proposed names; see param_proposals.json\n in the bundle). Proposals not listed stay demonstrated constants. Unknown\n names fail loud.\n --params-from FILE Non-interactive confirm pass: JSON decision file mapping each proposed\n name to {\"action\": \"confirm\"|\"rename\"|\"secret\"|\"constant\", \"name\": \"\"}. Unlisted proposals stay constants (fail-closed).\n --no-confirm-params Skip the interactive parameter review even on a TTY; flagged proposals\n stay demonstrated constants.\n --pixel-verify-enabled\n The runtime that will run this bundle sets runtime.pixel_verify_enabled.\n Lets the compiler give an unlabeled button a pixel identifier crop as its\n identity check. Without it the compiler doesn't, because a crop that can't\n be verified halts an irreversible step on every run.\n --no-encrypt Write this command's output in plaintext (recorded in\n ~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is encrypted\n by default; same as OPENADAPT_ENCRYPT_AT_REST=0. Ignored under\n OPENADAPT_FLOW_AT_REST=strict\n\nRelated operations (immediately after the task name): --induce, --compose, --variants, --scaffold-\nverifier, --bind-record-checks, --disambiguate, --sanitize, --materialize-approved, --api, --jit,\n--agent\n", "openadapt-flow compile-agent": "usage: openadapt-flow compile-agent [-h] [--param NAME=VALUE] [--url URL]\n [--backend {web,windows,macos,linux,rdp,citrix}]\n [--config CONFIG] [--verify VERIFY] [--expect FIELD=VALUE]\n [--on-screen TEXT] [--allow-origin URL] [--allow-text TEXT]\n [--write-adapter MODULE:ATTR]\n [--teach-authorization STATEMENT]\n [--approver-root APPROVER_ROOT] [--agent AGENT]\n [--vision {code,selective,every_turn}] [--model MODEL]\n [--effort EFFORT] [--max-cost MAX_COST] [--task-id TASK_ID]\n [--cache CACHE] [--key-dir KEY_DIR] [--policy POLICY]\n [--drop-field DROP_FIELD] [--admit-key ADMIT_KEY]\n [--admission-policy ADMISSION_POLICY]\n [--canary-param NAME=VALUE] [--admit-as ADMIT_AS]\n [--hold | --no-hold] [--show-browser] [--json]\n prompt [task_dir]\n\n``openadapt-flow compile-agent``: compile an agent's first verified run.\n\nA computer-use agent does the task once in the app at ``--url``. That run is\nreal: the agent makes the entry in that app. Point ``--url`` at a test copy\nwith test records. If the system of record shows exactly the record the task\nnamed, the run is compiled into a program that later runs with no model calls.\n\n::\n\n openadapt-flow compile-agent \"Open the referral for Jane Sample and save this note: {note}\" \\\n --url http://localhost:8080/#tasks --verify verify.yaml \\\n --param note=\"Follow up in two weeks\" \\\n --expect patient_id=p1 --on-screen \"Jane Sample\" --on-screen \"MRN P1\" \\\n --admit-key agent.pem --admission-policy signed-policy.json\n\n openadapt-flow compile-agent run --param note=\"Recheck in ten days\"\n\n openadapt-flow compile-agent admit --admit-as \"Dana Reviewer\" \\\n --canary-param note=\"Canary test note\"\n\n``admit`` is for a draft that waits for a person, such as one an agent taught\nover MCP (``openadapt-agent serve --teach``): at an interactive terminal the\nperson confirms the proposed record checks if nobody has yet, reviews the\nsteps, attends the canary and admits. ``--admit-key`` admits with a\nregistered key instead, after the checks are confirmed.\n\nThe command is re-entrant. Run it again with the same arguments and it picks\nup where it stopped: the agent runs only when the task has no draft and no\nadmitted program. Confirming the proposed record checks is a person's step at\nan interactive terminal; without one, the command stops with the draft\nwaiting and says so.\n\npositional arguments:\n prompt the task, with {name} for each --param; \"run\" to run a compiled task;\n \"admit\" to confirm and admit a waiting draft; or \"emit\" / \"re-emit\" to re-\n emit mcp/server.py and skills for an admitted task\n task_dir with run, admit, emit, or re-emit: the compiled task directory\n\noptions:\n -h, --help show this help message and exit\n --param NAME=VALUE\n --url URL the app's entry URL; the agent makes real entries there, so use a test\n copy\n --backend {web,windows,macos,linux,rdp,citrix}\n the surface the app runs on, as for record --backend. A desktop, RDP or\n Citrix app is named by --config instead\n --config CONFIG deployment.yaml; a non-web backend section (windows, macos, linux, rdp,\n citrix) is the app the agent drives, built by build_backend\n --verify VERIFY verify.yaml whose verifier: section reads the system of record\n --expect FIELD=VALUE a field the new record must have, such as patient_id=p1\n --on-screen TEXT the record's identity as the screen shows it; checked before every save\n --allow-origin URL another origin run 1's browser may reach (a sign-in host, a CDN); every\n origin but the app's is refused otherwise\n --allow-text TEXT more text the agent may type in run 1 (a test user name); it may always\n type the inputs, the --expect values and the --on-screen text\n --write-adapter MODULE:ATTR\n the app's write adapter (openadapt_flow.teach_scope.WriteAdapter): run 1's\n writes are read before they are sent\n --teach-authorization STATEMENT\n a person's signed teach authorization (openadapt-flow teach-\n authorization): run 1 is scoped by it, and the flags may only narrow it.\n Without one the draft is refused at admission\n --approver-root APPROVER_ROOT\n the approver root the teach authorization's signer is checked under\n (default OPENADAPT_APPROVER_ROOT)\n --agent AGENT claude (default), or a JSON file of scripted steps or code-action scripts\n (no model calls)\n --vision {code,selective,every_turn}\n code (default): act through one terminal-style tool, every save read back\n (docs/CODE_AS_ACTION.md); selective: the structural listing; every_turn: a\n screenshot after every action\n --model MODEL model id (default claude-sonnet-5-5 for code, claude-opus-5-5 otherwise)\n --effort EFFORT\n --max-cost MAX_COST USD cap for run 1\n --task-id TASK_ID\n --cache CACHE\n --key-dir KEY_DIR JIT admission key directory\n --policy POLICY Flow risk policy\n --drop-field DROP_FIELD\n a proposed match field to leave out of the checks (changes every save)\n --admit-key ADMIT_KEY\n encrypted key of a registered admitter, or of an agent with --admission-\n policy\n --admission-policy ADMISSION_POLICY\n signed admission policy for --admit-key\n --canary-param NAME=VALUE\n the value each canary saves; a canary is a real save on the record\n --expect names, so use a value that is safe there (required to admit)\n --admit-as ADMIT_AS a person who reviews, attends the canary and admits at this terminal\n --hold, --no-hold ask at this terminal before every save in run 1 (default: on at a\n terminal)\n --show-browser\n --json print the result as JSON\n\nAlso available as: openadapt-flow compile --agent\n", "openadapt-flow compose": "usage: openadapt-flow compose [-h] --child NAME=PATH [--handoff FROM.source=TO.target]\n [--after NAME=PRED[,PRED]] [--allow-halt NAME=OUTCOME] --out OUT\n [--name NAME]\n\noptions:\n -h, --help show this help message and exit\n --child NAME=PATH Named compiled child bundle (repeat; at least two)\n --handoff FROM.source=TO.target\n Verified fact copied from a predecessor effect-bound parameter into a\n successor parameter. Repeatable. Missing evidence HALTs.\n --after NAME=PRED[,PRED]\n Explicit DAG predecessors for NAME. Omit to run children in --child order.\n --allow-halt NAME=OUTCOME\n Let NAME start when a predecessor ended OUTCOME instead of VERIFIED\n (HALTED, FAILED, ...). VERIFIED is always allowed.\n --out OUT Output composition directory\n --name NAME Composition name\n\nAlso available as: openadapt-flow compile --compose\n", "openadapt-flow confirm-surfaces": "usage: openadapt-flow confirm-surfaces [-h] [--yes] recording\n\npositional arguments:\n recording Recording directory\n\noptions:\n -h, --help show this help message and exit\n --yes Confirm without asking\n\nAlso available as: openadapt-flow record confirm-surfaces\n", @@ -225,7 +231,7 @@ "openadapt-flow repair stage": "usage: openadapt-flow repair stage [-h] [--store STORE] candidate_id\n\npositional arguments:\n candidate_id\n\noptions:\n -h, --help show this help message and exit\n --store STORE Repair store directory (candidates, staged bundles by hash, and the atomic\n ACTIVE.json pointer). Default: repair-store/\n", "openadapt-flow repair standard-changes": "usage: openadapt-flow repair standard-changes [-h] [--day DAY] [--json] [--store STORE]\n\noptions:\n -h, --help show this help message and exit\n --day DAY UTC day, YYYY-MM-DD (default: today)\n --json Print the ledger rows as JSON\n --store STORE Repair store directory (candidates, staged bundles by hash, and the atomic\n ACTIVE.json pointer). Default: repair-store/\n", "openadapt-flow repair status": "usage: openadapt-flow repair status [-h] [--store STORE]\n\noptions:\n -h, --help show this help message and exit\n --store STORE Repair store directory (candidates, staged bundles by hash, and the atomic\n ACTIVE.json pointer). Default: repair-store/\n", - "openadapt-flow replay": "usage: openadapt-flow replay [-h] [--stop-before-effect] [--url URL] [--demo-app] [--drift DRIFT]\n [--run-dir RUN_DIR] [--param K=V] [--params-file PARAMS_FILE]\n [--local-grounding] [--allow-model-grounding]\n [--save-healed-to SAVE_HEALED_TO] [--headed] [--record-video DIR]\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 [--surface NAME=KIND[:TARGET]] [--browser-cdp-endpoint URL]\n [--browser-page-url URL]\n [--invocation-challenge INVOCATION_CHALLENGE] [--config-sha256 HEX]\n [--config YAML]\n [--effects-kind {none,rest,fhir,sql,file,document-hash}]\n [--effects-base-url EFFECTS_BASE_URL]\n [--effects-records-path EFFECTS_RECORDS_PATH]\n [--effects-root EFFECTS_ROOT] [--api-actuator]\n [--api-base-url API_BASE_URL] [--durable]\n [--worklist [RELATION=]FILE] [--workers N] [--readback-window K]\n [--attest-contract PATH] [--attest-sign-key PATH]\n [--attest-audit-log PATH] [--attest-pre-state PATH]\n bundle\n\npositional arguments:\n bundle Workflow bundle directory\n\noptions:\n -h, --help show this help message and exit\n --stop-before-effect Check it without application input: observe a prefilled screen, then stop\n before the first input. Unproved prefixes refuse; web requires an\n attached, already-open page.\n --url URL URL of the target app\n --demo-app Serve the bundled demo app and replay against it (for a bundle recorded on\n it, such as the tutorial's)\n --drift DRIFT Comma-separated demo drift modes (theme,move,rename,modal) to demonstrate\n bounded drift resolution; only with --demo-app\n --run-dir RUN_DIR Run output directory (default: runs/replay- under the\n current directory)\n --param K=V Parameter substitution (repeatable)\n --params-file PARAMS_FILE\n JSON object of parameter bindings; keeps values out of process arguments\n for managed execution\n --local-grounding Pixel surfaces (Citrix, RDP, VNC): find icons and unlabeled controls again\n after a display-scale, zoom, font or theme change with a local model.\n Look-alikes halt the step. In process, no outbound calls; the pinned 24 MB\n weights are fetched once.\n --allow-model-grounding\n EGRESS OPT-IN (PHI audit REM-3): permit wiring an off-box model grounder /\n identity-VLM / state-verifier (a paid API or an on-prem VLM appliance via\n OPENADAPT_FLOW_VLM_URL). Screenshots may leave the box. Off by default:\n replay is fully local with zero outbound calls.\n --save-healed-to SAVE_HEALED_TO\n Write the healed bundle to this directory\n --headed Run the browser headed\n --record-video DIR OPT-IN: capture a WebM video of the replay session into DIR (default: off;\n no effect on the run directory or report)\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 --surface NAME=KIND[:TARGET]\n Multi-surface bundles: bind a backend to the backend surface NAME\n (repeatable). KIND defaults to the kind the bundle declares; TARGET fills\n that kind's target (web: URL, windows: agent URL, macos: app, linux: app,\n rdp: host, citrix: client window). NAME=TARGET alone is accepted. Other\n fields go in the config's surfaces: map. Browser tabs and popups need no\n binding. See docs/MULTI_SURFACE.md.\n --browser-cdp-endpoint URL\n Run in an already-running, signed-in local Chromium through its loopback\n DevTools endpoint (for example, http://127.0.0.1:9222) instead of\n launching a new, signed-out browser. The run binds the one open tab on the\n --url origin, starts from the screen it shows, and never navigates or\n closes the browser. Overrides backend.browser_cdp_endpoint from --config.\n --browser-page-url URL\n Exact current URL of the tab to run in, when more than one open tab has\n the --url origin. Requires --browser-cdp-endpoint.\n --invocation-challenge INVOCATION_CHALLENGE\n Non-authority freshness challenge for the local Standard producer.\n --config-sha256 HEX The SHA-256 of --config's bytes. Flow opens the file once (not through a\n symlink; it must be a regular file), refuses it if the digest differs, and\n from then on parses only those bytes whenever this command loads that\n path, so replacing the file, or a symlink put in its place, changes\n nothing\n --config YAML Deployment config YAML wiring backend / actuation / effects / runtime /\n policy (see docs/deployment.example.yaml). Direct flags below override\n individual fields.\n --effects-kind {none,rest,fhir,sql,file,document-hash}\n System-of-record EffectVerifier to wire so consequential writes are\n verified against the real record (not the screen). rest needs --effects-\n records-path; the fhir/sql/file kinds need their config fields\n (resource_type and field_paths, sql_query, root, ...) from a --config\n deployment YAML\n --effects-base-url EFFECTS_BASE_URL\n Base URL for the rest / fhir effect verifier\n --effects-records-path EFFECTS_RECORDS_PATH\n Path whose GET returns the app's records (rest effect verifier)\n --effects-root EFFECTS_ROOT\n Document-store root for the document-hash effect verifier\n --api-actuator Wire the API/tool actuation tier: a step carrying an ApiBinding is\n performed via the API (deterministic, $0) and confirmed by the effect\n verifier, skipping the GUI\n --api-base-url API_BASE_URL\n Base URL for the API actuator (implies --api-actuator)\n --durable Enable the Tier-3 durable runtime: checkpoint each verified step and\n durably PAUSE on halt, so the run is resumable via `resume` (never re-\n performing a confirmed write)\n --worklist [RELATION=]FILE\n CSV/JSON worklist of parameter rows driving a PROGRAM bundle's loop over a\n relation (repeatable). 'RELATION=FILE' binds the file to that relation; a\n bare 'FILE' binds to the program's sole loop relation.\n --workers N Run a worklist program's items on N workers at once, each in its own\n signed-in session (docs/THROUGHPUT.md). The deployment must declare\n worklist.max_workers >= N, one account per worker, and items_independent:\n true. Each item is claimed once; a halt on any worker stops new items on\n all of them.\n --readback-window K Let a worker start its next item while up to K earlier saves still wait\n for their system-of-record read-back (default: worklist.readback_window,\n normally 0). A failed read-back stops the run and names the items written\n after it.\n --attest-contract PATH\n OPT-IN: effect-contract YAML for the openadapt-attest proof sidecar. After\n the run it verifies the claimed effect against the system of record and\n writes a SIGNED receipt (attest_receipt.json) into the run directory.\n Never changes the run outcome or exit code. Env fallback:\n OPENADAPT_FLOW_ATTEST_CONTRACT\n --attest-sign-key PATH\n Signing key for the attest receipt (env fallback:\n OPENADAPT_FLOW_ATTEST_SIGN_KEY)\n --attest-audit-log PATH\n Append-only audit log the attest sidecar writes to (env fallback:\n OPENADAPT_FLOW_ATTEST_AUDIT_LOG)\n --attest-pre-state PATH\n Existing pre-actuation system-of-record snapshot for delta checks. When\n omitted, replay captures one into the run directory\n (attest_pre_state.json) before actuation begins (env fallback:\n OPENADAPT_FLOW_ATTEST_PRE_STATE)\n\nAlso available as: openadapt-flow run --replay\n", + "openadapt-flow replay": "usage: openadapt-flow replay [-h] [--stop-before-effect] [--url URL] [--demo-app] [--drift DRIFT]\n [--run-dir RUN_DIR] [--param K=V] [--params-file PARAMS_FILE]\n [--local-grounding] [--allow-model-grounding]\n [--save-healed-to SAVE_HEALED_TO] [--headed] [--record-video DIR]\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 [--surface NAME=KIND[:TARGET]] [--browser-cdp-endpoint URL]\n [--browser-page-url URL]\n [--invocation-challenge INVOCATION_CHALLENGE] [--config-sha256 HEX]\n [--config YAML]\n [--effects-kind {none,rest,fhir,sql,file,document-hash}]\n [--effects-base-url EFFECTS_BASE_URL]\n [--effects-records-path EFFECTS_RECORDS_PATH]\n [--effects-root EFFECTS_ROOT] [--api-actuator]\n [--api-base-url API_BASE_URL] [--durable]\n [--worklist [RELATION=]FILE] [--workers N] [--readback-window K]\n [--attest-contract PATH] [--attest-sign-key PATH]\n [--attest-audit-log PATH] [--attest-pre-state PATH] [--no-encrypt]\n bundle\n\npositional arguments:\n bundle Workflow bundle directory\n\noptions:\n -h, --help show this help message and exit\n --stop-before-effect Check it without application input: observe a prefilled screen, then stop\n before the first input. Unproved prefixes refuse; web requires an\n attached, already-open page.\n --url URL URL of the target app\n --demo-app Serve the bundled demo app and replay against it (for a bundle recorded on\n it, such as the tutorial's)\n --drift DRIFT Comma-separated demo drift modes (theme,move,rename,modal) to demonstrate\n bounded drift resolution; only with --demo-app\n --run-dir RUN_DIR Run output directory (default: runs/replay- under the\n current directory)\n --param K=V Parameter substitution (repeatable)\n --params-file PARAMS_FILE\n JSON object of parameter bindings; keeps values out of process arguments\n for managed execution\n --local-grounding Pixel surfaces (Citrix, RDP, VNC): find icons and unlabeled controls again\n after a display-scale, zoom, font or theme change with a local model.\n Look-alikes halt the step. In process, no outbound calls; the pinned 24 MB\n weights are fetched once.\n --allow-model-grounding\n EGRESS OPT-IN (PHI audit REM-3): permit wiring an off-box model grounder /\n identity-VLM / state-verifier (a paid API or an on-prem VLM appliance via\n OPENADAPT_FLOW_VLM_URL). Screenshots may leave the box. Off by default:\n replay is fully local with zero outbound calls.\n --save-healed-to SAVE_HEALED_TO\n Write the healed bundle to this directory\n --headed Run the browser headed\n --record-video DIR OPT-IN: capture a WebM video of the replay session into DIR (default: off;\n no effect on the run directory or report)\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 --surface NAME=KIND[:TARGET]\n Multi-surface bundles: bind a backend to the backend surface NAME\n (repeatable). KIND defaults to the kind the bundle declares; TARGET fills\n that kind's target (web: URL, windows: agent URL, macos: app, linux: app,\n rdp: host, citrix: client window). NAME=TARGET alone is accepted. Other\n fields go in the config's surfaces: map. Browser tabs and popups need no\n binding. See docs/MULTI_SURFACE.md.\n --browser-cdp-endpoint URL\n Run in an already-running, signed-in local Chromium through its loopback\n DevTools endpoint (for example, http://127.0.0.1:9222) instead of\n launching a new, signed-out browser. The run binds the one open tab on the\n --url origin, starts from the screen it shows, and never navigates or\n closes the browser. Overrides backend.browser_cdp_endpoint from --config.\n --browser-page-url URL\n Exact current URL of the tab to run in, when more than one open tab has\n the --url origin. Requires --browser-cdp-endpoint.\n --invocation-challenge INVOCATION_CHALLENGE\n Non-authority freshness challenge for the local Standard producer.\n --config-sha256 HEX The SHA-256 of --config's bytes. Flow opens the file once (not through a\n symlink; it must be a regular file), refuses it if the digest differs, and\n from then on parses only those bytes whenever this command loads that\n path, so replacing the file, or a symlink put in its place, changes\n nothing\n --config YAML Deployment config YAML wiring backend / actuation / effects / runtime /\n policy (see docs/deployment.example.yaml). Direct flags below override\n individual fields.\n --effects-kind {none,rest,fhir,sql,file,document-hash}\n System-of-record EffectVerifier to wire so consequential writes are\n verified against the real record (not the screen). rest needs --effects-\n records-path; the fhir/sql/file kinds need their config fields\n (resource_type and field_paths, sql_query, root, ...) from a --config\n deployment YAML\n --effects-base-url EFFECTS_BASE_URL\n Base URL for the rest / fhir effect verifier\n --effects-records-path EFFECTS_RECORDS_PATH\n Path whose GET returns the app's records (rest effect verifier)\n --effects-root EFFECTS_ROOT\n Document-store root for the document-hash effect verifier\n --api-actuator Wire the API/tool actuation tier: a step carrying an ApiBinding is\n performed via the API (deterministic, $0) and confirmed by the effect\n verifier, skipping the GUI\n --api-base-url API_BASE_URL\n Base URL for the API actuator (implies --api-actuator)\n --durable Enable the Tier-3 durable runtime: checkpoint each verified step and\n durably PAUSE on halt, so the run is resumable via `resume` (never re-\n performing a confirmed write)\n --worklist [RELATION=]FILE\n CSV/JSON worklist of parameter rows driving a PROGRAM bundle's loop over a\n relation (repeatable). 'RELATION=FILE' binds the file to that relation; a\n bare 'FILE' binds to the program's sole loop relation.\n --workers N Run a worklist program's items on N workers at once, each in its own\n signed-in session (docs/THROUGHPUT.md). The deployment must declare\n worklist.max_workers >= N, one account per worker, and items_independent:\n true. Each item is claimed once; a halt on any worker stops new items on\n all of them.\n --readback-window K Let a worker start its next item while up to K earlier saves still wait\n for their system-of-record read-back (default: worklist.readback_window,\n normally 0). A failed read-back stops the run and names the items written\n after it.\n --attest-contract PATH\n OPT-IN: effect-contract YAML for the openadapt-attest proof sidecar. After\n the run it verifies the claimed effect against the system of record and\n writes a SIGNED receipt (attest_receipt.json) into the run directory.\n Never changes the run outcome or exit code. Env fallback:\n OPENADAPT_FLOW_ATTEST_CONTRACT\n --attest-sign-key PATH\n Signing key for the attest receipt (env fallback:\n OPENADAPT_FLOW_ATTEST_SIGN_KEY)\n --attest-audit-log PATH\n Append-only audit log the attest sidecar writes to (env fallback:\n OPENADAPT_FLOW_ATTEST_AUDIT_LOG)\n --attest-pre-state PATH\n Existing pre-actuation system-of-record snapshot for delta checks. When\n omitted, replay captures one into the run directory\n (attest_pre_state.json) before actuation begins (env fallback:\n OPENADAPT_FLOW_ATTEST_PRE_STATE)\n --no-encrypt Write this command's output in plaintext (recorded in\n ~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is encrypted\n by default; same as OPENADAPT_ENCRYPT_AT_REST=0. Ignored under\n OPENADAPT_FLOW_AT_REST=strict\n\nAlso available as: openadapt-flow run --replay\n", "openadapt-flow report-break": "usage: openadapt-flow report-break [-h] --workflow-id WORKFLOW_ID [--deployment-kind {cloud,byoc}]\n [--org-id ORG_ID] [--host HOST]\n [--destination-kind {openadapt-managed,customer-managed,local}]\n [--trusted-host TRUSTED_HOST] [--token TOKEN]\n run_dir\n\npositional arguments:\n run_dir The halted run directory (holds report.json)\n\noptions:\n -h, --help show this help message and exit\n --workflow-id WORKFLOW_ID\n The hosted workflow id this run belongs to (from `push`/dashboard)\n --deployment-kind {cloud,byoc}\n Backward-compatible hint; v2 provenance is derived server-side and this\n value is not sent\n --org-id ORG_ID Backward-compatible hint; token ownership is derived server-side and this\n value is not sent\n --host HOST Hosted base URL (default: config.toml host, else https://app.openadapt.ai)\n --destination-kind {openadapt-managed,customer-managed,local}\n Trust class for the break-report destination\n --trusted-host TRUSTED_HOST\n Exact allowed customer-managed origin (repeatable)\n --token TOKEN Ingest token (default: OPENADAPT_INGEST_TOKEN env, OS keychain, then an\n existing config migration token)\n\nAlso available as: openadapt-flow inspect report-break\n", "openadapt-flow report-run": "usage: openadapt-flow report-run [-h] [--workflow-id WORKFLOW_ID]\n [--deployment-kind {local,cloud,byoc}]\n [--backend {web,windows,macos,linux,rdp,citrix}]\n [--org-id ORG_ID] [--host HOST]\n [--destination-kind {openadapt-managed,customer-managed,local}]\n [--trusted-host TRUSTED_HOST] [--token TOKEN] [--receipt DIR]\n [--production]\n run_dir\n\npositional arguments:\n run_dir The completed run directory (holds report.json)\n\noptions:\n -h, --help show this help message and exit\n --workflow-id WORKFLOW_ID\n Hosted workflow id (from `push`/dashboard). When omitted the summary binds\n by the exact pushed bundle content digest\n --deployment-kind {local,cloud,byoc}\n Deprecated compatibility input from Flow 1.18.0; accepted but ignored\n because authenticated server provenance is authoritative\n --backend {web,windows,macos,linux,rdp,citrix}\n Backend/substrate this run executed on\n (web/windows/macos/linux/rdp/citrix)\n --org-id ORG_ID Deprecated compatibility input from Flow 1.18.0; accepted but ignored\n because token ownership is authoritative\n --host HOST Hosted base URL (default: config.toml host, else https://app.openadapt.ai)\n --destination-kind {openadapt-managed,customer-managed,local}\n Trust class for the run-summary destination\n --trusted-host TRUSTED_HOST\n Exact allowed customer-managed origin (repeatable)\n --token TOKEN Ingest token (default: OPENADAPT_INGEST_TOKEN env, OS keychain, then an\n existing config migration token)\n --receipt DIR LOCAL ONLY: write a shareable run summary (run-summary.png / .json / .md)\n into DIR instead of contacting any host. The receipt is generated from a\n closed allow-list -- closed enums, counts, digests, versions -- and can\n carry no screenshot, OCR text, typed value, parameter, URL, hostname,\n coordinate, or free-form text\n --production --receipt only: explicitly mark this as a real production run. A\n production receipt must go through sanitize/approve before it leaves your\n trust boundary\n\nAlso available as: openadapt-flow inspect report-run\n", "openadapt-flow resume": "usage: openadapt-flow resume [-h] [--qualification-authority-file PATH]\n [--qualification-campaign-authority-file PATH] [--url URL] [--headed]\n [--roll-back] [--require-approval] [--report] [--param K=V]\n [--params-file PARAMS_FILE]\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 [--browser-cdp-endpoint URL] [--browser-page-url URL]\n [--invocation-challenge INVOCATION_CHALLENGE] [--config-sha256 HEX]\n [--config YAML]\n [--effects-kind {none,rest,fhir,sql,file,document-hash}]\n [--effects-base-url EFFECTS_BASE_URL]\n [--effects-records-path EFFECTS_RECORDS_PATH]\n [--effects-root EFFECTS_ROOT] [--api-actuator]\n [--api-base-url API_BASE_URL] [--durable] [--attest-contract PATH]\n [--attest-sign-key PATH] [--attest-audit-log PATH]\n [--attest-pre-state PATH] [--approver-root HEX] [--key-dir KEY_DIR]\n [--approver-policy FILE] [--started-by ID] [--approver-webhook URL]\n [--approver-webhook-id APPROVER_WEBHOOK_ID]\n [--approver-webhook-kind {agent,system}]\n [--approval-mode {each_item,problems_only,not_gated}]\n [--approval-wait SECONDS]\n run_dir\n\npositional arguments:\n run_dir The paused run directory (holds checkpoints)\n\noptions:\n -h, --help show this help message and exit\n --qualification-authority-file PATH\n Private owner-only Production qualification authority for the resumed\n input edge\n --qualification-campaign-authority-file PATH\n Private signed non-production campaign authority for a resumed\n qualification input edge\n --url URL Target app URL to rebuild a live backend (default: backend.url)\n --headed Run the browser headed\n --roll-back Instead of resuming, roll the run back with its approved compensations and\n prove the store matches the read from before the run; also continues a\n rollback a crash interrupted\n --require-approval Refuse to resume unless the pending escalation is 'approved' (see\n `approve`)\n --report After a successful resume, send the PHI-minimal local completion summary\n to the paired control plane (also enabled by OPENADAPT_FLOW_REPORT_RUN=1)\n --param K=V Parameter substitution (repeatable); required again on resume when the\n effect-verifier config binds run parameters\n --params-file PARAMS_FILE\n JSON object of parameter bindings; keeps values out of process arguments\n for managed execution (see --param)\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 --browser-cdp-endpoint URL\n Run in an already-running, signed-in local Chromium through its loopback\n DevTools endpoint (for example, http://127.0.0.1:9222) instead of\n launching a new, signed-out browser. The run binds the one open tab on the\n --url origin, starts from the screen it shows, and never navigates or\n closes the browser. Overrides backend.browser_cdp_endpoint from --config.\n --browser-page-url URL\n Exact current URL of the tab to run in, when more than one open tab has\n the --url origin. Requires --browser-cdp-endpoint.\n --invocation-challenge INVOCATION_CHALLENGE\n Non-authority freshness challenge for the local Standard producer.\n --config-sha256 HEX The SHA-256 of --config's bytes. Flow opens the file once (not through a\n symlink; it must be a regular file), refuses it if the digest differs, and\n from then on parses only those bytes whenever this command loads that\n path, so replacing the file, or a symlink put in its place, changes\n nothing\n --config YAML Deployment config YAML wiring backend / actuation / effects / runtime /\n policy (see docs/deployment.example.yaml). Direct flags below override\n individual fields.\n --effects-kind {none,rest,fhir,sql,file,document-hash}\n System-of-record EffectVerifier to wire so consequential writes are\n verified against the real record (not the screen). rest needs --effects-\n records-path; the fhir/sql/file kinds need their config fields\n (resource_type and field_paths, sql_query, root, ...) from a --config\n deployment YAML\n --effects-base-url EFFECTS_BASE_URL\n Base URL for the rest / fhir effect verifier\n --effects-records-path EFFECTS_RECORDS_PATH\n Path whose GET returns the app's records (rest effect verifier)\n --effects-root EFFECTS_ROOT\n Document-store root for the document-hash effect verifier\n --api-actuator Wire the API/tool actuation tier: a step carrying an ApiBinding is\n performed via the API (deterministic, $0) and confirmed by the effect\n verifier, skipping the GUI\n --api-base-url API_BASE_URL\n Base URL for the API actuator (implies --api-actuator)\n --durable Enable the Tier-3 durable runtime: checkpoint each verified step and\n durably PAUSE on halt, so the run is resumable via `resume` (never re-\n performing a confirmed write)\n --attest-contract PATH\n OPT-IN: effect-contract YAML for the openadapt-attest proof sidecar. After\n the run it verifies the claimed effect against the system of record and\n writes a SIGNED receipt (attest_receipt.json) into the run directory.\n Never changes the run outcome or exit code. Env fallback:\n OPENADAPT_FLOW_ATTEST_CONTRACT\n --attest-sign-key PATH\n Signing key for the attest receipt (env fallback:\n OPENADAPT_FLOW_ATTEST_SIGN_KEY)\n --attest-audit-log PATH\n Append-only audit log the attest sidecar writes to (env fallback:\n OPENADAPT_FLOW_ATTEST_AUDIT_LOG)\n --attest-pre-state PATH\n Existing pre-actuation system-of-record snapshot for delta checks. When\n omitted, replay captures one into the run directory\n (attest_pre_state.json) before actuation begins (env fallback:\n OPENADAPT_FLOW_ATTEST_PRE_STATE)\n --approver-root HEX The root approver key (64 hex) this run trusts: a person's answer counts\n only when its signer is on the signed approver roster this key vouches\n for. Also set by the deployment config's approvers.root_public_key or\n OPENADAPT_APPROVER_ROOT; without one, a person's answer is refused\n --key-dir KEY_DIR Key directory with the signed approver roster (approvers.json) that\n approvals are checked against; use the one you approved with (default\n $OPENADAPT_JIT_KEY_DIR or ~/.openadapt/jit)\n --approver-policy FILE\n A person-signed approver grant (openadapt-flow approver-grant sign): which\n agents or systems may answer which classes of save, until when. Without a\n grant that verifies against the signer registry, only a person may answer;\n an unsigned or tampered file gives no authority. A clinical_write save\n takes a non-person approver only when the grant's policy pins an opt-in.\n --started-by ID The agent or system that started this run (opaque id). It can never answer\n this run's saves. openadapt-agent sets it.\n --approver-webhook URL\n Ask this https endpoint (the customer's approver agent or system) about\n each waiting save, with HMAC-signed, PHI-free messages. The secret is read\n from OPENADAPT_APPROVER_WEBHOOK_SECRET. A person can still answer in\n Desktop. Needs --approver-webhook-id and a policy that allows the\n approver's kind.\n --approver-webhook-id APPROVER_WEBHOOK_ID\n The webhook approver's opaque id, such as system:acme-approvals\n --approver-webhook-kind {agent,system}\n Whether the webhook approver is an agent or a system (default system)\n --approval-mode {each_item,problems_only,not_gated}\n Per-item approval before each consequential save. each_item (the default\n for every run): the run waits before every save until a person approves it\n in Desktop's Run it (see `item-approval`). problems_only: only problems go\n to a person; until a switch record is configured, every save still asks.\n not_gated: no per-item pause, recorded in the report (the hosted runner,\n Execute and MCP callers). Overrides runtime.approval_mode. A resume always\n keeps the run's own mode.\n --approval-wait SECONDS\n How long the run waits for a person's answer before it stops before the\n save (default 900, at most 14400). An answer given later can still be used\n by `resume`.\n\nAlso available as: openadapt-flow run --resume\n", @@ -233,7 +239,7 @@ "openadapt-flow rollback": "usage: openadapt-flow rollback [-h] {qualify} ...\n\npositional arguments:\n {qualify}\n qualify Stop the run before and after every save on a declared test copy, roll back, and\n keep the compensations that restore the whole store\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow undo rollback\n", "openadapt-flow rollback qualify": "usage: openadapt-flow rollback qualify [-h] --config CONFIG [--recording RECORDING]\n [--from-recording FROM_RECORDINGS] [--work-dir WORK_DIR]\n [--report REPORT] [--no-write] [--json]\n bundle\n\npositional arguments:\n bundle Workflow bundle directory\n\noptions:\n -h, --help show this help message and exit\n --config CONFIG Deployment file that declares a test copy (test_copy.declared: true);\n rollback.database, when set, is the whole-database read\n --recording RECORDING\n The bundle's own recording directory (its network.jsonl)\n --from-recording FROM_RECORDINGS\n A compiled bundle of a person deleting or cancelling (repeatable)\n --work-dir WORK_DIR Keep the test-copy runs here\n --report REPORT Write the report (JSON) here\n --no-write Qualify, but don't write new compensations into the bundle\n --json Print the report as JSON\n\nAlso available as: openadapt-flow undo rollback qualify\n", "openadapt-flow route": "usage: openadapt-flow route [-h] [--param K=V] [--params-file PARAMS_FILE] [--first-screen PNG]\n [--url URL] [--config CONFIG]\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 [--browser-cdp-endpoint URL] [--browser-page-url URL]\n variant_set\n\npositional arguments:\n variant_set Variant-set directory\n\noptions:\n -h, --help show this help message and exit\n --param K=V Item input\n --params-file PARAMS_FILE\n JSON object of item inputs\n --first-screen PNG\n --url URL Launch a browser here to read the first screen\n --config CONFIG Deployment config (backend section)\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 --browser-cdp-endpoint URL\n Run in an already-running, signed-in local Chromium through its loopback\n DevTools endpoint (for example, http://127.0.0.1:9222) instead of\n launching a new, signed-out browser. The run binds the one open tab on the\n --url origin, starts from the screen it shows, and never navigates or\n closes the browser. Overrides backend.browser_cdp_endpoint from --config.\n --browser-page-url URL\n Exact current URL of the tab to run in, when more than one open tab has\n the --url origin. Requires --browser-cdp-endpoint.\n\nAlso available as: openadapt-flow run --route\n", - "openadapt-flow run": "usage: openadapt-flow run [-h] [--first-screen PNG] [--profile {demo,standard,regulated}]\n [--url URL] [--run-dir RUN_DIR] [--param K=V]\n [--params-file PARAMS_FILE] [--local-grounding]\n [--allow-model-grounding] [--save-healed-to SAVE_HEALED_TO] [--headed]\n [--hold-on-halt SECONDS] [--self-repair] [--no-auto-repair]\n [--repair-agent MODULE:NAME] [--repair-screen-access-by NAME]\n [--repair-screen-share-mode {scrubbed_only,allow_unscrubbed}]\n [--repair-model-provider {anthropic,openai}]\n [--repair-model-key-file PATH] [--repair-store REPAIR_STORE]\n [--repair-attempts REPAIR_ATTEMPTS] [--repair-fault-url URL]\n [--repair-approval-wait SECONDS]\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 [--surface NAME=KIND[:TARGET]] [--browser-cdp-endpoint URL]\n [--browser-page-url URL] [--invocation-challenge INVOCATION_CHALLENGE]\n [--config-sha256 HEX] [--config YAML]\n [--effects-kind {none,rest,fhir,sql,file,document-hash}]\n [--effects-base-url EFFECTS_BASE_URL]\n [--effects-records-path EFFECTS_RECORDS_PATH]\n [--effects-root EFFECTS_ROOT] [--api-actuator]\n [--api-base-url API_BASE_URL] [--durable] [--worklist [RELATION=]FILE]\n [--workers N] [--readback-window K] [--attest-contract PATH]\n [--attest-sign-key PATH] [--attest-audit-log PATH]\n [--attest-pre-state PATH] [--policy NAME-OR-PATH]\n [--approve-unverified-writes] [--strict-templates] [--allow-unencrypted]\n [--pin-digest SHA256] [--pin-version VERSION]\n [--subroutine-library JSON] [--subroutine-workflow-id ID]\n [--permission-trust PATH] [--execute-url URL]\n [--execute-environment-id ID] [--code-trust PATH]\n [--code-runtime-environment-digest SHA256] [--allow-trusted-code]\n [--process-receipt-private-key PATH]\n [--process-receipt-issuer-key-id PROCESS_RECEIPT_ISSUER_KEY_ID]\n [--process-environment-id PROCESS_ENVIRONMENT_ID]\n [--process-runner-id PROCESS_RUNNER_ID]\n [--qualification-authority-file PATH] [--dry-run] [--report]\n [--cloud-execution-id CLOUD_EXECUTION_ID] [--approver-root HEX]\n [--key-dir KEY_DIR] [--approver-policy FILE] [--started-by ID]\n [--approver-webhook URL] [--approver-webhook-id APPROVER_WEBHOOK_ID]\n [--approver-webhook-kind {agent,system}]\n [--approval-mode {each_item,problems_only,not_gated}]\n [--approval-wait SECONDS]\n bundle\n\npositional arguments:\n bundle Workflow bundle directory\n\noptions:\n -h, --help show this help message and exit\n --first-screen PNG Variant sets only: the first screen to route on. Without it the router\n reads one frame through the selected backend.\n --profile {demo,standard,regulated}\n Named execution posture (or runtime.profile from --config). Demo is\n explicitly non-production; Standard requires certification, durability,\n identity, and independently verified consequential effects. Regulated\n additionally requires encrypted bundles, strictly sealed evidence assets,\n and encrypted durable checkpoints in a customer-controlled deployment.\n Omit only for compatibility with a pre-profile deployment.\n --url URL Target app URL (default: backend.url from --config)\n --run-dir RUN_DIR Run output directory (default: runs/replay-)\n --param K=V Parameter substitution (repeatable)\n --params-file PARAMS_FILE\n JSON object of parameter bindings; keeps values out of process arguments\n for managed execution\n --local-grounding Pixel surfaces (Citrix, RDP, VNC): find icons and unlabeled controls again\n after a display-scale, zoom, font or theme change with a local model.\n Look-alikes halt the step. In process, no outbound calls; the pinned 24 MB\n weights are fetched once.\n --allow-model-grounding\n EGRESS OPT-IN (PHI audit REM-3): permit wiring an off-box model component\n (also settable via runtime.allow_model_grounding)\n --save-healed-to SAVE_HEALED_TO\n Write the healed bundle to this directory\n --headed Run the browser headed\n --hold-on-halt SECONDS\n When a browser run halts, keep its page open for up to SECONDS so\n openadapt-agent can record a repair on it (see\n openadapt_flow.repair.hold). 0, the default, closes it at once. Max 1800.\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 --surface NAME=KIND[:TARGET]\n Multi-surface bundles: bind a backend to the backend surface NAME\n (repeatable). KIND defaults to the kind the bundle declares; TARGET fills\n that kind's target (web: URL, windows: agent URL, macos: app, linux: app,\n rdp: host, citrix: client window). NAME=TARGET alone is accepted. Other\n fields go in the config's surfaces: map. Browser tabs and popups need no\n binding. See docs/MULTI_SURFACE.md.\n --browser-cdp-endpoint URL\n Run in an already-running, signed-in local Chromium through its loopback\n DevTools endpoint (for example, http://127.0.0.1:9222) instead of\n launching a new, signed-out browser. The run binds the one open tab on the\n --url origin, starts from the screen it shows, and never navigates or\n closes the browser. Overrides backend.browser_cdp_endpoint from --config.\n --browser-page-url URL\n Exact current URL of the tab to run in, when more than one open tab has\n the --url origin. Requires --browser-cdp-endpoint.\n --invocation-challenge INVOCATION_CHALLENGE\n Non-authority freshness challenge for the local Standard producer.\n --config-sha256 HEX The SHA-256 of --config's bytes. Flow opens the file once (not through a\n symlink; it must be a regular file), refuses it if the digest differs, and\n from then on parses only those bytes whenever this command loads that\n path, so replacing the file, or a symlink put in its place, changes\n nothing\n --config YAML Deployment config YAML wiring backend / actuation / effects / runtime /\n policy (see docs/deployment.example.yaml). Direct flags below override\n individual fields.\n --effects-kind {none,rest,fhir,sql,file,document-hash}\n System-of-record EffectVerifier to wire so consequential writes are\n verified against the real record (not the screen). rest needs --effects-\n records-path; the fhir/sql/file kinds need their config fields\n (resource_type and field_paths, sql_query, root, ...) from a --config\n deployment YAML\n --effects-base-url EFFECTS_BASE_URL\n Base URL for the rest / fhir effect verifier\n --effects-records-path EFFECTS_RECORDS_PATH\n Path whose GET returns the app's records (rest effect verifier)\n --effects-root EFFECTS_ROOT\n Document-store root for the document-hash effect verifier\n --api-actuator Wire the API/tool actuation tier: a step carrying an ApiBinding is\n performed via the API (deterministic, $0) and confirmed by the effect\n verifier, skipping the GUI\n --api-base-url API_BASE_URL\n Base URL for the API actuator (implies --api-actuator)\n --durable Enable the Tier-3 durable runtime: checkpoint each verified step and\n durably PAUSE on halt, so the run is resumable via `resume` (never re-\n performing a confirmed write)\n --worklist [RELATION=]FILE\n CSV/JSON worklist of parameter rows driving a PROGRAM bundle's loop over a\n relation (repeatable). 'RELATION=FILE' binds the file to that relation; a\n bare 'FILE' binds to the program's sole loop relation.\n --workers N Run a worklist program's items on N workers at once, each in its own\n signed-in session (docs/THROUGHPUT.md). The deployment must declare\n worklist.max_workers >= N, one account per worker, and items_independent:\n true. Each item is claimed once; a halt on any worker stops new items on\n all of them.\n --readback-window K Let a worker start its next item while up to K earlier saves still wait\n for their system-of-record read-back (default: worklist.readback_window,\n normally 0). A failed read-back stops the run and names the items written\n after it.\n --attest-contract PATH\n OPT-IN: effect-contract YAML for the openadapt-attest proof sidecar. After\n the run it verifies the claimed effect against the system of record and\n writes a SIGNED receipt (attest_receipt.json) into the run directory.\n Never changes the run outcome or exit code. Env fallback:\n OPENADAPT_FLOW_ATTEST_CONTRACT\n --attest-sign-key PATH\n Signing key for the attest receipt (env fallback:\n OPENADAPT_FLOW_ATTEST_SIGN_KEY)\n --attest-audit-log PATH\n Append-only audit log the attest sidecar writes to (env fallback:\n OPENADAPT_FLOW_ATTEST_AUDIT_LOG)\n --attest-pre-state PATH\n Existing pre-actuation system-of-record snapshot for delta checks. When\n omitted, replay captures one into the run directory\n (attest_pre_state.json) before actuation begins (env fallback:\n OPENADAPT_FLOW_ATTEST_PRE_STATE)\n --policy NAME-OR-PATH\n Certifying policy the bundle must PASS to run (default: the deployment\n config's policy, else 'clinical-write')\n --approve-unverified-writes\n APPROVAL FALLBACK: explicitly approve executing writes whose effects\n cannot be independently verified in this deployment (no verifier\n configured). Without it such a bundle is refused\n --strict-templates Refuse (not just warn) when template/screenshot assets are unsealed\n (plaintext at rest)\n --allow-unencrypted Escape hatch: permit running a bundle whose workflow.json is NOT encrypted\n at rest (disables the encryption gate). Discouraged\n --pin-digest SHA256 Refuse unless the bundle's sealed content digest equals this\n --pin-version VERSION\n Refuse unless the bundle's compiler version equals this\n --subroutine-library JSON\n Current subroutine library to re-admit embedded subroutines against before\n this run. Required when the bundle embeds a subroutine; a certification\n made before a newer version was published does not let the old version\n run.\n --subroutine-workflow-id ID\n Id this workflow was registered under when it was certified (default: the\n workflow name)\n --permission-trust PATH, --qualification-trust PATH\n Trusted signers for process run permissions. Also\n OPENADAPT_QUALIFICATION_TRUST or qualification-trust.json beside process-\n contract.json. --qualification-trust is deprecated; use --permission-\n trust.\n --execute-url URL HTTPS Execute v1 base URL for process children (OPENADAPT_EXECUTE_URL).\n Local process run uses governed run unless this and a bearer token are set\n --execute-environment-id ID\n Execute environment_id for process children\n (OPENADAPT_EXECUTE_ENVIRONMENT_ID)\n --code-trust PATH Code-admission Ed25519 signer registry for ProcessContract v1. Required\n when the contract contains a code child.\n --code-runtime-environment-digest SHA256\n Exact admitted runtime-environment digest for code children\n --allow-trusted-code Approve exact admitted code that uses the trusted_local profile\n --process-receipt-private-key PATH\n Raw 32-byte Ed25519 key for the ProcessContract v1 terminal receipt\n --process-receipt-issuer-key-id PROCESS_RECEIPT_ISSUER_KEY_ID\n --process-environment-id PROCESS_ENVIRONMENT_ID\n --process-runner-id PROCESS_RUNNER_ID\n --qualification-authority-file PATH\n Private owner-only Production qualification authority (v2 envelope or\n issued openadapt.qualification-admission/v4). Required for Standard and\n Regulated actuation; verified and re-read at every input edge\n --dry-run, --explain Print the fail-closed coverage report and exit WITHOUT executing\n --report OPT-IN: after a SUCCESSFUL run, emit the PHI-free run summary to the\n paired hosted control plane (see `report-run`). Off by default \u2014 nothing\n is ever uploaded without this flag (or OPENADAPT_FLOW_REPORT_RUN=1)\n --cloud-execution-id CLOUD_EXECUTION_ID\n OpenAdapt Cloud Execute execution this run belongs to (or\n OPENADAPT_CLOUD_EXECUTION_ID). After a VERIFIED outcome, Cloud's signed\n receipt is fetched with OPENADAPT_EXECUTE_API_KEY and written into\n report.json as execute_receipt.\n --approver-root HEX The root approver key (64 hex) this run trusts: a person's answer counts\n only when its signer is on the signed approver roster this key vouches\n for. Also set by the deployment config's approvers.root_public_key or\n OPENADAPT_APPROVER_ROOT; without one, a person's answer is refused\n --key-dir KEY_DIR Key directory with the signed approver roster (approvers.json) that\n approvals are checked against; use the one you approved with (default\n $OPENADAPT_JIT_KEY_DIR or ~/.openadapt/jit)\n --approver-policy FILE\n A person-signed approver grant (openadapt-flow approver-grant sign): which\n agents or systems may answer which classes of save, until when. Without a\n grant that verifies against the signer registry, only a person may answer;\n an unsigned or tampered file gives no authority. A clinical_write save\n takes a non-person approver only when the grant's policy pins an opt-in.\n --started-by ID The agent or system that started this run (opaque id). It can never answer\n this run's saves. openadapt-agent sets it.\n --approver-webhook URL\n Ask this https endpoint (the customer's approver agent or system) about\n each waiting save, with HMAC-signed, PHI-free messages. The secret is read\n from OPENADAPT_APPROVER_WEBHOOK_SECRET. A person can still answer in\n Desktop. Needs --approver-webhook-id and a policy that allows the\n approver's kind.\n --approver-webhook-id APPROVER_WEBHOOK_ID\n The webhook approver's opaque id, such as system:acme-approvals\n --approver-webhook-kind {agent,system}\n Whether the webhook approver is an agent or a system (default system)\n --approval-mode {each_item,problems_only,not_gated}\n Per-item approval before each consequential save. each_item (the default\n for every run): the run waits before every save until a person approves it\n in Desktop's Run it (see `item-approval`). problems_only: only problems go\n to a person; until a switch record is configured, every save still asks.\n not_gated: no per-item pause, recorded in the report (the hosted runner,\n Execute and MCP callers). Overrides runtime.approval_mode. A resume always\n keeps the run's own mode.\n --approval-wait SECONDS\n How long the run waits for a person's answer before it stops before the\n save (default 900, at most 14400). An answer given later can still be used\n by `resume`.\n\nself-repair:\n When the run halts before any effect because a screen changed, a repair agent proposes a fix,\n Flow probes it up to the save, and one person approves it before the run resumes. On by\n default whenever a repair agent is configured (here or in the deployment file's repair\n section). See docs/SELF_REPAIR.md.\n\n --self-repair Require self-repair for this run (web runs against --url): refuse the run\n when it can't be repaired.\n --no-auto-repair Do not hand stops to the repair agent; a stop waits for a person.\n --repair-agent MODULE:NAME\n The repair agent: an object, class or factory with dialect, agent_id and\n propose(request).\n --repair-screen-access-by NAME\n The person who allowed the agent to see screens (recorded).\n --repair-screen-share-mode {scrubbed_only,allow_unscrubbed}\n Scrub screens before the agent sees them (default) or not.\n --repair-model-provider {anthropic,openai}\n Load the customer's own key for an agent that calls a model.\n --repair-model-key-file PATH\n The customer's key file ({\"anthropic\": {\"api_key\": ...}}).\n --repair-store REPAIR_STORE\n The repair store the candidate enters (default repair-store/).\n --repair-attempts REPAIR_ATTEMPTS\n Proposals tried for one halt (default 3).\n --repair-fault-url URL\n A URL that presents a fault the patched run must refuse before the save\n (repeatable). Needed when the step's identity is read from the DOM.\n --repair-approval-wait SECONDS\n How long to wait for a person's answer (default 900).\n\nRelated operations (immediately after the task name): --for-each, --process, --dispatch, --route,\n--replay, --resume, --triage, --task-admit, --guard, --flight, --plan\n", + "openadapt-flow run": "usage: openadapt-flow run [-h] [--first-screen PNG] [--profile {demo,standard,regulated}]\n [--url URL] [--run-dir RUN_DIR] [--param K=V]\n [--params-file PARAMS_FILE] [--local-grounding]\n [--allow-model-grounding] [--save-healed-to SAVE_HEALED_TO] [--headed]\n [--hold-on-halt SECONDS] [--self-repair] [--no-auto-repair]\n [--repair-agent MODULE:NAME] [--repair-screen-access-by NAME]\n [--repair-screen-share-mode {scrubbed_only,allow_unscrubbed}]\n [--repair-model-provider {anthropic,openai}]\n [--repair-model-key-file PATH] [--repair-store REPAIR_STORE]\n [--repair-attempts REPAIR_ATTEMPTS] [--repair-fault-url URL]\n [--repair-approval-wait SECONDS]\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 [--surface NAME=KIND[:TARGET]] [--browser-cdp-endpoint URL]\n [--browser-page-url URL] [--invocation-challenge INVOCATION_CHALLENGE]\n [--config-sha256 HEX] [--config YAML]\n [--effects-kind {none,rest,fhir,sql,file,document-hash}]\n [--effects-base-url EFFECTS_BASE_URL]\n [--effects-records-path EFFECTS_RECORDS_PATH]\n [--effects-root EFFECTS_ROOT] [--api-actuator]\n [--api-base-url API_BASE_URL] [--durable] [--worklist [RELATION=]FILE]\n [--workers N] [--readback-window K] [--attest-contract PATH]\n [--attest-sign-key PATH] [--attest-audit-log PATH]\n [--attest-pre-state PATH] [--policy NAME-OR-PATH]\n [--approve-unverified-writes] [--strict-templates] [--allow-unencrypted]\n [--pin-digest SHA256] [--pin-version VERSION]\n [--subroutine-library JSON] [--subroutine-workflow-id ID]\n [--permission-trust PATH] [--execute-url URL]\n [--execute-environment-id ID] [--code-trust PATH]\n [--code-runtime-environment-digest SHA256] [--allow-trusted-code]\n [--process-receipt-private-key PATH]\n [--process-receipt-issuer-key-id PROCESS_RECEIPT_ISSUER_KEY_ID]\n [--process-environment-id PROCESS_ENVIRONMENT_ID]\n [--process-runner-id PROCESS_RUNNER_ID]\n [--qualification-authority-file PATH] [--dry-run] [--report]\n [--cloud-execution-id CLOUD_EXECUTION_ID] [--approver-root HEX]\n [--key-dir KEY_DIR] [--approver-policy FILE] [--started-by ID]\n [--approver-webhook URL] [--approver-webhook-id APPROVER_WEBHOOK_ID]\n [--approver-webhook-kind {agent,system}]\n [--approval-mode {each_item,problems_only,not_gated}]\n [--approval-wait SECONDS] [--no-encrypt]\n bundle\n\npositional arguments:\n bundle Workflow bundle directory\n\noptions:\n -h, --help show this help message and exit\n --first-screen PNG Variant sets only: the first screen to route on. Without it the router\n reads one frame through the selected backend.\n --profile {demo,standard,regulated}\n Named execution posture (or runtime.profile from --config). Demo is\n explicitly non-production; Standard requires certification, durability,\n identity, and independently verified consequential effects. Regulated\n additionally requires encrypted bundles, strictly sealed evidence assets,\n and encrypted durable checkpoints in a customer-controlled deployment.\n Omit only for compatibility with a pre-profile deployment.\n --url URL Target app URL (default: backend.url from --config)\n --run-dir RUN_DIR Run output directory (default: runs/replay-)\n --param K=V Parameter substitution (repeatable)\n --params-file PARAMS_FILE\n JSON object of parameter bindings; keeps values out of process arguments\n for managed execution\n --local-grounding Pixel surfaces (Citrix, RDP, VNC): find icons and unlabeled controls again\n after a display-scale, zoom, font or theme change with a local model.\n Look-alikes halt the step. In process, no outbound calls; the pinned 24 MB\n weights are fetched once.\n --allow-model-grounding\n EGRESS OPT-IN (PHI audit REM-3): permit wiring an off-box model component\n (also settable via runtime.allow_model_grounding)\n --save-healed-to SAVE_HEALED_TO\n Write the healed bundle to this directory\n --headed Run the browser headed\n --hold-on-halt SECONDS\n When a browser run halts, keep its page open for up to SECONDS so\n openadapt-agent can record a repair on it (see\n openadapt_flow.repair.hold). 0, the default, closes it at once. Max 1800.\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 --surface NAME=KIND[:TARGET]\n Multi-surface bundles: bind a backend to the backend surface NAME\n (repeatable). KIND defaults to the kind the bundle declares; TARGET fills\n that kind's target (web: URL, windows: agent URL, macos: app, linux: app,\n rdp: host, citrix: client window). NAME=TARGET alone is accepted. Other\n fields go in the config's surfaces: map. Browser tabs and popups need no\n binding. See docs/MULTI_SURFACE.md.\n --browser-cdp-endpoint URL\n Run in an already-running, signed-in local Chromium through its loopback\n DevTools endpoint (for example, http://127.0.0.1:9222) instead of\n launching a new, signed-out browser. The run binds the one open tab on the\n --url origin, starts from the screen it shows, and never navigates or\n closes the browser. Overrides backend.browser_cdp_endpoint from --config.\n --browser-page-url URL\n Exact current URL of the tab to run in, when more than one open tab has\n the --url origin. Requires --browser-cdp-endpoint.\n --invocation-challenge INVOCATION_CHALLENGE\n Non-authority freshness challenge for the local Standard producer.\n --config-sha256 HEX The SHA-256 of --config's bytes. Flow opens the file once (not through a\n symlink; it must be a regular file), refuses it if the digest differs, and\n from then on parses only those bytes whenever this command loads that\n path, so replacing the file, or a symlink put in its place, changes\n nothing\n --config YAML Deployment config YAML wiring backend / actuation / effects / runtime /\n policy (see docs/deployment.example.yaml). Direct flags below override\n individual fields.\n --effects-kind {none,rest,fhir,sql,file,document-hash}\n System-of-record EffectVerifier to wire so consequential writes are\n verified against the real record (not the screen). rest needs --effects-\n records-path; the fhir/sql/file kinds need their config fields\n (resource_type and field_paths, sql_query, root, ...) from a --config\n deployment YAML\n --effects-base-url EFFECTS_BASE_URL\n Base URL for the rest / fhir effect verifier\n --effects-records-path EFFECTS_RECORDS_PATH\n Path whose GET returns the app's records (rest effect verifier)\n --effects-root EFFECTS_ROOT\n Document-store root for the document-hash effect verifier\n --api-actuator Wire the API/tool actuation tier: a step carrying an ApiBinding is\n performed via the API (deterministic, $0) and confirmed by the effect\n verifier, skipping the GUI\n --api-base-url API_BASE_URL\n Base URL for the API actuator (implies --api-actuator)\n --durable Enable the Tier-3 durable runtime: checkpoint each verified step and\n durably PAUSE on halt, so the run is resumable via `resume` (never re-\n performing a confirmed write)\n --worklist [RELATION=]FILE\n CSV/JSON worklist of parameter rows driving a PROGRAM bundle's loop over a\n relation (repeatable). 'RELATION=FILE' binds the file to that relation; a\n bare 'FILE' binds to the program's sole loop relation.\n --workers N Run a worklist program's items on N workers at once, each in its own\n signed-in session (docs/THROUGHPUT.md). The deployment must declare\n worklist.max_workers >= N, one account per worker, and items_independent:\n true. Each item is claimed once; a halt on any worker stops new items on\n all of them.\n --readback-window K Let a worker start its next item while up to K earlier saves still wait\n for their system-of-record read-back (default: worklist.readback_window,\n normally 0). A failed read-back stops the run and names the items written\n after it.\n --attest-contract PATH\n OPT-IN: effect-contract YAML for the openadapt-attest proof sidecar. After\n the run it verifies the claimed effect against the system of record and\n writes a SIGNED receipt (attest_receipt.json) into the run directory.\n Never changes the run outcome or exit code. Env fallback:\n OPENADAPT_FLOW_ATTEST_CONTRACT\n --attest-sign-key PATH\n Signing key for the attest receipt (env fallback:\n OPENADAPT_FLOW_ATTEST_SIGN_KEY)\n --attest-audit-log PATH\n Append-only audit log the attest sidecar writes to (env fallback:\n OPENADAPT_FLOW_ATTEST_AUDIT_LOG)\n --attest-pre-state PATH\n Existing pre-actuation system-of-record snapshot for delta checks. When\n omitted, replay captures one into the run directory\n (attest_pre_state.json) before actuation begins (env fallback:\n OPENADAPT_FLOW_ATTEST_PRE_STATE)\n --policy NAME-OR-PATH\n Certifying policy the bundle must PASS to run (default: the deployment\n config's policy, else 'clinical-write')\n --approve-unverified-writes\n APPROVAL FALLBACK: explicitly approve executing writes whose effects\n cannot be independently verified in this deployment (no verifier\n configured). Without it such a bundle is refused\n --strict-templates Refuse (not just warn) when template/screenshot assets are unsealed\n (plaintext at rest)\n --allow-unencrypted Escape hatch: permit running a bundle whose workflow.json is NOT encrypted\n at rest (disables the encryption gate). Discouraged\n --pin-digest SHA256 Refuse unless the bundle's sealed content digest equals this\n --pin-version VERSION\n Refuse unless the bundle's compiler version equals this\n --subroutine-library JSON\n Current subroutine library to re-admit embedded subroutines against before\n this run. Required when the bundle embeds a subroutine; a certification\n made before a newer version was published does not let the old version\n run.\n --subroutine-workflow-id ID\n Id this workflow was registered under when it was certified (default: the\n workflow name)\n --permission-trust PATH, --qualification-trust PATH\n Trusted signers for process run permissions. Also\n OPENADAPT_QUALIFICATION_TRUST or qualification-trust.json beside process-\n contract.json. --qualification-trust is deprecated; use --permission-\n trust.\n --execute-url URL HTTPS Execute v1 base URL for process children (OPENADAPT_EXECUTE_URL).\n Local process run uses governed run unless this and a bearer token are set\n --execute-environment-id ID\n Execute environment_id for process children\n (OPENADAPT_EXECUTE_ENVIRONMENT_ID)\n --code-trust PATH Code-admission Ed25519 signer registry for ProcessContract v1. Required\n when the contract contains a code child.\n --code-runtime-environment-digest SHA256\n Exact admitted runtime-environment digest for code children\n --allow-trusted-code Approve exact admitted code that uses the trusted_local profile\n --process-receipt-private-key PATH\n Raw 32-byte Ed25519 key for the ProcessContract v1 terminal receipt\n --process-receipt-issuer-key-id PROCESS_RECEIPT_ISSUER_KEY_ID\n --process-environment-id PROCESS_ENVIRONMENT_ID\n --process-runner-id PROCESS_RUNNER_ID\n --qualification-authority-file PATH\n Private owner-only Production qualification authority (v2 envelope or\n issued openadapt.qualification-admission/v4). Required for Standard and\n Regulated actuation; verified and re-read at every input edge\n --dry-run, --explain Print the fail-closed coverage report and exit WITHOUT executing\n --report OPT-IN: after a SUCCESSFUL run, emit the PHI-free run summary to the\n paired hosted control plane (see `report-run`). Off by default \u2014 nothing\n is ever uploaded without this flag (or OPENADAPT_FLOW_REPORT_RUN=1)\n --cloud-execution-id CLOUD_EXECUTION_ID\n OpenAdapt Cloud Execute execution this run belongs to (or\n OPENADAPT_CLOUD_EXECUTION_ID). After a VERIFIED outcome, Cloud's signed\n receipt is fetched with OPENADAPT_EXECUTE_API_KEY and written into\n report.json as execute_receipt.\n --approver-root HEX The root approver key (64 hex) this run trusts: a person's answer counts\n only when its signer is on the signed approver roster this key vouches\n for. Also set by the deployment config's approvers.root_public_key or\n OPENADAPT_APPROVER_ROOT; without one, a person's answer is refused\n --key-dir KEY_DIR Key directory with the signed approver roster (approvers.json) that\n approvals are checked against; use the one you approved with (default\n $OPENADAPT_JIT_KEY_DIR or ~/.openadapt/jit)\n --approver-policy FILE\n A person-signed approver grant (openadapt-flow approver-grant sign): which\n agents or systems may answer which classes of save, until when. Without a\n grant that verifies against the signer registry, only a person may answer;\n an unsigned or tampered file gives no authority. A clinical_write save\n takes a non-person approver only when the grant's policy pins an opt-in.\n --started-by ID The agent or system that started this run (opaque id). It can never answer\n this run's saves. openadapt-agent sets it.\n --approver-webhook URL\n Ask this https endpoint (the customer's approver agent or system) about\n each waiting save, with HMAC-signed, PHI-free messages. The secret is read\n from OPENADAPT_APPROVER_WEBHOOK_SECRET. A person can still answer in\n Desktop. Needs --approver-webhook-id and a policy that allows the\n approver's kind.\n --approver-webhook-id APPROVER_WEBHOOK_ID\n The webhook approver's opaque id, such as system:acme-approvals\n --approver-webhook-kind {agent,system}\n Whether the webhook approver is an agent or a system (default system)\n --approval-mode {each_item,problems_only,not_gated}\n Per-item approval before each consequential save. each_item (the default\n for every run): the run waits before every save until a person approves it\n in Desktop's Run it (see `item-approval`). problems_only: only problems go\n to a person; until a switch record is configured, every save still asks.\n not_gated: no per-item pause, recorded in the report (the hosted runner,\n Execute and MCP callers). Overrides runtime.approval_mode. A resume always\n keeps the run's own mode.\n --approval-wait SECONDS\n How long the run waits for a person's answer before it stops before the\n save (default 900, at most 14400). An answer given later can still be used\n by `resume`.\n --no-encrypt Write this command's output in plaintext (recorded in\n ~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is encrypted\n by default; same as OPENADAPT_ENCRYPT_AT_REST=0. Ignored under\n OPENADAPT_FLOW_AT_REST=strict\n\nself-repair:\n When the run halts before any effect because a screen changed, a repair agent proposes a fix,\n Flow probes it up to the save, and one person approves it before the run resumes. On by\n default whenever a repair agent is configured (here or in the deployment file's repair\n section). See docs/SELF_REPAIR.md.\n\n --self-repair Require self-repair for this run (web runs against --url): refuse the run\n when it can't be repaired.\n --no-auto-repair Do not hand stops to the repair agent; a stop waits for a person.\n --repair-agent MODULE:NAME\n The repair agent: an object, class or factory with dialect, agent_id and\n propose(request).\n --repair-screen-access-by NAME\n The person who allowed the agent to see screens (recorded).\n --repair-screen-share-mode {scrubbed_only,allow_unscrubbed}\n Scrub screens before the agent sees them (default) or not.\n --repair-model-provider {anthropic,openai}\n Load the customer's own key for an agent that calls a model.\n --repair-model-key-file PATH\n The customer's key file ({\"anthropic\": {\"api_key\": ...}}).\n --repair-store REPAIR_STORE\n The repair store the candidate enters (default repair-store/).\n --repair-attempts REPAIR_ATTEMPTS\n Proposals tried for one halt (default 3).\n --repair-fault-url URL\n A URL that presents a fault the patched run must refuse before the save\n (repeatable). Needed when the step's identity is read from the DOM.\n --repair-approval-wait SECONDS\n How long to wait for a person's answer (default 900).\n\nRelated operations (immediately after the task name): --for-each, --process, --dispatch, --route,\n--replay, --resume, --triage, --task-admit, --guard, --flight, --plan\n", "openadapt-flow sanitize": "usage: openadapt-flow sanitize [-h] --out OUT --kind {recording,bundle} [--redactions REDACTIONS]\n [--overwrite]\n path\n\npositional arguments:\n path Original recording or bundle directory\n\noptions:\n -h, --help show this help message and exit\n --out OUT New sanitized derivative directory\n --kind {recording,bundle}\n Artifact type\n --redactions REDACTIONS\n Optional local JSON file with additional text/image redactions\n --overwrite Replace an existing derivative (never modifies the original)\n\nAlso available as: openadapt-flow compile --sanitize\n", "openadapt-flow scaffold-verifier": "usage: openadapt-flow scaffold-verifier [-h] [-o DIR] [--db SQLITE] [--verifier YAML]\n [--prove FIXTURE] [--complete-read] [--fault-gate]\n [--probe-reads] [--probe-base URL] [--recording DIR]\n [--bundle DIR]\n source\n\npositional arguments:\n source Recording directory OR workflow bundle directory\n\noptions:\n -h, --help show this help message and exit\n -o DIR, --out DIR Directory for the proposed check or drafted effect_contract.yaml (default:\n beside the input)\n --db SQLITE Read-only database read path (SQLite file): find the saved row in every table\n and guard the rest with a no-new-rows check\n --verifier YAML A verify.yaml whose `verifier:` section reads the system of record (REST,\n FHIR, SQL); read once to find the saved record\n --prove FIXTURE Also run the proposed check end to end against this caller-supplied fault\n fixture (requires an injected proof source)\n --complete-read Declare that the reads return everything the save can change (one store, no\n other tables). Recorded as declared, not proven\n --fault-gate With --db: write each bad save to a copy of the database and let the check\n read it through its own read (the fault gate). A fault the read can't see\n keeps the check a draft\n --probe-reads When the recording never reads the saved record back, derive reads from the\n captured write and probe them with GET on a local copy of the app; use one\n only when it returns the written values. Every probe is recorded in the proof\n --probe-base URL With --probe-reads: the local copy of the app to probe (default: the recorded\n origin, which must be the local machine)\n --recording DIR The recording a bundle was compiled from (when SOURCE is a bundle)\n --bundle DIR The bundle compiled from this recording, for identity coverage (when SOURCE\n is a recording)\n\nAlso available as: openadapt-flow compile --scaffold-verifier\n", "openadapt-flow seal": "usage: openadapt-flow seal [-h] -o OUT source\n\npositional arguments:\n source Existing workflow bundle directory\n\noptions:\n -h, --help show this help message and exit\n -o OUT, --out OUT New destination directory (must not already exist)\n\nAlso available as: openadapt-flow setup encrypt\n", @@ -329,6 +335,7 @@ "approve": [], "approve-sanitized": [], "approver-grant": [], + "at-rest": [], "attach-seal": [], "bench": [], "benchmark": [], @@ -1207,6 +1214,193 @@ "commands": {}, "exclusive": [] }, + "openadapt-flow at-rest": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + } + ], + "commands": { + "archive": [], + "recovery": [], + "shred": [], + "status": [] + }, + "exclusive": [] + }, + "openadapt-flow at-rest archive": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + } + ], + "commands": {}, + "exclusive": [] + }, + "openadapt-flow at-rest recovery": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + } + ], + "commands": { + "create": [] + }, + "exclusive": [] + }, + "openadapt-flow at-rest recovery create": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "replace", + "help": null, + "metavar": null, + "nargs": 0, + "options": [ + "--replace" + ], + "required": false, + "type": null + } + ], + "commands": {}, + "exclusive": [] + }, + "openadapt-flow at-rest shred": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "dir", + "help": "The encrypted directory", + "metavar": null, + "nargs": null, + "options": [], + "required": true, + "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "yes", + "help": "Confirm; this can't be undone", + "metavar": null, + "nargs": 0, + "options": [ + "--yes" + ], + "required": false, + "type": null + } + ], + "commands": {}, + "exclusive": [] + }, + "openadapt-flow at-rest status": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "json", + "help": null, + "metavar": null, + "nargs": 0, + "options": [ + "--json" + ], + "required": false, + "type": null + } + ], + "commands": {}, + "exclusive": [] + }, "openadapt-flow attach-seal": { "arguments": [ { @@ -2306,6 +2500,20 @@ ], "required": false, "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "no_encrypt", + "help": "Write this command's output in plaintext (recorded in ~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. Ignored under OPENADAPT_FLOW_AT_REST=strict", + "metavar": null, + "nargs": 0, + "options": [ + "--no-encrypt" + ], + "required": false, + "type": null } ], "commands": {}, @@ -20568,6 +20776,20 @@ ], "required": false, "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "no_encrypt", + "help": "Write this command's output in plaintext (recorded in ~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. Ignored under OPENADAPT_FLOW_AT_REST=strict", + "metavar": null, + "nargs": 0, + "options": [ + "--no-encrypt" + ], + "required": false, + "type": null } ], "commands": {}, @@ -23467,6 +23689,20 @@ ], "required": false, "type": "float" + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "no_encrypt", + "help": "Write this command's output in plaintext (recorded in ~/.openadapt/plaintext-at-rest.jsonl, with a warning). Output is encrypted by default; same as OPENADAPT_ENCRYPT_AT_REST=0. Ignored under OPENADAPT_FLOW_AT_REST=strict", + "metavar": null, + "nargs": 0, + "options": [ + "--no-encrypt" + ], + "required": false, + "type": null } ], "commands": {}, From 44f7d75df8bcafeced7af6794e99b0fffb601154 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 18:18:43 -0500 Subject: [PATCH 22/37] test(flow): the records.json receipt test writes outside a run under the opt-out --- packages/flow/tests/test_records_read_step.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/flow/tests/test_records_read_step.py b/packages/flow/tests/test_records_read_step.py index f5d57851bb..f239889e32 100644 --- a/packages/flow/tests/test_records_read_step.py +++ b/packages/flow/tests/test_records_read_step.py @@ -229,7 +229,10 @@ def test_recorded_read_compiles_to_read_step_and_replays(tmp_path) -> None: assert report.model_calls == 0 -def test_seal_pointers_come_from_the_run_receipt(tmp_path) -> None: +def test_seal_pointers_come_from_the_run_receipt(tmp_path, monkeypatch) -> None: + # The receipt folder here is not an encrypted run directory, so the field + # values go there in plaintext only under the recorded opt-out. + monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "synthetic test data") import hashlib from openadapt_flow.records.run import ( From 2321f4bfcf515cbe6259ba0e98d3d91f432ba116 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 18:36:17 -0500 Subject: [PATCH 23/37] flow: seal rollback records in encrypted runs, bind solo sets to their device - rollback writes its compensated marker and difference files through the run's sealed set when the run is encrypted (the default), and was_compensated reads the marker there; a run whose state can't be read is never treated as resumable. - A key record carried in a header opens silently only with this computer's device key. A set that only the recovery code opens (which anyone who read recovery.pub.json could make) is refused until the person restores it: `openadapt-flow at-rest restore DIR --yes` rewraps it to this device and re-stamps the header, or OPENADAPT_RECOVERY_RESTORE=1 reads backups in place. - CI: flow core unit shard 1 also runs the rollback, checkpoint and key suites with OPENADAPT_TEST_DEFAULT_AT_REST=1. - Regenerate the CLI surface snapshot (at-rest restore) and llms-full.txt. --- .github/workflows/packages.yml | 14 +++++ CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/CHANGELOG.md | 5 +- .../commands/08-run-on-premises/at-rest.md | 2 +- packages/flow/docs/phi_at_rest.md | 19 +++++-- packages/flow/openadapt_flow/cli_at_rest.py | 40 ++++++++++++- packages/flow/openadapt_flow/key_hierarchy.py | 53 +++++++++++++++++- packages/flow/openadapt_flow/rollback.py | 28 +++++++++- .../openadapt_flow/runtime/durable/resume.py | 10 +++- packages/flow/openadapt_flow/sealed_set.py | 49 +++++++++++++++- packages/flow/tests/fixtures/cli_surface.json | 51 ++++++++++++++++- .../flow/tests/test_at_rest_review_round3.py | 33 +++++++++++ packages/flow/tests/test_durable_runtime.py | 11 +++- packages/flow/tests/test_key_hierarchy.py | 56 +++++++++++++++++++ packages/flow/tests/test_rollback.py | 14 +++-- 16 files changed, 364 insertions(+), 25 deletions(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 1292dba79c..508e352df5 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -882,6 +882,20 @@ jobs: fi exit "$unit_rc" # Before the claims upload, which tests expect to be the last step. + - name: Rollback, checkpoint and key tests under the default (encrypted) mode + # The suite above runs with a recorded plaintext opt-out. Encryption is + # the default, so run the stores that keep their own state inside a + # run directory (rollback, durable checkpoints, the key hierarchy) + # with it off as well: a plaintext write inside an encrypted run, or a + # reader that assumes plaintext, fails here. + if: matrix.shard == 1 + env: + OPENADAPT_TEST_DEFAULT_AT_REST: "1" + run: >- + pytest -n logical --dist loadfile -q --basetemp=runs/ci-default-at-rest + tests/test_rollback.py tests/test_rollback_qualify.py + tests/test_checkpoint_key_derivations.py tests/test_key_hierarchy.py + tests/test_at_rest_review_round3.py - name: Upload coverage data if: always() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 61cbe0565a..1e0c30fc0a 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -481,7 +481,7 @@ A test fails when a command has no file or this list is out of date. **Run on premises:** -- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. +- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, `restore` for a backup only the recovery code opens, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. - `no-outbound` - `service` diff --git a/llms-full.txt b/llms-full.txt index ada7ba2711..3594d90ed8 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -941,7 +941,7 @@ A test fails when a command has no file or this list is out of date. **Run on premises:** -- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. +- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, `restore` for a backup only the recovery code opens, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. - `no-outbound` - `service` diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index cfa6bbf057..f1d1153518 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -56,7 +56,10 @@ file is gone. Organization mode requires `records: archive`. Durable checkpoints in an encrypted run are keyed from the run's own data key. `--no-encrypt` lasts for one command, and the Python recorders follow the - at-rest policy by default. + at-rest policy by default. A solo set opens silently only with the device + key that wrote it; a backup that only the recovery code opens needs + `openadapt-flow at-rest restore DIR --yes`. Rollback records in an + encrypted run stay inside its sealed set. ### Features diff --git a/packages/flow/docs/commands/08-run-on-premises/at-rest.md b/packages/flow/docs/commands/08-run-on-premises/at-rest.md index e25f2b7478..5a3f0741f2 100644 --- a/packages/flow/docs/commands/08-run-on-premises/at-rest.md +++ b/packages/flow/docs/commands/08-run-on-premises/at-rest.md @@ -1 +1 @@ -Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. +Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, `restore` for a backup only the recovery code opens, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index d72e74ac2c..db3a96ebb4 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -253,9 +253,19 @@ not built yet. `openadapt-flow at-rest recovery create` makes a recovery key: 32 random bytes shown once as a 52-character code, turned into a P-256 key with HPKE's DeriveKeyPair. Only its public half is stored; it becomes a recipient of -every new set. Open with it on another computer by setting -`OPENADAPT_RECOVERY_CODE`. Without one, a lost or reset computer means its -encrypted runs can't be opened. +every new set. Without one, a lost or reset computer means its encrypted +runs can't be opened. + +A set's own header carries its key record in solo mode, so the set is bound +to the computer that wrote it: only that computer's device key opens it +silently (the device's public key is never written out). The recovery +public key is on disk, so anyone who reads it could make a set the code +opens. The code therefore never opens a set silently. To use a backup on a +new or reset computer, set `OPENADAPT_RECOVERY_CODE` and run +`openadapt-flow at-rest restore DIR --yes`, which wraps that set to this +computer's device key so it opens here from then on. Where no device key can +be made (a restored home whose keychain entry is gone), +`OPENADAPT_RECOVERY_RESTORE=1` with the code reads backups in place. ### Legacy keys @@ -335,7 +345,8 @@ recorder, before the first write, is not built yet. | Variable | Used for | | --- | --- | | `OPENADAPT_POLICY` | A policy file, when no machine policy exists. | -| `OPENADAPT_RECOVERY_CODE` | The solo recovery code, to open sets on another computer. | +| `OPENADAPT_RECOVERY_CODE` | The solo recovery code, for `at-rest restore` on another computer. | +| `OPENADAPT_RECOVERY_RESTORE` | `1`: read backups in place with the recovery code (an explicit restore). | | `OPENADAPT_ORG_KEY_FILE` | An organization recipient's PEM private key, for a reviewer. | | `OPENADAPT_FLOW_KEY_STORE` | Where the software device key is kept: `auto`, `keychain` or `file`. | | `OPENADAPT_BUNDLE_KEY` | Deprecated: a passphrase for bundles and their run directories (version 1 header). | diff --git a/packages/flow/openadapt_flow/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py index 2e24441e72..798592ea48 100644 --- a/packages/flow/openadapt_flow/cli_at_rest.py +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -6,6 +6,8 @@ key material. - ``recovery create`` makes a solo recovery key: the code is shown once and never stored; its public half becomes a recipient of every new run. +- ``restore DIR --yes`` lets this computer open a backup that only the + recovery code opens (it is never opened by the code silently). - ``shred DIR --yes`` destroys an encrypted set's bucket key (every tracked copy), so nobody can open it. It can't be undone. @@ -140,6 +142,30 @@ def _cmd_shred(args: argparse.Namespace) -> int: return 0 +def _cmd_restore(args: argparse.Namespace) -> int: + from openadapt_flow import key_hierarchy as kh + from openadapt_flow import sealed_set + + root = Path(args.dir) + if not sealed_set.is_sealed(root): + print(f"at-rest restore: {root} is not an encrypted set", file=sys.stderr) + return 2 + if not args.yes: + print( + f"at-rest restore: this lets this computer open {root} from now on, " + "with the recovery code. Restore only a backup you made. Pass --yes.", + file=sys.stderr, + ) + return 2 + try: + fpr = sealed_set.restore(root) + except sealed_set.SealedSetError as exc: + print(f"at-rest restore: {exc} (set {kh.RECOVERY_CODE_ENV})", file=sys.stderr) + return 2 + print(f"Restored {root}: it now opens with this computer's device key ({fpr}).") + return 0 + + #: Commands that read sealed input without decrypting it to disk: #: ``inspect report-run`` and ``local-seal verify`` read the report in #: memory; ``shred`` touches keys. @@ -147,6 +173,7 @@ def _cmd_shred(args: argparse.Namespace) -> int: { "openadapt_flow.__main__:_cmd_report_run", "openadapt_flow.cli_at_rest:_cmd_shred", + "openadapt_flow.cli_at_rest:_cmd_restore", "openadapt_flow.cli_local_seal:_cmd_verify", } ) @@ -194,7 +221,10 @@ def precheck_open(root: object) -> None: if sealed_set.read_header(root).get("shredded"): # type: ignore[arg-type] return - sealed_set.open_set(root) # type: ignore[arg-type] + try: + sealed_set.open_set(root) # type: ignore[arg-type] + except sealed_set.SealedSetRestoreRequired: + return # `at-rest restore` opens it; any other command still refuses def add_no_encrypt(p: argparse.ArgumentParser) -> None: @@ -269,6 +299,14 @@ def register(sub: argparse._SubParsersAction) -> None: ) c.add_argument("--replace", action="store_true") c.set_defaults(func=_cmd_recovery_create) + s = rsub.add_parser( + "restore", + help="Let this computer open a backup that only the recovery code opens", + allow_abbrev=False, + ) + s.add_argument("dir", help="The encrypted directory") + s.add_argument("--yes", action="store_true", help="Confirm it is your backup") + s.set_defaults(func=_cmd_restore) s = rsub.add_parser( "shred", help="Destroy an encrypted set's bucket key; nobody can open it after", diff --git a/packages/flow/openadapt_flow/key_hierarchy.py b/packages/flow/openadapt_flow/key_hierarchy.py index 63ca9791c1..f53841399c 100644 --- a/packages/flow/openadapt_flow/key_hierarchy.py +++ b/packages/flow/openadapt_flow/key_hierarchy.py @@ -70,6 +70,10 @@ #: (development and tests); machine policies never need it. TRUST_USER_POLICY_ENV: Final[str] = "OPENADAPT_POLICY_TRUST_USER_FILE" RECOVERY_CODE_ENV: Final[str] = "OPENADAPT_RECOVERY_CODE" +#: ``1``: the person is restoring backups with the recovery code, so a set +#: that only the code opens may be read (``at-rest restore`` rewraps one to +#: this computer instead). Never set by Flow itself. +RECOVERY_RESTORE_ENV: Final[str] = "OPENADAPT_RECOVERY_RESTORE" #: A PEM private key of an organization or break-glass recipient, for a #: reviewer opening evidence without a KMS (KMS unwrap is not built yet). ORG_KEY_FILE_ENV: Final[str] = "OPENADAPT_ORG_KEY_FILE" @@ -116,6 +120,12 @@ class NoRecipientKey(KeyHierarchyError): """No key this computer holds opens the bucket record.""" +class RecoveryRestoreRequired(NoRecipientKey): + """Only the recovery code opens this set, and it was not written on this + computer (or its device key is gone): it opens only through an explicit + restore (``at-rest restore``), never silently.""" + + # -- primitives -------------------------------------------------------------- @@ -1142,13 +1152,22 @@ def _candidates( def open_bucket( - record: dict[str, Any], *, prefer_runtime: bool = True, from_header: bool = False + record: dict[str, Any], + *, + prefer_runtime: bool = True, + from_header: bool = False, + restore: bool = False, ) -> Bucket: """Unwrap a bucket's private half with the first key this computer holds. ``from_header``: the record came from the set's own header, not from - this computer's key store. Only a device key or a recovery key may open - it then, through a stanza of that role. + this computer's key store. Only this computer's device key opens it then, + which binds the set to the device that wrote it: its public key is never + written out, so nobody else can wrap a bucket to it. The recovery public + key is on disk, so a set that only the recovery code opens could have + been made by anyone who read that file. It opens only with ``restore`` + (``at-rest restore DIR``, the person's explicit choice), and otherwise + raises :class:`RecoveryRestoreRequired`. """ if record.get("schema") != BUCKET_SCHEMA: raise KeyHierarchyError("not a bucket record") @@ -1162,6 +1181,7 @@ def open_bucket( ) stanzas = {s.get("fpr"): s for s in record.get("stanzas") or []} keys, deferred = _candidates(from_header=from_header) + needs_restore = False for key in keys: try: fpr = key.fpr @@ -1172,6 +1192,13 @@ def open_bucket( continue if from_header and str(stanza.get("role")) not in _HEADER_ROLES: continue + if ( + from_header + and stanza.get("role") == ROLE_RECOVERY + and not (restore or os.environ.get(RECOVERY_RESTORE_ENV) == "1") + ): + needs_restore = True + continue info = _stanza_info(bucket_id, str(stanza["role"]), fpr) try: secret = key.unwrap(_unb64(stanza["ct"]), info) @@ -1187,6 +1214,15 @@ def open_bucket( "the unwrapped bucket key does not match the record" ) return Bucket(bucket_id, private, private.public_key(), record) # type: ignore[arg-type] + if needs_restore: + raise RecoveryRestoreRequired( + "this encrypted set opens only with the recovery code: this computer's " + "device key does not open it, so Flow can't tell it was written here " + "rather than made by someone who read the recovery public key. If it " + "is your backup, restore it with the code: `openadapt-flow at-rest " + f"restore DIR --yes`, or set {RECOVERY_RESTORE_ENV}=1 to read your " + "backups with it. Nothing was read." + ) if deferred is not None: raise deferred raise NoRecipientKey( @@ -1197,6 +1233,16 @@ def open_bucket( ) +def device_stanza(bucket: Bucket) -> dict[str, str]: + """A stanza wrapping ``bucket`` to this computer's viewer key (made if + missing), for a set restored with the recovery code.""" + device = device_keys(create=True) + assert device is not None and bucket.private is not None + viewer = device[1] + recipient = Recipient(viewer.role or ROLE_VIEWER, HPKE_P256, viewer.public()) + return _stanza(recipient, bucket.bucket_id, _scalar(bucket.private)) + + def _pending_dir() -> Path: return _home() / "keys" / "shred-pending" @@ -1387,6 +1433,7 @@ def describe(policy: Policy) -> dict[str, Any]: "HardwareDouble", "KeyHierarchyError", "NoRecipientKey", + "RecoveryRestoreRequired", "Policy", "Recipient", "SoftwareKey", diff --git a/packages/flow/openadapt_flow/rollback.py b/packages/flow/openadapt_flow/rollback.py index 83d69b7524..c099570d03 100644 --- a/packages/flow/openadapt_flow/rollback.py +++ b/packages/flow/openadapt_flow/rollback.py @@ -120,7 +120,20 @@ def _private_dir(path: Path) -> None: os.chmod(path, 0o700) +def _in_sealed_run(path: Path) -> bool: + from openadapt_flow import sealed_set + + return sealed_set.is_sealed_path(path) + + def _write_private(path: Path, payload: dict[str, Any]) -> None: + if _in_sealed_run(path): + # An encrypted run (the default): through its sealed set, ciphertext only. + from openadapt_flow import sealed_set + + text = json.dumps(payload, indent=2, sort_keys=True, default=str) + sealed_set.write_text(path, text) + return _private_dir(path.parent) staging = path.with_name(f".{path.name}.{os.getpid()}") # A leftover staging file would keep its own mode: start from nothing. @@ -135,6 +148,19 @@ def _write_private(path: Path, payload: dict[str, Any]) -> None: os.replace(staging, path) +def _mark_compensated(run_dir: Path) -> None: + """The store may change from here: the run can't be resumed. Inside an + encrypted run the marker goes through its sealed set, never as a stray + plaintext file its readers would refuse.""" + marker = run_dir / COMPENSATED_MARKER + if _in_sealed_run(run_dir): + from openadapt_flow import sealed_set + + sealed_set.write_bytes(marker, b"") + return + marker.touch() + + # --------------------------------------------------------------------------- # Is the step's change there? (a fresh read, for an uncertain write) # --------------------------------------------------------------------------- @@ -911,7 +937,7 @@ def drifted(now: Snapshot, since: Snapshot) -> Optional[str]: break sub_dir = run_dir / ROLLBACK_DIRNAME / undo.id # From here the store may change: the run can't be resumed. - (run_dir / COMPENSATED_MARKER).touch() + _mark_compensated(run_dir) try: if journal is not None: journal.step(entry.step_id, "started") diff --git a/packages/flow/openadapt_flow/runtime/durable/resume.py b/packages/flow/openadapt_flow/runtime/durable/resume.py index 683f05a825..2b052c5820 100644 --- a/packages/flow/openadapt_flow/runtime/durable/resume.py +++ b/packages/flow/openadapt_flow/runtime/durable/resume.py @@ -1086,9 +1086,17 @@ def _begin_continuation( def was_compensated(run_dir: Path | str) -> bool: """Did a compensating rollback start undoing this run (docs/ROLLBACK.md)? Every resume path checks it: the CLI, the attended console and the relay.""" + from openadapt_flow import sealed_set from openadapt_flow.rollback import COMPENSATED_MARKER - return (Path(run_dir) / COMPENSATED_MARKER).exists() + marker = Path(run_dir) / COMPENSATED_MARKER + if marker.exists(): + return True + try: + # An encrypted run keeps the marker in its sealed set. + return sealed_set.exists(marker) + except (OSError, ValueError): # a SealedSetError is a ValueError + return True # can't tell: never resume a run that may be undone def resume( diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index 8574fa4a7a..3b9fd69974 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -94,6 +94,11 @@ class SealedSetKeyError(SealedSetError): """A sealed set was found but no key was configured to open it.""" +class SealedSetRestoreRequired(SealedSetKeyError): + """Only the recovery code opens this set; it opens only through an + explicit restore (:func:`restore`).""" + + @dataclass(frozen=True) class FileKind: """One kind of file a bundle or recording can contain.""" @@ -633,7 +638,7 @@ def check(self, header: dict[str, object]) -> None: ) -def _open_v3(header: dict[str, object]) -> V3Key: +def _open_v3(header: dict[str, object], *, restore: bool = False) -> V3Key: """Open a version 3 set: find its bucket record, unwrap the bucket key with a key this computer holds, unwrap the DEK, check the header MACs.""" from openadapt_flow import key_hierarchy as kh @@ -659,7 +664,9 @@ def _open_v3(header: dict[str, object]) -> V3Key: raise SealedSetError("the bucket record belongs to another set") # A record the header supplies proves nothing about who wrote the # set: only this computer's device keys or a recovery key open it. - bucket = kh.open_bucket(record, from_header=record is inline) + bucket = kh.open_bucket(record, from_header=record is inline, restore=restore) + except kh.RecoveryRestoreRequired as exc: + raise SealedSetRestoreRequired(str(exc)) from exc except kh.NoRecipientKey as exc: raise SealedSetKeyError(str(exc)) from exc except kh.KeyHierarchyError as exc: @@ -1562,6 +1569,42 @@ def _replace_header(root: Path, header: dict[str, object]) -> None: os.close(fd) +def restore(root: Path | str) -> str: + """Restore a set that only the recovery code opens (a backup on a new or + reset computer): open it with ``OPENADAPT_RECOVERY_CODE``, wrap its + bucket to this computer's device key, and re-stamp the header MACs. From + then on it opens here like a set written here. The person runs this on + purpose (``at-rest restore DIR --yes``); a set from a header is never + opened by the recovery code silently. Returns the device fingerprint.""" + from openadapt_flow import key_hierarchy as kh + + base = Path(_abs(root)) + with mutation_lock(base): + header = read_header(base) + if header.get("version") != ENVELOPE_VERSION or not isinstance( + header.get("bucket_record"), dict + ): + raise SealedSetError( + f"{base} keeps no key record in its header; only a solo-mode " + "encrypted set is restored with the recovery code" + ) + key = _open_v3(header, restore=True) + bucket = key.bucket + try: + stanza = kh.device_stanza(bucket) # type: ignore[arg-type] + except kh.KeyHierarchyError as exc: + raise SealedSetError(f"Not restoring {base}: {exc}") from exc + record = dict(header["bucket_record"]) # type: ignore[arg-type] + stanzas = [ + s for s in record.get("stanzas", []) if s.get("fpr") != stanza["fpr"] + ] + record["stanzas"] = [*stanzas, stanza] + header["bucket_record"] = record + key.stamp(header) + _replace_header(base, header) + return stanza["fpr"] + + def key_record_of(root: Path | str) -> Optional[dict[str, object]]: """The bucket record of a version 3 set (no key material in the clear): inline in the header, or this computer's local copy. None otherwise.""" @@ -1732,6 +1775,8 @@ def shred(root: Path | str) -> dict[str, object]: "SealedSet", "SealedSetError", "SealedSetKeyError", + "SealedSetRestoreRequired", + "restore", "SealedSetWriter", "append_line", "classify", diff --git a/packages/flow/tests/fixtures/cli_surface.json b/packages/flow/tests/fixtures/cli_surface.json index f028eb4066..72b0e8a250 100644 --- a/packages/flow/tests/fixtures/cli_surface.json +++ b/packages/flow/tests/fixtures/cli_surface.json @@ -15,10 +15,11 @@ "openadapt-flow approver-grant": "usage: openadapt-flow approver-grant [-h] {sign,verify} ...\n\npositional arguments:\n {sign,verify}\n sign Sign a grant with your policy-signer key\n verify Check a signed grant against the registry\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup approver-grant\n", "openadapt-flow approver-grant sign": "usage: openadapt-flow approver-grant sign [-h] --key KEY --out OUT [--key-dir KEY_DIR] grant\n\npositional arguments:\n grant Unsigned openadapt-flow/approver-grant/v1 JSON\n\noptions:\n -h, --help show this help message and exit\n --key KEY Your encrypted policy-signer key\n --out OUT\n --key-dir KEY_DIR\n\nAlso available as: openadapt-flow setup approver-grant sign\n", "openadapt-flow approver-grant verify": "usage: openadapt-flow approver-grant verify [-h] [--key-dir KEY_DIR] grant\n\npositional arguments:\n grant Signed grant JSON\n\noptions:\n -h, --help show this help message and exit\n --key-dir KEY_DIR\n\nAlso available as: openadapt-flow setup approver-grant verify\n", - "openadapt-flow at-rest": "usage: openadapt-flow at-rest [-h] {status,archive,recovery,shred} ...\n\npositional arguments:\n {status,archive,recovery,shred}\n status Where the keys are and who can open new runs\n archive Send key records and pending shreds to the organization archive\n recovery The solo recovery key\n shred Destroy an encrypted set's bucket key; nobody can open it after\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup at-rest\n", + "openadapt-flow at-rest": "usage: openadapt-flow at-rest [-h] {status,archive,recovery,restore,shred} ...\n\npositional arguments:\n {status,archive,recovery,restore,shred}\n status Where the keys are and who can open new runs\n archive Send key records and pending shreds to the organization archive\n recovery The solo recovery key\n restore Let this computer open a backup that only the recovery code opens\n shred Destroy an encrypted set's bucket key; nobody can open it after\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup at-rest\n", "openadapt-flow at-rest archive": "usage: openadapt-flow at-rest archive [-h]\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup at-rest archive\n", "openadapt-flow at-rest recovery": "usage: openadapt-flow at-rest recovery [-h] {create} ...\n\npositional arguments:\n {create}\n create Make a recovery key; the code is shown once\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup at-rest recovery\n", "openadapt-flow at-rest recovery create": "usage: openadapt-flow at-rest recovery create [-h] [--replace]\n\noptions:\n -h, --help show this help message and exit\n --replace\n\nAlso available as: openadapt-flow setup at-rest recovery create\n", + "openadapt-flow at-rest restore": "usage: openadapt-flow at-rest restore [-h] [--yes] dir\n\npositional arguments:\n dir The encrypted directory\n\noptions:\n -h, --help show this help message and exit\n --yes Confirm it is your backup\n\nAlso available as: openadapt-flow setup at-rest restore\n", "openadapt-flow at-rest shred": "usage: openadapt-flow at-rest shred [-h] [--yes] dir\n\npositional arguments:\n dir The encrypted directory\n\noptions:\n -h, --help show this help message and exit\n --yes Confirm; this can't be undone\n\nAlso available as: openadapt-flow setup at-rest shred\n", "openadapt-flow at-rest status": "usage: openadapt-flow at-rest status [-h] [--json]\n\noptions:\n -h, --help show this help message and exit\n --json\n\nAlso available as: openadapt-flow setup at-rest status\n", "openadapt-flow attach-seal": "usage: openadapt-flow attach-seal [-h] --execution-id EXECUTION_ID [--cloud-url CLOUD_URL] run_dir\n\npositional arguments:\n run_dir Run directory holding a VERIFIED report.json\n\noptions:\n -h, --help show this help message and exit\n --execution-id EXECUTION_ID\n Cloud Execute execution id\n --cloud-url CLOUD_URL\n Cloud base URL (or OPENADAPT_CLOUD_URL; default https://app.openadapt.ai)\n\nAlso available as: openadapt-flow verify attach-seal\n", @@ -1235,6 +1236,7 @@ "commands": { "archive": [], "recovery": [], + "restore": [], "shred": [], "status": [] }, @@ -1319,6 +1321,53 @@ "commands": {}, "exclusive": [] }, + "openadapt-flow at-rest restore": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "dir", + "help": "The encrypted directory", + "metavar": null, + "nargs": null, + "options": [], + "required": true, + "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "yes", + "help": "Confirm it is your backup", + "metavar": null, + "nargs": 0, + "options": [ + "--yes" + ], + "required": false, + "type": null + } + ], + "commands": {}, + "exclusive": [] + }, "openadapt-flow at-rest shred": { "arguments": [ { diff --git a/packages/flow/tests/test_at_rest_review_round3.py b/packages/flow/tests/test_at_rest_review_round3.py index bf80586abc..a56018fe36 100644 --- a/packages/flow/tests/test_at_rest_review_round3.py +++ b/packages/flow/tests/test_at_rest_review_round3.py @@ -210,3 +210,36 @@ def test_an_explicit_none_recorder_is_refused_in_strict_and_ledgered_otherwise( Recorder(_Backend(), tmp_path / "b", encryption_key=None) ledger = at_rest.ledger_path().read_text() assert str(tmp_path / "b") in ledger and "encryption_key=None" in ledger + + +def test_a_rollback_in_an_encrypted_run_keeps_its_marker_sealed( + default_mode: Path, tmp_path: Path +) -> None: + """Rollback proof in the default (encrypted) mode: the compensated marker + and the remaining-difference file go through the run's sealed set, the + run still opens, and resume still sees that the run was undone.""" + from openadapt_flow import rollback + from openadapt_flow.runtime.durable.resume import was_compensated + + run = tmp_path / "run" + writer = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) + sealed_set.register_writer(writer) + try: + writer.write("report.json", b"{}") + rollback._mark_compensated(run) + rollback._write_private( + run / rollback.ROLLBACK_DIRNAME / rollback.DIFF_FILENAME, + {"row": TYPED.decode()}, + ) + finally: + sealed_set.unregister_writer(writer) + writer.finalize(adopt_external=True) + assert not (run / rollback.COMPENSATED_MARKER).exists() # no stray plaintext + for path in run.rglob("*"): + if path.is_file(): + assert TYPED not in path.read_bytes(), path + sealed_set.SealedSet.open(run).verify_all() + assert was_compensated(run) is True + # A run whose state can't be read is never treated as resumable. + sealed_set.shred(run) + assert was_compensated(run) is True diff --git a/packages/flow/tests/test_durable_runtime.py b/packages/flow/tests/test_durable_runtime.py index c7bfdab07d..efb2ed6995 100644 --- a/packages/flow/tests/test_durable_runtime.py +++ b/packages/flow/tests/test_durable_runtime.py @@ -21,6 +21,7 @@ import pytest +from openadapt_flow import sealed_set as _sealed_set from openadapt_flow.ir import ( ActionDeliveryReceipt, ActionKind, @@ -828,7 +829,9 @@ def test_durable_resume_projection_failure_keeps_fail_closed_terminal_evidence( assert resumed.success is False assert resumed.execution_outcome == "FAILED" assert resumed.transaction_outcome == "RECONCILIATION_REQUIRED" - persisted = RunReport.model_validate_json((run_dir / "report.json").read_text()) + persisted = RunReport.model_validate_json( + _sealed_set.read_text(run_dir / "report.json") + ) assert persisted.execution_outcome == "FAILED" assert persisted.transaction_outcome == "RECONCILIATION_REQUIRED" assert persisted.results[-1].step_id == "" @@ -845,7 +848,7 @@ def test_durable_resume_projection_failure_keeps_fail_closed_terminal_evidence( assert ( record.report_sha256 == "sha256:" - + hashlib.sha256((run_dir / "report.json").read_bytes()).hexdigest() + + hashlib.sha256(_sealed_set.read_bytes(run_dir / "report.json")).hexdigest() ) assert authority.prove_executor_outcome( manifest, @@ -933,7 +936,9 @@ def test_indeterminate_durable_state_fails_closed_without_ledger_projection( assert "durable terminal state persistence failed" in ( report.results[-1].error or "" ) - persisted = RunReport.model_validate_json((run_dir / "report.json").read_text()) + persisted = RunReport.model_validate_json( + _sealed_set.read_text(run_dir / "report.json") + ) assert persisted.execution_outcome == "FAILED" assert ledger.lookup("indeterminate-durable-state-key")["outcome"] is None diff --git a/packages/flow/tests/test_key_hierarchy.py b/packages/flow/tests/test_key_hierarchy.py index a95dafb9f6..b9304aea1e 100644 --- a/packages/flow/tests/test_key_hierarchy.py +++ b/packages/flow/tests/test_key_hierarchy.py @@ -498,6 +498,12 @@ def test_a_recovery_code_opens_a_backup_on_a_new_computer(home, monkeypatch) -> with pytest.raises(sealed_set.SealedSetKeyError): sealed_set.read_bytes(run / "report.json") monkeypatch.setenv(kh.RECOVERY_CODE_ENV, code) + # The code alone does not open a set this computer didn't write: the + # person restores it on purpose, and from then on the device key opens it. + with pytest.raises(sealed_set.SealedSetRestoreRequired, match="restore"): + sealed_set.read_bytes(run / "report.json") + sealed_set.restore(run) + monkeypatch.delenv(kh.RECOVERY_CODE_ENV) assert sealed_set.read_bytes(run / "report.json") == TYPED @@ -825,6 +831,9 @@ def test_a_lost_keychain_entry_does_not_hide_the_recovery_code( with pytest.raises(sealed_set.SealedSetError, match="missing"): sealed_set.read_bytes(run / "report.json") monkeypatch.setenv(kh.RECOVERY_CODE_ENV, code) + with pytest.raises(sealed_set.SealedSetRestoreRequired): + sealed_set.read_bytes(run / "report.json") # never silently + monkeypatch.setenv(kh.RECOVERY_RESTORE_ENV, "1") # the person restores assert sealed_set.read_bytes(run / "report.json") == TYPED # Writing still needs the device key, and still fails closed without it. with pytest.raises((sealed_set.SealedSetError, at_rest.LocalKeyError)): @@ -938,3 +947,50 @@ class Bindings(BaseModel): plain / "s1.json", Bindings(typed=TYPED.decode()) ) assert written.name.endswith(".enc") and TYPED not in written.read_bytes() + + +def test_a_set_forged_to_the_recovery_public_key_is_refused(home, monkeypatch) -> None: + """Whoever reads keys/recovery.pub.json can wrap a bucket to it. Such a set + does not open here: the recovery code opens only what the person restores + on purpose, and a restore is refused without the code.""" + root, _keychain = home + code, recipient = kh.new_recovery_code() + kh.save_recovery_recipient(recipient) + genuine = root.parent / "genuine" + _seal(genuine, {"report.json": TYPED}) + # The forger: another computer, with only the public recovery key. + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "forger")) + at_rest.use_key_store(MemoryKeychain()) + kh.save_recovery_recipient(recipient) + forged = root.parent / "forged" + _seal(forged, {"report.json": b"forged evidence"}) + # Back on the person's computer, with the recovery code configured. + monkeypatch.setenv(at_rest.HOME_ENV, str(root)) + at_rest.use_key_store(_keychain) + monkeypatch.setenv(kh.RECOVERY_CODE_ENV, code) + assert sealed_set.read_bytes(genuine / "report.json") == TYPED # device key + with pytest.raises(sealed_set.SealedSetRestoreRequired): + sealed_set.read_bytes(forged / "report.json") + monkeypatch.delenv(kh.RECOVERY_CODE_ENV) + with pytest.raises(sealed_set.SealedSetKeyError): + sealed_set.restore(forged) + header = _header(forged) + with pytest.raises(sealed_set.SealedSetError): + sealed_set._open_v3(header) + + +def test_the_cli_restores_a_backup_with_the_recovery_code(home, monkeypatch) -> None: + from openadapt_flow.__main__ import main + + root, _keychain = home + code, recipient = kh.new_recovery_code() + kh.save_recovery_recipient(recipient) + run = root.parent / "run" + _seal(run, {"report.json": TYPED}) + monkeypatch.setenv(at_rest.HOME_ENV, str(root.parent / "new-laptop")) + at_rest.use_key_store(MemoryKeychain()) + monkeypatch.setenv(kh.RECOVERY_CODE_ENV, code) + assert main(["at-rest", "restore", str(run)]) == 2 # needs --yes + assert main(["at-rest", "restore", str(run), "--yes"]) == 0 + monkeypatch.delenv(kh.RECOVERY_CODE_ENV) + assert sealed_set.read_bytes(run / "report.json") == TYPED diff --git a/packages/flow/tests/test_rollback.py b/packages/flow/tests/test_rollback.py index 4cfa7733d9..b839d966bf 100644 --- a/packages/flow/tests/test_rollback.py +++ b/packages/flow/tests/test_rollback.py @@ -27,6 +27,7 @@ import pytest import requests +from openadapt_flow import sealed_set from openadapt_flow.after_stop import keep_prior_state from openadapt_flow.ir import ( ActionKind, @@ -268,7 +269,7 @@ def test_a_stop_after_a_save_is_rolled_back_and_proven(tmp_path, mockmed): assert _records(mockmed) == [] # The persisted report carries it, PHI-free. persisted = RunReport.model_validate_json( - (tmp_path / "run" / "report.json").read_text() + sealed_set.read_text(tmp_path / "run" / "report.json") ) assert persisted.rollback == rollback assert "p1" not in persisted.rollback.model_dump_json() @@ -287,8 +288,9 @@ def test_an_unapproved_proposal_is_never_used(tmp_path, mockmed): # Nothing was undone, and the person gets the exact difference. assert [r["type"] for r in _records(mockmed)] == ["Triage"] diff_path = tmp_path / "run" / rollback.diff_path - assert (diff_path.stat().st_mode & 0o777) == 0o600 - diff = json.loads(diff_path.read_text()) + if not sealed_set.is_sealed_path(diff_path): + assert (diff_path.stat().st_mode & 0o777) == 0o600 + diff = json.loads(sealed_set.read_text(diff_path)) [added] = diff["tables"]["records"]["added"] assert added["row"]["type"] == "Triage" assert "records: 1 added" in rollback.reason @@ -754,7 +756,7 @@ def test_a_compensation_that_leaves_a_side_record_is_named_precisely(tmp_path): } assert "history: 1 added" in rollback.reason assert report.transaction_outcome == "RECONCILIATION_REQUIRED" - diff = json.loads((tmp_path / "run" / rollback.diff_path).read_text()) + diff = json.loads(sealed_set.read_text(tmp_path / "run" / rollback.diff_path)) [row] = diff["tables"]["history"]["added"] assert row["row"]["smoker"] == "no" @@ -1757,7 +1759,7 @@ def test_a_late_write_hands_over_the_store_as_it_is(tmp_path): # named apart, as the stop left them. assert rollback.remaining_diff == {} assert rollback.late_diff_path - late = json.loads((tmp_path / "run" / rollback.late_diff_path).read_text()) + late = json.loads(sealed_set.read_text(tmp_path / "run" / rollback.late_diff_path)) assert "patients" in late["tables"] @@ -2684,6 +2686,8 @@ def test_a_durable_run_with_rollback_needs_a_key_to_seal_its_state( plan = RollbackPlan(DatabaseReader(dialect="sqlite")) monkeypatch.delenv("OPENADAPT_BUNDLE_KEY", raising=False) + # Under the plaintext opt-out no key resolves (by default the local one does). + monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "synthetic test data") with pytest.raises(SystemExit, match="OPENADAPT_BUNDLE_KEY"): _rollback_seal(plan, True, tmp_path) assert _rollback_seal(None, True, tmp_path) is None From 1ddb607c1e604939e22d0e2b173ef208ed3fbcc1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 19:39:42 -0500 Subject: [PATCH 24/37] fix(flow): use open_binary in key_hierarchy and satisfy mypy --- packages/flow/openadapt_flow/key_hierarchy.py | 10 +++++++--- packages/flow/openadapt_flow/sealed_set.py | 4 +++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/flow/openadapt_flow/key_hierarchy.py b/packages/flow/openadapt_flow/key_hierarchy.py index f53841399c..68c01247de 100644 --- a/packages/flow/openadapt_flow/key_hierarchy.py +++ b/packages/flow/openadapt_flow/key_hierarchy.py @@ -585,7 +585,9 @@ def _read_registry(subkey: str) -> Optional[dict]: # pragma: no cover - Windows """The ``Policy`` value under ``HKLM\\``. None only when the key does not exist; access denied or a key without the value is an error, so a policy the account can't read never falls back to solo mode.""" - import winreg + import importlib + + winreg: Any = importlib.import_module("winreg") try: handle = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey) @@ -599,8 +601,10 @@ def _read_registry(subkey: str) -> Optional[dict]: # pragma: no cover - Windows def _read_trusted_file(path: Path) -> tuple[bytes, os.stat_result]: """Read ``path`` once and return its bytes with the status of the file actually read (not of whatever the path names a moment later).""" - flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) - fd = os.open(path, flags) + from openadapt_flow.private_file import open_binary + + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + fd = open_binary(path, flags) try: info = os.fstat(fd) chunks = [] diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index 3b9fd69974..705398141b 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -1594,7 +1594,9 @@ def restore(root: Path | str) -> str: stanza = kh.device_stanza(bucket) # type: ignore[arg-type] except kh.KeyHierarchyError as exc: raise SealedSetError(f"Not restoring {base}: {exc}") from exc - record = dict(header["bucket_record"]) # type: ignore[arg-type] + raw_record = header["bucket_record"] + assert isinstance(raw_record, dict) + record = dict(raw_record) stanzas = [ s for s in record.get("stanzas", []) if s.get("fpr") != stanza["fpr"] ] From 7f4f5b5ba8af18d907065442b098d6186878f41a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 20:29:04 -0500 Subject: [PATCH 25/37] flow: durable resume and authority proofs work in encrypted runs - DurableAuthority digests report.json through the run's sealed set (the bytes the continuation fenced), so prove_executor_outcome and the terminal check no longer fail on every encrypted run. - A run cut off before its writer finalized (a crash or a killed leg) can be carried on: the next writer authenticates the header and adopts each file only if it authenticates under the set's key at its own path. - CheckpointStore resolves the run's key when it is used, so a store made before its run became an encrypted set uses the run's key. - was_compensated checks the marker's presence in either form without opening the set (the previous push treated an unfinalized run as compensated and refused its resume). - The attended reject path rewrites the report through the sealed set. - CI: the default-mode step also runs the durable and authority suites that pass in that mode. --- .github/workflows/packages.yml | 13 +++++ .../runtime/durable/attended.py | 6 ++- .../runtime/durable/authority.py | 22 +++++--- .../runtime/durable/checkpoint.py | 25 +++++++-- .../openadapt_flow/runtime/durable/resume.py | 14 ++--- packages/flow/openadapt_flow/sealed_set.py | 53 +++++++++++++++++++ .../flow/tests/test_at_rest_review_round3.py | 35 +++++++++++- 7 files changed, 148 insertions(+), 20 deletions(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 508e352df5..0106248542 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -891,11 +891,24 @@ jobs: if: matrix.shard == 1 env: OPENADAPT_TEST_DEFAULT_AT_REST: "1" + # The durable and authority files whose tests read files directly + # as plaintext are not listed yet (#2423 lists them). run: >- pytest -n logical --dist loadfile -q --basetemp=runs/ci-default-at-rest tests/test_rollback.py tests/test_rollback_qualify.py tests/test_checkpoint_key_derivations.py tests/test_key_hierarchy.py tests/test_at_rest_review_round3.py + tests/test_api_step_durable.py tests/test_attended_executor_fence_v13.py + tests/test_authoring_authority.py tests/test_continuation_receiver_clock.py + tests/test_default_ledger_authority.py tests/test_durable_authority_create.py + tests/test_durable_authority_edges_v13.py + tests/test_durable_authority_isolation_policy.py + tests/test_durable_first_local_delivery.py + tests/test_durable_first_local_program_delivery.py + tests/test_durable_pipelined_readback.py + tests/test_durable_resume_state_binding.py tests/test_durable_runtime.py + tests/test_module_durable_authority.py tests/test_realism_durable_resume.py + tests/test_tx_atomic_authority.py - name: Upload coverage data if: always() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/packages/flow/openadapt_flow/runtime/durable/attended.py b/packages/flow/openadapt_flow/runtime/durable/attended.py index 0117b24da3..88d29509c0 100644 --- a/packages/flow/openadapt_flow/runtime/durable/attended.py +++ b/packages/flow/openadapt_flow/runtime/durable/attended.py @@ -2319,7 +2319,7 @@ def _terminate_rejected_run( # must not acquire a dependency on it to end a run. try: report = RunReport.model_validate_json( - (run_dir / "report.json").read_text(encoding="utf-8") + _sealed.read_text(run_dir / "report.json") ) except (OSError, ValueError): return None @@ -2331,6 +2331,10 @@ def _terminate_rejected_run( # Atomic, because a torn report.json would lose the only machine-readable # record that this run is over. target = run_dir / "report.json" + if _sealed.is_sealed_path(target): + # An encrypted run (the default): its writer replaces it atomically. + _sealed.write_bytes(target, report.report_bytes()) + return outcome.value tmp = target.with_suffix(".json.rejecting") tmp.write_bytes(report.report_bytes()) os.replace(tmp, target) diff --git a/packages/flow/openadapt_flow/runtime/durable/authority.py b/packages/flow/openadapt_flow/runtime/durable/authority.py index 66d960c41d..d408e7bfc6 100644 --- a/packages/flow/openadapt_flow/runtime/durable/authority.py +++ b/packages/flow/openadapt_flow/runtime/durable/authority.py @@ -3104,9 +3104,7 @@ def prove_executor_outcome( if record.phase == "completed": report_path = self.run_dir / "report.json" try: - report_sha256 = ( - "sha256:" + hashlib.sha256(report_path.read_bytes()).hexdigest() - ) + report_sha256 = "sha256:" + _report_digest(report_path) except OSError: return None base_proof = ( @@ -3170,9 +3168,7 @@ def prove_completed_pause( return False report_path = self.run_dir / "report.json" try: - report_sha256 = ( - "sha256:" + hashlib.sha256(report_path.read_bytes()).hexdigest() - ) + report_sha256 = "sha256:" + _report_digest(report_path) except OSError: return False return bool( @@ -3423,3 +3419,17 @@ def _owned( "the external continuation authority is no longer owned by this attempt" ) return record + + +def _report_digest(report_path: Path) -> str: + """SHA-256 of the report's plaintext, the bytes the continuation fenced: + read through the run's sealed set when the run is encrypted (the + default), else from disk. A report that can't be read raises ``OSError``, + so no proof is given for it.""" + from openadapt_flow import sealed_set + + try: + data = sealed_set.read_bytes(report_path) + except ValueError as exc: # a SealedSetError: changed, shredded, no key + raise OSError(str(exc)) from exc + return hashlib.sha256(data).hexdigest() diff --git a/packages/flow/openadapt_flow/runtime/durable/checkpoint.py b/packages/flow/openadapt_flow/runtime/durable/checkpoint.py index 9c1bffcf84..b0663f61f3 100644 --- a/packages/flow/openadapt_flow/runtime/durable/checkpoint.py +++ b/packages/flow/openadapt_flow/runtime/durable/checkpoint.py @@ -495,11 +495,11 @@ def __init__(self, run_dir: Path | str, *, key: Optional[str] = None) -> None: # A non-empty passphrase turns on AEAD sealing for writes and # decryption for reads. Inside a version 3 run the passphrase is # always the run's own (derived from its data key, so a shred reaches - # these containers too), whatever the caller resolved. - from openadapt_flow import sealed_set as _sealed - - bound = _sealed.store_passphrase(self.run_dir) - self.key = bound or key + # these containers too), whatever the caller resolved. It is looked + # up when used, so a store made before its run directory became an + # encrypted set still uses the run's key (see :attr:`key`). + self._given_key = key + self._bound_key: Optional[str] = None # Reuse one public salt for containers this store seals; each # container records the salt and gets its own random nonce. self._salt: Optional[bytes] = None @@ -509,6 +509,21 @@ def __init__(self, run_dir: Path | str, *, key: Optional[str] = None) -> None: # changed key, derives again. Every read still authenticates. self._container_keys: Optional["ContainerKeys"] = None + @property + def key(self) -> Optional[str]: + """This store's passphrase: the run's own inside a version 3 run (a + run that can't be opened, such as a shredded one, refuses), else the + one given.""" + if self._bound_key is None: + from openadapt_flow import sealed_set as _sealed + + self._bound_key = _sealed.store_passphrase(self.run_dir) + return self._bound_key or self._given_key + + @key.setter + def key(self, value: Optional[str]) -> None: + self._given_key = value + def _keys(self) -> Optional["ContainerKeys"]: """This store's derived-key handle, or None without an explicit key.""" if not self.key: diff --git a/packages/flow/openadapt_flow/runtime/durable/resume.py b/packages/flow/openadapt_flow/runtime/durable/resume.py index 2b052c5820..9fe0138447 100644 --- a/packages/flow/openadapt_flow/runtime/durable/resume.py +++ b/packages/flow/openadapt_flow/runtime/durable/resume.py @@ -1090,13 +1090,13 @@ def was_compensated(run_dir: Path | str) -> bool: from openadapt_flow.rollback import COMPENSATED_MARKER marker = Path(run_dir) / COMPENSATED_MARKER - if marker.exists(): - return True - try: - # An encrypted run keeps the marker in its sealed set. - return sealed_set.exists(marker) - except (OSError, ValueError): # a SealedSetError is a ValueError - return True # can't tell: never resume a run that may be undone + # In either form: plaintext, or its ciphertext in an encrypted run (the + # default). Its presence is the fact; nothing needs opening, so a run cut + # off before it was finalized still answers. + return ( + marker.exists() + or marker.with_name(marker.name + sealed_set.SEALED_SUFFIX).exists() + ) def resume( diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index 3b9fd69974..edd2390ec5 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -1030,6 +1030,8 @@ def __init__( def _initialize(self, passphrase: Optional[str], *, resume: bool) -> None: kind = self.kind + if resume and is_sealed(self.root) and self._resume_unfinished(): + return if resume and is_sealed(self.root): opened = SealedSet.open(self.root, passphrase, expect=kind) self._header: dict[str, object] = dict(opened._header) @@ -1063,6 +1065,57 @@ def _initialize(self, passphrase: Optional[str], *, resume: bool) -> None: self._key = _derive(self._header, passphrase) self._write_header() + def _resume_unfinished(self) -> bool: + """Reopen a version 3 run whose writer stopped before finalizing it + (a leg cut off mid-run: a crash, or a process killed during an + unknown delivery), so a durable resume can carry it on. The header is + authenticated first. Each file the earlier leg sealed is adopted only + if it authenticates under this set's key at its own path; a + structural file the inventory names and another store's ciphertext + are adopted as on open. Anything else refuses. False for a finalized + set (the ordinary path) or any other kind.""" + header = read_header(self.root) + if ( + self.kind != "run" + or header.get("kind") != "run" + or header.get("version") != ENVELOPE_VERSION + or isinstance(header.get("index"), str) + ): + return False + key = _open_v3(header) + files: dict[str, Codec] = {} + hashes: dict[str, str] = {} + for physical in _disk_files(self.root): + raw = (self.root / physical).read_bytes() + if physical.endswith(SEALED_SUFFIX) and raw.startswith( + crypto.SET3_FILE_MAGIC + ): + rel = _check_rel(physical[: -len(SEALED_SUFFIX)]) + try: + key.open(raw, aad=_file_aad("run", rel)) + except (crypto.CryptoError, SealedSetError) as exc: + raise SealedSetError( + f"{self.root} was not finalized, and {physical} does not " + "authenticate under its key; refusing to carry it on" + ) from exc + files[rel] = "set" + else: + codec = _adoptable(self.root, "run", physical) + if codec is None: + raise SealedSetError( + f"{self.root} holds {physical} in plaintext, outside its " + "sealed writer" + ) + files[physical] = codec + rel = physical + hashes[rel] = _sha256(raw) + self._header = dict(header) + self._key = key + self._header_revision = _sha256((self.root / HEADER).read_bytes()) + self._codecs.update(files) + self._hashes.update(hashes) + return True + def _write_header(self) -> None: if isinstance(self._key, V3Key): self._key.stamp(self._header) diff --git a/packages/flow/tests/test_at_rest_review_round3.py b/packages/flow/tests/test_at_rest_review_round3.py index a56018fe36..b6be2fdc4b 100644 --- a/packages/flow/tests/test_at_rest_review_round3.py +++ b/packages/flow/tests/test_at_rest_review_round3.py @@ -240,6 +240,39 @@ def test_a_rollback_in_an_encrypted_run_keeps_its_marker_sealed( assert TYPED not in path.read_bytes(), path sealed_set.SealedSet.open(run).verify_all() assert was_compensated(run) is True - # A run whose state can't be read is never treated as resumable. + # A shredded run still answers (nothing needs opening). sealed_set.shred(run) assert was_compensated(run) is True + # A run that was never compensated is not. + other = _run(tmp_path / "other", {"report.json": b"{}"}) + assert was_compensated(other) is False + + +def test_a_run_cut_off_before_finalizing_resumes_into_the_same_set( + default_mode: Path, tmp_path: Path +) -> None: + """A durable leg killed mid-run leaves an unfinalized encrypted run. The + next leg carries it on: files the earlier leg sealed are adopted only + when they authenticate under the set's key at their own path.""" + run = tmp_path / "run" + first = sealed_set.SealedSetWriter(run, "run", sealed_set.passphrase_for("run")) + first.write("steps/a.png", TYPED) + # The process dies here: no finalize, no index. + with pytest.raises(sealed_set.SealedSetError, match="never finalized"): + sealed_set.SealedSet.open(run) + second = sealed_set.SealedSetWriter( + run, "run", sealed_set.passphrase_for("run"), resume=True + ) + second.write("report.json", b"{}") + second.finalize() + assert sealed_set.read_bytes(run / "steps" / "a.png") == TYPED + # A file that doesn't authenticate at its path is never carried on. + cut = tmp_path / "cut" + w = sealed_set.SealedSetWriter(cut, "run", sealed_set.passphrase_for("run")) + w.write("steps/a.png", TYPED) + w.write("steps/b.png", b"other") + (cut / "steps" / "b.png.enc").write_bytes( + (cut / "steps" / "a.png.enc").read_bytes() + ) + with pytest.raises(sealed_set.SealedSetError, match="does not authenticate"): + sealed_set.SealedSetWriter(cut, "run", None, resume=True) From 8e6bb2d6a9f979574bd83bdcce3e058d84bffd10 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 20:29:36 -0500 Subject: [PATCH 26/37] flow: an atomic report replace that keeps an encrypted run sealed (attended reject) --- .../flow/openadapt_flow/runtime/durable/attended.py | 12 ++---------- packages/flow/openadapt_flow/sealed_set.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/durable/attended.py b/packages/flow/openadapt_flow/runtime/durable/attended.py index 88d29509c0..ba8cb0cc1f 100644 --- a/packages/flow/openadapt_flow/runtime/durable/attended.py +++ b/packages/flow/openadapt_flow/runtime/durable/attended.py @@ -2328,16 +2328,8 @@ def _terminate_rejected_run( report.transaction_outcome = outcome.value report.transaction_billable = outcome.is_billable report.transaction_platform_fault = outcome.is_platform_fault - # Atomic, because a torn report.json would lose the only machine-readable - # record that this run is over. - target = run_dir / "report.json" - if _sealed.is_sealed_path(target): - # An encrypted run (the default): its writer replaces it atomically. - _sealed.write_bytes(target, report.report_bytes()) - return outcome.value - tmp = target.with_suffix(".json.rejecting") - tmp.write_bytes(report.report_bytes()) - os.replace(tmp, target) + # Atomic: a torn report.json would lose the only record this run is over. + _sealed.replace_bytes(run_dir / "report.json", report.report_bytes()) return outcome.value diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index edd2390ec5..de52eb0b8c 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -1544,6 +1544,18 @@ def write_bytes(path: Path | str, data: bytes, *, key: Optional[str] = None) -> resumed.finalize() +def replace_bytes(path: Path | str, data: bytes) -> None: + """Replace ``path`` atomically: through its sealed set when it lies in + one (whose writer replaces files atomically), else by a rename.""" + if is_sealed_path(path): + write_bytes(path, data) + return + target = Path(path) + tmp = target.with_name(f".{target.name}.{secrets.token_hex(4)}.tmp") + tmp.write_bytes(data) + os.replace(tmp, target) + + def write_text( path: Path | str, text: str, *, encoding: str = "utf-8", key: Optional[str] = None ) -> None: From d2cbdf21c9cc528b83f15305e7b134908aa3a03d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 23:31:03 -0500 Subject: [PATCH 27/37] flow: keep at_rest below sealed_set, fix mypy, keep capability row sources - new_artifact_key moves to sealed_set (at_rest must not import upward). - A type ignore for the unfinished-run resume key, as on the creation path. - The checkpoint lifecycle test checks the refusal when the key is used. - CAPABILITIES.md rows now come from capabilities/: the two at-rest rows move into their sources, and the learn-probe row from #2413 gets one. --- ...-per-request-bookkeeping-from-read-only.md | 1 + ...-phi-at-rest-every-bundle-file-that-can.md | 2 +- ...n-at-rest-under-a-configured-or-locally.md | 2 +- capabilities/CAPABILITIES.md.sha256 | 2 +- packages/flow/openadapt_flow/at_rest.py | 19 ------------------ .../flow/openadapt_flow/desktop_record.py | 4 ++-- packages/flow/openadapt_flow/recorder.py | 3 +-- packages/flow/openadapt_flow/sealed_set.py | 20 ++++++++++++++++++- packages/flow/tests/test_key_hierarchy.py | 2 +- 9 files changed, 27 insertions(+), 28 deletions(-) create mode 100644 capabilities/04-the-core-a-checked-entry-every-time/0395-learn-per-request-bookkeeping-from-read-only.md diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0395-learn-per-request-bookkeeping-from-read-only.md b/capabilities/04-the-core-a-checked-entry-every-time/0395-learn-per-request-bookkeeping-from-read-only.md new file mode 100644 index 0000000000..623d9f603d --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0395-learn-per-request-bookkeeping-from-read-only.md @@ -0,0 +1 @@ +| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user that every round (at least two) shows (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts whose every effect creates new records, or that read the target's versions on every other effect's surface, get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | diff --git a/capabilities/11-recording-privacy-and-proof/0090-encrypt-phi-at-rest-every-bundle-file-that-can.md b/capabilities/11-recording-privacy-and-proof/0090-encrypt-phi-at-rest-every-bundle-file-that-can.md index 5efa694808..88a537e147 100644 --- a/capabilities/11-recording-privacy-and-proof/0090-encrypt-phi-at-rest-every-bundle-file-that-can.md +++ b/capabilities/11-recording-privacy-and-proof/0090-encrypt-phi-at-rest-every-bundle-file-that-can.md @@ -1 +1 @@ -| Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | +| Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | diff --git a/capabilities/11-recording-privacy-and-proof/0100-encryption-at-rest-under-a-configured-or-locally.md b/capabilities/11-recording-privacy-and-proof/0100-encryption-at-rest-under-a-configured-or-locally.md index bcf303b2bb..8db691ddac 100644 --- a/capabilities/11-recording-privacy-and-proof/0100-encryption-at-rest-under-a-configured-or-locally.md +++ b/capabilities/11-recording-privacy-and-proof/0100-encryption-at-rest-under-a-configured-or-locally.md @@ -1 +1 @@ -| Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` authenticates the set's header, then destroys its tracked bucket-key copies, in the archive the set was written to (an archive counts only with its marker file), and the run's checkpoints, which are keyed from the run's own data key. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred, unmounted and moved archive, whole-set substitution, backlog race and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | diff --git a/capabilities/CAPABILITIES.md.sha256 b/capabilities/CAPABILITIES.md.sha256 index a121e3ae63..3cb555d374 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -e43b02968b96995aa15093365c5405a2ef95166f04506c3137b21ba63f3a6afb +b2786fb1a9fca82ba1ca70d49e8bbe07a07ab91501fca8412029f2bbc4c2af62 diff --git a/packages/flow/openadapt_flow/at_rest.py b/packages/flow/openadapt_flow/at_rest.py index 215ee77a9b..14da1c2083 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -812,25 +812,6 @@ def plaintext_by_caller(artifact: str, path: Path | str) -> None: ) -def new_artifact_key( - explicit: Optional[str] | object, artifact: str, path: Path | str -) -> Optional[str]: - """The key for a new recording a library entry point writes: the - caller's key; under :data:`POLICY`, the policy's (None, plaintext, only - under the recorded opt-out); an explicit ``None`` is plaintext through - :func:`plaintext_by_caller` (refused in strict mode, else recorded).""" - if explicit is POLICY: - if not seal_new(artifact, path): - return None - from openadapt_flow import sealed_set - - return sealed_set.recording_key() - if not explicit: - plaintext_by_caller(artifact, path) - return None - return str(explicit) - - def seals_by_default() -> bool: """Whether new artifacts are sealed now, without recording anything: strict mode, or the default mode without the opt-out.""" diff --git a/packages/flow/openadapt_flow/desktop_record.py b/packages/flow/openadapt_flow/desktop_record.py index 7dd0450daa..5c409c4d41 100644 --- a/packages/flow/openadapt_flow/desktop_record.py +++ b/packages/flow/openadapt_flow/desktop_record.py @@ -449,11 +449,11 @@ def _policy_key(out_dir: Path | str, explicit: Optional[str] | object) -> Option Strict mode refuses any desktop capture (its raw session is plaintext while it records), whether or not a key was passed. An explicit ``None`` is a plaintext recording, recorded in the ledger.""" - from openadapt_flow import at_rest + from openadapt_flow import at_rest, sealed_set if at_rest.strict(): at_rest.unsealed_write("a desktop raw capture session", str(out_dir)) - return at_rest.new_artifact_key(explicit, "a desktop recording", out_dir) + return sealed_set.new_artifact_key(explicit, "a desktop recording", out_dir) def _seal_recording(plain: Path, dest: Path, key: str) -> None: diff --git a/packages/flow/openadapt_flow/recorder.py b/packages/flow/openadapt_flow/recorder.py index 1a3bf1c4d2..2f4f19f97e 100644 --- a/packages/flow/openadapt_flow/recorder.py +++ b/packages/flow/openadapt_flow/recorder.py @@ -61,7 +61,6 @@ from PIL import Image, ImageDraw -from openadapt_flow import at_rest as _at_rest from openadapt_flow import sealed_set as _sealed from openadapt_flow.at_rest import POLICY from openadapt_flow.backend import ( @@ -277,7 +276,7 @@ def __init__( self._finalize_on_finish = finalize_on_finish # Encrypted by default (the at-rest policy decides); an explicit # ``None`` is plaintext that strict mode refuses and the ledger records. - encryption_key = _at_rest.new_artifact_key( + encryption_key = _sealed.new_artifact_key( encryption_key, "a recording", self._dir ) if encryption_key: diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index ec1a8aeac5..dfc59a8aab 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -984,6 +984,24 @@ def _new_v3( return header, V3Key(dek, set_id, bucket) +def new_artifact_key( + explicit: Optional[str] | object, artifact: str, path: Path | str +) -> Optional[str]: + """The key for a new recording a library entry point writes: the + caller's key; under :data:`at_rest.POLICY`, the policy's (None, plaintext, + only under the recorded opt-out); an explicit ``None`` is plaintext through + :func:`at_rest.plaintext_by_caller` (refused in strict mode, else + recorded).""" + from openadapt_flow import at_rest + + if explicit is at_rest.POLICY: + return recording_key() if at_rest.seal_new(artifact, path) else None + if not explicit: + at_rest.plaintext_by_caller(artifact, path) + return None + return str(explicit) + + def preflight_new(kind: str, passphrase: Optional[str]) -> None: """Refuse, before a capture starts, a new set :func:`_new_v3` would refuse at sealing time (organization recipients, archive and backlog, @@ -1110,7 +1128,7 @@ def _resume_unfinished(self) -> bool: rel = physical hashes[rel] = _sha256(raw) self._header = dict(header) - self._key = key + self._key = key # type: ignore[assignment] self._header_revision = _sha256((self.root / HEADER).read_bytes()) self._codecs.update(files) self._hashes.update(hashes) diff --git a/packages/flow/tests/test_key_hierarchy.py b/packages/flow/tests/test_key_hierarchy.py index b9304aea1e..1211ce5403 100644 --- a/packages/flow/tests/test_key_hierarchy.py +++ b/packages/flow/tests/test_key_hierarchy.py @@ -929,7 +929,7 @@ class Bindings(BaseModel): # Organization mode: the backup's header names a bucket whose every # tracked key copy is gone, so its checkpoints are gone too. with pytest.raises(sealed_set.SealedSetError): - CheckpointStore(backup, key=local) + CheckpointStore(backup, key=local).key # refused when used def test_a_checkpoint_store_without_a_key_encrypts_by_default(home) -> None: From 358e28755cb3e23990540de53b58237127f0bf40 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 23:55:48 -0500 Subject: [PATCH 28/37] ci: a temporary informational job running the whole flow suite with encryption at rest on (#2423) --- .github/workflows/packages.yml | 173 ++++++++++++++++++++++++++++++++ tests/test_pinned_apt_action.py | 3 +- 2 files changed, 175 insertions(+), 1 deletion(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 0106248542..924b544e2f 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -672,6 +672,179 @@ jobs: openadapt_flow/compiler/induction.py \ openadapt_flow/compiler/loop_authoring.py + flow-default-at-rest: + # TEMPORARY (#2423): the whole flow suite under the product default, + # encryption at rest on (no plaintext opt-out). Informational while the + # results are triaged; it gates nothing. + name: flow default at rest (shard ${{ matrix.shard }}/${{ matrix.of }}, informational) + needs: scope + # PR and post-merge tiers. The merge queue skips it: a pull request can + # enter the queue only after packages-gate passed with these shards green + # on its merge with main, and flow-critical re-checks the golden path on + # the group. + if: github.event_name == 'pull_request' && github.event.pull_request.draft != true && needs.scope.outputs.flow == 'true' + runs-on: ubuntu-latest + # The nightly tier (a schedule or a dispatch) also measures coverage, + # which slows the suite by about a third; it gets 60 minutes. + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + # Each shard runs one pytest-xdist worker per vCPU (four on + # ubuntu-latest) and pays about 35 s of setup. Files are packed by + # measured time (scripts/ci/flow_shards.py), so the shards finish + # together. A pull request's fast lane takes four shards: with three, + # the identity, wire and verifier tests it must keep held each shard + # near 12 minutes of tests (run 44684203094). The full suite on main + # and nightly takes two. + include: [{"shard":1,"of":4},{"shard":2,"of":4},{"shard":3,"of":4},{"shard":4,"of":4}] + defaults: + run: + working-directory: packages/flow + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + # uv installs the locked requirements into the setup-python interpreter, + # in seconds instead of minutes, from a cache keyed on the locks. + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + enable-cache: true + cache-dependency-glob: | + packages/flow/uv.lock + packages/capture/uv.lock + cache-suffix: flow-default-at-rest + - name: Install from the locks + # Flow's lock, then Capture's: the in-tree Capture can need newer + # dependencies than the published one Flow's lock names. + run: >- + python ../../scripts/ci/locked_install.py --lock 'packages/flow[dev,capture,agent]' --lock packages/capture + --editable packages/types --editable packages/capture --editable packages/flow --editable packages/agent --editable . + - name: Install tesseract for the flight scrubber's OCR tests + # pytesseract comes from Flow's dev extra (locked); this is its binary. + uses: OpenAdaptAI/OpenAdapt/.github/actions/apt-install@94f724c7dc0b0995a7108b7b99bbb53f0749cb68 + with: + packages: tesseract-ocr tesseract-ocr-eng + - name: Install Harness² for the integration tests + # Not on PyPI. Pinned to the commit benchmark.harness.harness2 + # is written against; it has no runtime dependencies. + run: >- + uv pip install --system --no-deps + 'harness2 @ git+https://github.com/google-research/harness2@1cfe254e8d25b15f37048c3730134686abe60335' + - name: Verify the in-tree openadapt-capture imports headless + run: | + python - <<'PY' + import pathlib, openadapt_capture + here = pathlib.Path(openadapt_capture.__file__).resolve().as_posix() + assert "packages/capture/openadapt_capture" in here, here + print("openadapt_capture from", here) + PY + - name: Verify the installed Agent shim, launcher and Flow implementation + run: | + python - <<'PY' + import importlib.metadata + import importlib.util + import json + import pathlib + + root = pathlib.Path.cwd().resolve().parents[1] + shim = importlib.util.find_spec("openadapt_agent") + expected = root / "packages/agent/src/openadapt_agent/__init__.py" + assert ( + shim and shim.origin and pathlib.Path(shim.origin).resolve() == expected + ), shim + installed = importlib.metadata.distribution("openadapt-agent") + direct = json.loads(installed.read_text("direct_url.json") or "{}") + assert direct.get("url") == (root / "packages/agent").as_uri(), direct + assert direct.get("dir_info", {}).get("editable") is True, direct + + compatibility = importlib.import_module("openadapt_agent") + engine = importlib.import_module("openadapt_flow.agent") + assert compatibility is engine + implementation = pathlib.Path(engine.__file__).resolve() + expected_implementation = root / "packages/flow/openadapt_flow/agent/__init__.py" + assert implementation == expected_implementation, implementation + print("openadapt-agent shim from", expected) + print("openadapt_flow.agent from", implementation) + + launcher_spec = importlib.util.find_spec("openadapt") + expected_launcher = root / "openadapt/__init__.py" + assert ( + launcher_spec + and launcher_spec.origin + and pathlib.Path(launcher_spec.origin).resolve() == expected_launcher + ), launcher_spec + launcher_distribution = importlib.metadata.distribution("openadapt") + launcher_direct = json.loads( + launcher_distribution.read_text("direct_url.json") or "{}" + ) + assert launcher_direct.get("url") == root.as_uri(), launcher_direct + assert ( + launcher_direct.get("dir_info", {}).get("editable") is True + ), launcher_direct + launcher = importlib.import_module("openadapt") + assert pathlib.Path(launcher.__file__).resolve() == expected_launcher + print("openadapt launcher from", expected_launcher) + PY + - name: Resolve Playwright version + id: pw + run: | + python -c "import importlib.metadata as m; print('version=' + m.version('playwright'))" >> "$GITHUB_OUTPUT" + - name: Cache Playwright browsers + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ steps.pw.outputs.version }} + - name: Install and launch Playwright browser + timeout-minutes: 12 + run: >- + python scripts/install_playwright_browser.py + --attempts 2 --attempt-timeout-seconds 270 + - name: Select this shard's test files + env: + SHARD: ${{ matrix.shard }} + SHARDS: ${{ matrix.of }} + EVENT_NAME: ${{ github.event_name }} + run: | + set -euo pipefail + # Everything outside tests/e2e, minus the installer self-test and the + # long qualification campaign. The nightly run (a schedule, or a + # dispatch) also takes all of tests/e2e; pull requests and main run + # the end-to-end tests flow-critical names. flow_shards.py packs the + # files by their measured time (scripts/ci/flow_test_durations.json) + # and lists each shard longest first; every file lands in exactly + # one shard. + e2e=(-not -path 'tests/e2e/*') + case "$EVENT_NAME" in schedule|workflow_dispatch) e2e=() ;; esac + find tests -name 'test_*.py' "${e2e[@]}" \ + -not -path 'tests/test_install_playwright_browser.py' \ + -not -path 'tests/test_qualification_gate_campaign.py' \ + -not -path 'tests/golden_runs/test_golden_runs.py' \ + | python ../../scripts/ci/flow_shards.py --shard "$SHARD" --of "$SHARDS" > "$RUNNER_TEMP/shard.txt" + wc -l < "$RUNNER_TEMP/shard.txt" + - name: Test under the default (encrypted) mode + continue-on-error: true + env: + OPENADAPT_TEST_DEFAULT_AT_REST: "1" + OPENADAPT_TEST_LANE: fast + run: | + set -uo pipefail + mkdir -p runs + mapfile -t files < "$RUNNER_TEMP/shard.txt" + pytest -n logical --dist loadfile -q -rfE --timeout 300 \ + --basetemp=runs/ci-default \ + --junitxml=runs/flow-default-at-rest-${{ matrix.shard }}.xml "${files[@]}" + - name: Upload the default-mode results + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: flow-default-at-rest-${{ matrix.shard }} + path: packages/flow/runs/flow-default-at-rest-${{ matrix.shard }}.xml + if-no-files-found: warn + flow-unit: name: flow core unit (shard ${{ matrix.shard }}/${{ matrix.of }}) needs: scope diff --git a/tests/test_pinned_apt_action.py b/tests/test_pinned_apt_action.py index fd2f0e8e39..c857d7ce87 100644 --- a/tests/test_pinned_apt_action.py +++ b/tests/test_pinned_apt_action.py @@ -45,7 +45,8 @@ def test_all_production_callers_pin_the_reviewed_action(): "packages.yml", "quickstart-lifecycle.yml", } - assert len(production) == 12 # + the flow unit shards' tesseract + # + the flow unit shards' tesseract, and the default-at-rest shards' (#2423) + assert len(production) == 13 assert len(local_selftests) == 5 # Exercise future helper edits, not the pin. From f51aa3b53d1fcc06d3107664b8cbbe99fb6130a0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 00:00:11 -0500 Subject: [PATCH 29/37] test(flow): tamper durable state through the stores' own writers, so the intended refusal is checked in either mode --- .../tests/test_attended_source_identity_v13.py | 6 +++++- packages/flow/tests/test_durable_program.py | 4 +++- .../tests/test_durable_program_history_v13.py | 18 ++++++++++++------ 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/packages/flow/tests/test_attended_source_identity_v13.py b/packages/flow/tests/test_attended_source_identity_v13.py index 3af07149c7..a50ce6e291 100644 --- a/packages/flow/tests/test_attended_source_identity_v13.py +++ b/packages/flow/tests/test_attended_source_identity_v13.py @@ -337,7 +337,11 @@ def test_pre_v3_capability_only_supports_non_identity_required_resume( } ) legacy.signature = action_store._sign(legacy, create_key=False) - action_store.capability_path.write_text(legacy.model_dump_json(indent=2)) + # Through the store's own writer: plaintext beside an encrypted capability + # would be refused before the identity check this test is about. + action_store._state_write( + action_store.capability_path, legacy.model_dump_json(indent=2).encode() + ) manifest = store.read_manifest() assert manifest is not None checkpoint = RunCheckpoint( diff --git a/packages/flow/tests/test_durable_program.py b/packages/flow/tests/test_durable_program.py index 964f406c22..96e7875f39 100644 --- a/packages/flow/tests/test_durable_program.py +++ b/packages/flow/tests/test_durable_program.py @@ -1423,7 +1423,9 @@ def test_program_resume_refuses_a_noncontiguous_checkpoint_history(tmp_path): store = CheckpointStore(run_dir) checkpoint = store.program_checkpoints()[0] path = run_dir / "checkpoints" / "pstate_0001.json" - path.write_text(checkpoint.model_copy(update={"seq": 2}).model_dump_json(indent=2)) + # Through the store's own writer, so the tampered checkpoint replaces the + # real one in either form (sealed in an encrypted run, the default). + store._write_model(path, checkpoint.model_copy(update={"seq": 2})) backend = FakeBackend() calls_before = verifier.capture_calls diff --git a/packages/flow/tests/test_durable_program_history_v13.py b/packages/flow/tests/test_durable_program_history_v13.py index 40f54bc26c..e21967a627 100644 --- a/packages/flow/tests/test_durable_program_history_v13.py +++ b/packages/flow/tests/test_durable_program_history_v13.py @@ -8,8 +8,6 @@ from __future__ import annotations -import json - import pytest from openadapt_flow.ir import ActionKind, State, StateKind, Step, Transition @@ -18,6 +16,7 @@ BoundAttendedExecutor, execute_attended_action, ) +from openadapt_flow.runtime.durable.checkpoint import PendingEscalation from openadapt_flow.runtime.durable.program_checkpoint import history_hash from openadapt_flow.runtime.replayer import Replayer from tests.test_attended_actions import ( @@ -46,8 +45,10 @@ def _assert_boundary( def _rewrite_checkpoint(run_dir, checkpoint) -> None: + # Through the store's own writer: in an encrypted run (the default) a + # plaintext file beside the sealed checkpoint would be refused first. path = run_dir / "checkpoints" / f"pstate_{checkpoint.seq:04d}.json" - path.write_text(checkpoint.model_dump_json(indent=2)) + CheckpointStore(run_dir)._write_model(path, checkpoint) def _verified_checkpoint_path(checkpoints) -> list[str]: @@ -391,7 +392,10 @@ def test_reordered_checkpoint_history_refuses_before_input(tmp_path): def test_deleted_program_checkpoint_refuses_before_input(tmp_path): _report, run_dir, bundle, verifier = _run_branch_loop_to_pause(tmp_path) path = run_dir / "checkpoints" / "pstate_0001.json" - path.unlink() + forms = [path, path.with_name(path.name + ".enc")] # plaintext or sealed + assert any(form.exists() for form in forms) + for form in forms: + form.unlink(missing_ok=True) backend = FakeBackend() with pytest.raises(StateDiverged): @@ -406,10 +410,12 @@ def test_deleted_program_checkpoint_refuses_before_input(tmp_path): def test_changed_pending_history_refuses_before_input(tmp_path): _report, run_dir, bundle, verifier = _run_branch_loop_to_pause(tmp_path) pending_path = run_dir / "pending_escalation.json" - raw = json.loads(pending_path.read_text()) + store = CheckpointStore(run_dir) + raw = store._read_json(pending_path) + assert raw is not None raw["program_history"] = list(reversed(raw["program_history"])) raw["program_history_hash"] = history_hash(raw["program_history"]) - pending_path.write_text(json.dumps(raw, indent=2)) + store._write_model(pending_path, PendingEscalation.model_validate(raw)) backend = FakeBackend() with pytest.raises(StateDiverged): From 5480849ec7a4795b3b4d928eb1c16ebb7c14d025 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 00:24:28 -0500 Subject: [PATCH 30/37] flow: authoring, runtime validation and agent teach read and write encrypted recordings and runs - AuthoringSession reads and stamps the recording's events.jsonl and meta.json, and writes admit.json, through the sealed set (the recorder seals by default). - Runtime validation reads the run report in memory. - Agent-teach evidence reads the sealed report and frames; writing that plaintext evidence folder is logged by default and refused in strict mode. - Tests: under OPENADAPT_TEST_DEFAULT_AT_REST=1, one at-rest home per session (per worker), outside the tests' own directories. --- packages/flow/openadapt_flow/authoring.py | 24 ++++++++++++------- .../flow/openadapt_flow/repair/agent_teach.py | 17 ++++++++++--- .../flow/openadapt_flow/runtime_validation.py | 5 +++- packages/flow/tests/conftest.py | 15 +++++++++++- 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/packages/flow/openadapt_flow/authoring.py b/packages/flow/openadapt_flow/authoring.py index 751d3501a2..6f3d7375d2 100644 --- a/packages/flow/openadapt_flow/authoring.py +++ b/packages/flow/openadapt_flow/authoring.py @@ -343,12 +343,15 @@ def _pixels_from_mapping(raw: Mapping[str, Any]) -> _NodePixels: def _load_events(recording_dir: Path) -> list[dict[str, Any]]: + from openadapt_flow import sealed_set + + # The recording is encrypted by default: read it through its sealed set. path = recording_dir / "events.jsonl" - if not path.is_file(): + if not sealed_set.is_file(path): return [] return [ json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + for line in sealed_set.read_text(path).splitlines() if line.strip() ] @@ -1250,9 +1253,10 @@ def admit(self, confirm: object = None) -> AdmitResult: record["digest"] = self._draft_digest dest = self._draft_bundle if self._draft_bundle is not None else self._out_dir dest.mkdir(parents=True, exist_ok=True) - (dest / "admit.json").write_text( - json.dumps(record, indent=2) + "\n", encoding="utf-8" - ) + from openadapt_flow import sealed_set + + # Inside an encrypted draft bundle (the default) it is sealed too. + sealed_set.write_text(dest / "admit.json", json.dumps(record, indent=2) + "\n") public: AdmitResult = {"status": "accepted", "workflow_id": workflow_id} if self._draft_digest: public["digest"] = self._draft_digest @@ -1394,6 +1398,8 @@ def _stamp_provenance(self, rec_dir: Path) -> None: the ``surface`` the demonstration ran on, and how the input reached it. """ + from openadapt_flow import sealed_set + events_path = rec_dir / "events.jsonl" events = _load_events(rec_dir) for event in events: @@ -1402,8 +1408,8 @@ def _stamp_provenance(self, rec_dir: Path) -> None: self._actors.get(index, "agent") if isinstance(index, int) else "agent" ) if events: - events_path.write_text( - "".join(json.dumps(event) + "\n" for event in events), encoding="utf-8" + sealed_set.write_text( + events_path, "".join(json.dumps(event) + "\n" for event in events) ) actors = {event["actor"] for event in events} if actors == {"person"}: @@ -1413,7 +1419,7 @@ def _stamp_provenance(self, rec_dir: Path) -> None: else: demonstrated_by = "agent" meta_path = rec_dir / "meta.json" - meta = json.loads(meta_path.read_text(encoding="utf-8")) + meta = json.loads(sealed_set.read_text(meta_path)) meta["demonstrated_by"] = demonstrated_by meta["surface"] = self._kind meta["authoring"] = { @@ -1426,7 +1432,7 @@ def _stamp_provenance(self, rec_dir: Path) -> None: # A remote session's frames are the client window's own pixels, # the same space Capture's window-scoped recordings declare. meta["coordinate_space"] = "window_pixels" - meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8") + sealed_set.write_text(meta_path, json.dumps(meta, indent=2)) def _refuse_missing_secret_type(self, recording_dir: Path) -> None: events = _load_events(recording_dir) diff --git a/packages/flow/openadapt_flow/repair/agent_teach.py b/packages/flow/openadapt_flow/repair/agent_teach.py index 743914220e..904aab288b 100644 --- a/packages/flow/openadapt_flow/repair/agent_teach.py +++ b/packages/flow/openadapt_flow/repair/agent_teach.py @@ -77,8 +77,10 @@ def _evidence_frame(recording: Path, template: str) -> Path: raise AgentTeachRefused( "a taught step has no recorded template, so there is no frame to test it on" ) + from openadapt_flow import sealed_set + frame = recording / "frames" / f"{int(match.group(1)):04d}_before.png" - if not frame.is_file(): + if not sealed_set.is_file(frame): raise AgentTeachRefused(f"the recording has no frame for {template}") return frame @@ -102,17 +104,26 @@ def _finish_candidate( raise AgentTeachRefused( "the demonstration added no step with an on-screen target" ) + from openadapt_flow import at_rest, sealed_set + + if sealed_set.is_sealed_path(run_dir) or sealed_set.is_sealed_path(recording): + # The candidate's evidence (the run report and the taught frames) is + # a plaintext folder the repair review reads; it can't be encrypted + # yet. Logged by default, refused in strict mode, before it's written. + at_rest.unsealed_write("agent-teach repair evidence", evidence) if evidence.exists(): shutil.rmtree(evidence) (evidence / "heals").mkdir(parents=True) - shutil.copy2(run_dir / "report.json", evidence / "report.json") + (evidence / "report.json").write_bytes( + sealed_set.read_bytes(run_dir / "report.json") + ) taught: list[TaughtStep] = [] for step_id, step in sorted(new_steps.items()): assert step.anchor is not None # filtered above frame = _evidence_frame(recording, step.anchor.template) target = evidence / "heals" / step_id / "screen.png" target.parent.mkdir(parents=True) - shutil.copy2(frame, target) + target.write_bytes(sealed_set.read_bytes(frame)) taught.append( TaughtStep(step_id=step_id, frame_sha256=sha256_hex(target.read_bytes())) ) diff --git a/packages/flow/openadapt_flow/runtime_validation.py b/packages/flow/openadapt_flow/runtime_validation.py index ba4cb0582d..8f37afc029 100644 --- a/packages/flow/openadapt_flow/runtime_validation.py +++ b/packages/flow/openadapt_flow/runtime_validation.py @@ -565,7 +565,10 @@ def _replay_attestation( report_path = run_dir / "report.json" try: - report_bytes = report_path.read_bytes() + from openadapt_flow import sealed_set + + # The run directory is encrypted by default: read it in memory. + report_bytes = sealed_set.read_bytes(report_path) report = RunReport.model_validate_json(report_bytes) except (OSError, ValueError) as exc: raise RuntimeValidationError(f"Cannot read a valid run report: {exc}") from exc diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index 5143735ffe..772b339ac2 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -32,6 +32,8 @@ def pytest_collection_modifyitems( _SESSION_ENV: dict[str, str | None] = {} +#: The at-rest home of an OPENADAPT_TEST_DEFAULT_AT_REST=1 session. +_SESSION_AT_REST_HOME: str | None = None def _configure_at_rest() -> None: @@ -40,7 +42,13 @@ def _configure_at_rest() -> None: output under a key a later per-test home can't open, and nothing may reach the person's OS keychain. The per-test isolation sets these again.""" + global _SESSION_AT_REST_HOME wanted = {"OPENADAPT_FLOW_KEY_STORE": "file"} + if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") == "1": + import tempfile + + _SESSION_AT_REST_HOME = tempfile.mkdtemp(prefix="openadapt-at-rest-home-") + wanted["OPENADAPT_FLOW_AT_REST_HOME"] = _SESSION_AT_REST_HOME if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") != "1": wanted["OPENADAPT_FLOW_PLAINTEXT_AT_REST"] = os.environ.get( "OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data" @@ -105,7 +113,12 @@ def _isolation_env(root: Path) -> dict[str, str | None]: "OPENADAPT_FLOW_PLAINTEXT_AT_REST": None if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") == "1" else "test suite: synthetic data", - "OPENADAPT_FLOW_AT_REST_HOME": str(root / ".at-rest-home"), + # Under the default mode, one device key per test session (per xdist + # worker), outside every test's own directories: a module fixture + # sealed in one test must open in the next, and the key files must + # never land inside a recording or run directory a test seals. + "OPENADAPT_FLOW_AT_REST_HOME": _SESSION_AT_REST_HOME + or str(root / ".at-rest-home"), "OPENADAPT_FLOW_AT_REST": None, # The device key goes to a file in the isolated home, never to the # OS keychain (no dialog, no write to the person's login keychain). From 694bc0fa9e64080e8c02e03adfc00d183f057abb Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 00:47:59 -0500 Subject: [PATCH 31/37] flow: distill and agent-teach candidates stay encrypted; default-mode test isolation - distill_recording reads an encrypted recording in memory and writes the distilled recording encrypted (authoring compile distills by default). - The agent-teach repair candidate is written through the sealed set. - Tests: the default-mode skip list (tests/default_at_rest_skips.txt), and the sealed lock directory outside the tests' own directories. --- .../flow/openadapt_flow/compiler/distill.py | 87 ++++++++++++++----- .../flow/openadapt_flow/repair/agent_teach.py | 6 +- packages/flow/tests/conftest.py | 42 ++++++++- 3 files changed, 109 insertions(+), 26 deletions(-) diff --git a/packages/flow/openadapt_flow/compiler/distill.py b/packages/flow/openadapt_flow/compiler/distill.py index 0d00b9c8d6..563a9915c4 100644 --- a/packages/flow/openadapt_flow/compiler/distill.py +++ b/packages/flow/openadapt_flow/compiler/distill.py @@ -73,7 +73,6 @@ import io import json import re -import shutil from dataclasses import asdict, dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any, Optional @@ -131,9 +130,12 @@ def _pixels(path: Path) -> Optional[np.ndarray]: import numpy as np from PIL import Image - if not path.exists(): + from openadapt_flow import sealed_set + + # A recording is encrypted by default: frames read in memory. + if not sealed_set.is_file(path): return None - with Image.open(io.BytesIO(path.read_bytes())) as image: + with Image.open(io.BytesIO(sealed_set.read_bytes(path))) as image: return np.asarray(image.convert("RGB")) @@ -391,7 +393,9 @@ def _corrections(events: list[dict[str, Any]], dropped: dict[int, str]) -> None: def _load(recording_dir: Path) -> list[dict[str, Any]]: - lines = (recording_dir / "events.jsonl").read_text(encoding="utf-8").splitlines() + from openadapt_flow import sealed_set + + lines = sealed_set.read_text(recording_dir / "events.jsonl").splitlines() return [json.loads(line) for line in lines if line.strip()] @@ -513,8 +517,37 @@ def frame(i: int, side: str) -> Optional[np.ndarray]: if frames_unchanged(frame(event["i"], "before"), frame(event["i"], "after")): dropped[pos] = "no_visible_effect" - dst.mkdir(parents=True) - (dst / "frames").mkdir() + from contextlib import nullcontext + + from openadapt_flow import sealed_set + + # An encrypted recording (the default) distills into an encrypted one; + # nothing it holds is written in plaintext. + sealed_src = sealed_set.is_sealed_path(src) + if sealed_src: + target: Any = sealed_set.writing(dst, "recording", sealed_set.recording_key()) + else: + dst.mkdir(parents=True) + (dst / "frames").mkdir() + target = nullcontext() + with target: + kept_lines = _write_distilled(src, dst, events, dropped, frames) + report = _distill_report(src, dst, events, dropped, kept_lines) + sealed_set.write_text( + dst / "distill.json", json.dumps(report.to_dict(), indent=2) + "\n" + ) + return report + + +def _write_distilled( + src: Path, + dst: Path, + events: list[dict[str, Any]], + dropped: dict[int, str], + frames: Path, +) -> list[str]: + from openadapt_flow import sealed_set + kept_lines = [] for new_i, (pos, event) in enumerate( (p, e) for p, e in enumerate(events) if p not in dropped @@ -522,23 +555,37 @@ def frame(i: int, side: str) -> Optional[np.ndarray]: old_i = event["i"] for side in ("before", "after"): source_frame = frames / f"{old_i:04d}_{side}.png" - if source_frame.exists(): - shutil.copyfile( - source_frame, dst / "frames" / f"{new_i:04d}_{side}.png" + if sealed_set.is_file(source_frame): + sealed_set.write_bytes( + dst / "frames" / f"{new_i:04d}_{side}.png", + sealed_set.read_bytes(source_frame), ) kept_lines.append(json.dumps({**event, "i": new_i, "distilled_from_i": old_i})) - (dst / "events.jsonl").write_text( - "".join(line + "\n" for line in kept_lines), encoding="utf-8" + sealed_set.write_text( + dst / "events.jsonl", "".join(line + "\n" for line in kept_lines) ) meta_path = src / "meta.json" - if meta_path.exists(): - meta = json.loads(meta_path.read_text(encoding="utf-8")) + if sealed_set.is_file(meta_path): + meta = json.loads(sealed_set.read_text(meta_path)) meta["distilled_from"] = meta.get("id") - (dst / "meta.json").write_text(json.dumps(meta, indent=2), encoding="utf-8") - for name in sorted(p.name for p in src.iterdir() if p.is_file()): - if name not in ("events.jsonl", "meta.json") and not (dst / name).exists(): - shutil.copyfile(src / name, dst / name) - report = DistillReport( + sealed_set.write_text(dst / "meta.json", json.dumps(meta, indent=2)) + top = sorted(p.name for p in sealed_set.list_files(src) if p.parent == src) + for name in top: + if name not in ("events.jsonl", "meta.json") and not sealed_set.is_file( + dst / name + ): + sealed_set.write_bytes(dst / name, sealed_set.read_bytes(src / name)) + return kept_lines + + +def _distill_report( + src: Path, + dst: Path, + events: list[dict[str, Any]], + dropped: dict[int, str], + kept_lines: list[str], +) -> "DistillReport": + return DistillReport( source=str(src), output=str(dst), steps_in=len(events), @@ -550,7 +597,3 @@ def frame(i: int, side: str) -> Optional[np.ndarray]: for pos, rule in sorted(dropped.items()) ], ) - (dst / "distill.json").write_text( - json.dumps(report.to_dict(), indent=2) + "\n", encoding="utf-8" - ) - return report diff --git a/packages/flow/openadapt_flow/repair/agent_teach.py b/packages/flow/openadapt_flow/repair/agent_teach.py index 904aab288b..d81cf58031 100644 --- a/packages/flow/openadapt_flow/repair/agent_teach.py +++ b/packages/flow/openadapt_flow/repair/agent_teach.py @@ -133,8 +133,10 @@ def _finish_candidate( candidate.taught_steps = taught candidate.provenance = provenance path = detached_candidate_path(out) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(candidate.model_dump_json(indent=2), encoding="utf-8") + if not sealed_set.is_sealed_path(out): + path.parent.mkdir(parents=True, exist_ok=True) + # Encrypted when the proposed bundle is (it names anchor text). + sealed_set.write_text(path, candidate.model_dump_json(indent=2)) return candidate diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index 772b339ac2..672289de09 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -26,9 +26,41 @@ def pytest_collection_modifyitems( config: pytest.Config, items: list[pytest.Item] ) -> None: - """In the fast and main lanes, leave out tests in tests/nightly_only.txt.""" + """In the fast and main lanes, leave out tests in tests/nightly_only.txt. + Under OPENADAPT_TEST_DEFAULT_AT_REST=1, skip the tests listed in + tests/default_at_rest_skips.txt, each with its stated reason.""" lanes.deselect(config, items) + if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") == "1": + _skip_default_at_rest(items) + + +_DEFAULT_AT_REST_SKIPS = Path(__file__).parent / "default_at_rest_skips.txt" + + +def _skip_default_at_rest(items: list[pytest.Item]) -> None: + """Tests that read or plant a run, recording or bundle file directly as + plaintext. Under the default (everything encrypted) the product refuses + that file, correctly, so the test can't observe what it checks. Each line + is `` | ``; a prefix may name a whole file.""" + if not _DEFAULT_AT_REST_SKIPS.is_file(): + return + rules: list[tuple[str, str]] = [] + for line in _DEFAULT_AT_REST_SKIPS.read_text(encoding="utf-8").splitlines(): + if not line.strip() or line.startswith("#"): + continue + prefix, _, reason = line.partition(" | ") + rules.append((prefix.strip(), reason.strip())) + for item in items: + nodeid = item.nodeid.removeprefix("packages/flow/") + for prefix, reason in rules: + if ( + nodeid == prefix + or nodeid.startswith(prefix + "::") + or (prefix.endswith(".py") and nodeid.startswith(prefix)) + ): + item.add_marker(pytest.mark.skip(reason=f"default at rest: {reason}")) + break _SESSION_ENV: dict[str, str | None] = {} @@ -98,7 +130,13 @@ def _isolation_env(root: Path) -> dict[str, str | None]: return { # Offline Seals must not create keys or a batch queue in the real home. - "OPENADAPT_SEALED_LOCK_DIR": str(root / ".sealed-locks"), + # Under the default mode, outside the test's own directories too: a + # lock file inside a directory a test seals is a stray file there. + "OPENADAPT_SEALED_LOCK_DIR": str( + Path(_SESSION_AT_REST_HOME) / "sealed-locks" + if _SESSION_AT_REST_HOME + else root / ".sealed-locks" + ), "OPENADAPT_SEAL_HOME": str(root / ".seal-home"), # Never create or read the real ~/.config/openadapt/frame.key. "OPENADAPT_FRAME_SECRET": "11" * 32, From 8cc262b69fd9825139902804c1451b0d24c775f7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 01:14:11 -0500 Subject: [PATCH 32/37] docs: drop the duplicate learn-probe row source (#2573 added it on main) --- CAPABILITIES.md | 5 +++-- .../0395-learn-per-request-bookkeeping-from-read-only.md | 1 - capabilities/CAPABILITIES.md.sha256 | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) delete mode 100644 capabilities/04-the-core-a-checked-entry-every-time/0395-learn-per-request-bookkeeping-from-read-only.md diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 0694f95760..972aa09be7 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -378,8 +378,8 @@ improvising or retrying when something is off. | Each package installs on its own within a size budget, checked in CI (privacy without desktop, capture without plotting) | Released ([#1270](https://github.com/OpenAdaptAI/OpenAdapt/pull/1270), [#1271](https://github.com/OpenAdaptAI/OpenAdapt/pull/1271), [#1279](https://github.com/OpenAdaptAI/OpenAdapt/pull/1279)) | CI | `.github/workflows/packages.yml` | | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | -| Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | -| Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | +| Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` authenticates the set's header, then destroys its tracked bucket-key copies, in the archive the set was written to (an archive counts only with its marker file), and the run's checkpoints, which are keyed from the run's own data key. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred, unmounted and moved archive, whole-set substitution, backlog race and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](packages/flow/docs/RECEIPTS.md); [vectors](packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | @@ -494,6 +494,7 @@ A test fails when a command has no file or this list is out of date. **Run on premises:** +- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, `restore` for a backup only the recovery code opens, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. - `no-outbound` - `service` diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0395-learn-per-request-bookkeeping-from-read-only.md b/capabilities/04-the-core-a-checked-entry-every-time/0395-learn-per-request-bookkeeping-from-read-only.md deleted file mode 100644 index 623d9f603d..0000000000 --- a/capabilities/04-the-core-a-checked-entry-every-time/0395-learn-per-request-bookkeeping-from-read-only.md +++ /dev/null @@ -1 +0,0 @@ -| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user that every round (at least two) shows (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts whose every effect creates new records, or that read the target's versions on every other effect's surface, get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | diff --git a/capabilities/CAPABILITIES.md.sha256 b/capabilities/CAPABILITIES.md.sha256 index ce6569dcc8..3cb555d374 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -93e2f3c7e6f63fe1c2bc96a55ee62c99a582690971839a0e84e250ce01d421da +b2786fb1a9fca82ba1ca70d49e8bbe07a07ab91501fca8412029f2bbc4c2af62 From 9db1a8acadce6fedd795524cf621ef91834c8702 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 02:31:08 -0500 Subject: [PATCH 33/37] flow: receipts and handoff follow-ups for encrypted runs; JIT drafts plaintext by design, ledgered - Run receipts are written for encrypted runs (the default): receipt.json stays a structural file of the set, the private openings, card and follow-ups are sealed in it, and receipts and follow-ups serialize on a lock of their own (sealed_set.side_lock). Verification and the handoff list read them through the set. - The JIT compile agent's capture (recording, draft bundle, signed records) is plaintext by design: named on stderr and in the ledger, refused in strict mode before recording, with the opt-out held for that capture only. - distill: a type fix for mypy. - Tests: the default-mode session home resolves symlinks. --- .../flow/openadapt_flow/cli_handoff_list.py | 10 ++- .../flow/openadapt_flow/compiler/distill.py | 4 +- .../flow/openadapt_flow/handoffs/followup.py | 73 +++++++++++++++---- .../flow/openadapt_flow/jit/compile_agent.py | 36 ++++++++- .../flow/openadapt_flow/receipt_record.py | 59 ++++++++++----- packages/flow/openadapt_flow/sealed_set.py | 15 ++++ packages/flow/tests/conftest.py | 4 +- 7 files changed, 158 insertions(+), 43 deletions(-) diff --git a/packages/flow/openadapt_flow/cli_handoff_list.py b/packages/flow/openadapt_flow/cli_handoff_list.py index 3ba7d8d59a..b1869e7b11 100644 --- a/packages/flow/openadapt_flow/cli_handoff_list.py +++ b/packages/flow/openadapt_flow/cli_handoff_list.py @@ -263,12 +263,14 @@ def _history( from openadapt_types import receipt as r + from openadapt_flow import sealed_set from openadapt_flow.handoffs.followup import SIDECAR - orphans = ( - any(run_dir.glob("receipt.update-*.json")) or (run_dir / SIDECAR).is_file() - ) - if not (run_dir / r.RECEIPT_FILE).is_file() and not orphans: + # Read through the run's sealed set: it is encrypted by default. + orphans = bool( + sealed_set.list_files(run_dir, "receipt.update-*.json") + ) or sealed_set.is_file(run_dir / SIDECAR) + if not sealed_set.is_file(run_dir / r.RECEIPT_FILE) and not orphans: return {"error": "no receipt.json in the run"} if sign else None try: from openadapt_flow.handoffs.followup import sign_updates, verify_history diff --git a/packages/flow/openadapt_flow/compiler/distill.py b/packages/flow/openadapt_flow/compiler/distill.py index 563a9915c4..c70cf658aa 100644 --- a/packages/flow/openadapt_flow/compiler/distill.py +++ b/packages/flow/openadapt_flow/compiler/distill.py @@ -525,7 +525,9 @@ def frame(i: int, side: str) -> Optional[np.ndarray]: # nothing it holds is written in plaintext. sealed_src = sealed_set.is_sealed_path(src) if sealed_src: - target: Any = sealed_set.writing(dst, "recording", sealed_set.recording_key()) + target: Any = sealed_set.writing( + dst, "recording", sealed_set.recording_key() or "" + ) else: dst.mkdir(parents=True) (dst / "frames").mkdir() diff --git a/packages/flow/openadapt_flow/handoffs/followup.py b/packages/flow/openadapt_flow/handoffs/followup.py index 5ac9aaa519..79140fb03d 100644 --- a/packages/flow/openadapt_flow/handoffs/followup.py +++ b/packages/flow/openadapt_flow/handoffs/followup.py @@ -57,7 +57,37 @@ def _signature(handoff: Handoff) -> dict[str, Any]: return {**item.line, "values": values} +def _is_file(path: Path) -> bool: + # The run directory is encrypted by default: its files are read, written + # and removed through its sealed set (in memory), never in plaintext. + from openadapt_flow import sealed_set + + return sealed_set.is_file(path) + + +def _read(path: Path) -> str: + from openadapt_flow import sealed_set + + return sealed_set.read_text(path) + + +def _unlink(path: Path) -> None: + from openadapt_flow import sealed_set + + if sealed_set.is_sealed_path(path): + sealed_set.unlink(path, missing_ok=True) + else: + path.unlink(missing_ok=True) + + def _write_json(path: Path, payload: Any, *, private: bool) -> None: + from openadapt_flow import sealed_set + + if sealed_set.is_sealed_path(path): + sealed_set.write_text( + path, json.dumps(payload, indent=2, sort_keys=True) + "\n" + ) + return tmp = path.with_name(path.name + ".tmp") fd = os.open( tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600 if private else 0o644 @@ -69,9 +99,9 @@ def _write_json(path: Path, payload: Any, *, private: bool) -> None: def _sidecar(run_dir: Path) -> dict[str, Any]: path = run_dir / SIDECAR - if not path.is_file(): + if not _is_file(path): return {"schema": SCHEMA, "records": []} - data = json.loads(path.read_text("utf-8")) + data = json.loads(_read(path)) if data.get("schema") != SCHEMA: raise ValueError(f"{SIDECAR} is not {SCHEMA}") return data @@ -112,7 +142,9 @@ def updates(run_dir: Path) -> list[Path]: """ numbers: list[int] = [] private_numbers: set[int] = set() - for path in Path(run_dir).iterdir(): + from openadapt_flow import sealed_set + + for path in sealed_set.list_files(run_dir, "receipt.update-*"): match = _UPDATE_NAME.match(path.name) if not match: continue @@ -148,15 +180,15 @@ def _finish_pending(run_dir: Path, registry: Sequence[Any]) -> None: from openadapt_flow.offline_seal import loads_strict pending = _pending_path(run_dir) - if not pending.is_file(): + if not _is_file(pending): return - note = json.loads(pending.read_text("utf-8")) + note = json.loads(_read(pending)) out = run_dir / str(note["file"]) private = run_dir / str(note["private"]) complete = False try: - envelope = loads_strict(out.read_text("utf-8")) - complete = r.verify_receipt(envelope, registry).ok and private.is_file() + envelope = loads_strict(_read(out)) + complete = r.verify_receipt(envelope, registry).ok and _is_file(private) except (OSError, ValueError): complete = False if complete: @@ -166,8 +198,8 @@ def _finish_pending(run_dir: Path, registry: Sequence[Any]) -> None: _write_json(run_dir / SIDECAR, data, private=True) else: for partial in (out, private): - partial.unlink(missing_ok=True) - pending.unlink() + _unlink(partial) + _unlink(pending) def sign_updates( @@ -185,6 +217,13 @@ def sign_updates( completed or rolled back by the next call.""" run_dir = Path(run_dir) + from openadapt_flow import sealed_set + + if sealed_set.is_sealed(run_dir): + # An encrypted run's writes take its set's lock per write; one signer + # at a time holds a lock of its own instead of a file in the set. + with sealed_set.side_lock(run_dir, "receipt-update"): + return _sign_updates_locked(run_dir, ledgers, signer=signer) lock = run_dir / ".receipt-update.lock" try: fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) @@ -214,7 +253,7 @@ def _sign_updates_locked( kid, base64.b64encode(signer.public_raw()).decode("ascii"), "this_computer" ) _finish_pending(run_dir, [own]) - original = loads_strict((run_dir / r.RECEIPT_FILE).read_text("utf-8")) + original = loads_strict(_read(run_dir / r.RECEIPT_FILE)) # Extend only a chain that verifies as it stands, signed by this key # alone: the receipt and every update already written. verify_chain # refuses a follow-up from any other key. @@ -225,7 +264,9 @@ def _sign_updates_locked( f" ({existing.detail})" if existing is not None and existing.detail else "" ) raise ValueError(f"the run's receipt does not verify: {reason}{detail}") - raw_report = (run_dir / "report.json").read_bytes() + from openadapt_flow import sealed_set + + raw_report = sealed_set.read_bytes(run_dir / "report.json") statement = r.loads_strict(base64.b64decode(original["payload"])) subjects = { x["name"]: x["digest"]["sha256"] for x in statement.get("subject") or [] @@ -249,7 +290,7 @@ def _sign_updates_locked( out = run_dir / update_file(sequence) # Race class: a sequence is claimed exclusively, so two signers can't # write the same update; the loser fails and signs nothing. - if out.exists(): + if _is_file(out): raise ValueError(f"{out.name} was written by another signer") # Durable before any update file: what this update is, so an # interrupted publication can be completed or rolled back. @@ -269,7 +310,7 @@ def _sign_updates_locked( ) _write_json(out, envelope, private=False) record_signed(run_dir, out.name, changed) - _pending_path(run_dir).unlink() + _unlink(_pending_path(run_dir)) return out @@ -285,12 +326,12 @@ def verify_history(run_dir: str | Path, registry: Sequence[Any]) -> Any: def load(name: str) -> Optional[Mapping[str, Any]]: path = run_dir / name - return loads_strict(path.read_text("utf-8")) if path.is_file() else None + return loads_strict(_read(path)) if _is_file(path) else None original = load(r.RECEIPT_FILE) found = updates(run_dir) if original is None: - if found or (run_dir / SIDECAR).is_file(): + if found or _is_file(run_dir / SIDECAR): # Missing-evidence class: signed updates without their receipt are # a broken history, not an unsigned run. raise ValueError("signed updates are here but receipt.json is missing") @@ -304,7 +345,7 @@ def load(name: str) -> Optional[Mapping[str, Any]]: ] if sorted(recorded) != sorted(p.name for p in found): raise ValueError("the signed updates don't match the record of what was signed") - chain = [loads_strict(p.read_text("utf-8")) for p in found] + chain = [loads_strict(_read(p)) for p in found] return r.verify_chain( original, chain, diff --git a/packages/flow/openadapt_flow/jit/compile_agent.py b/packages/flow/openadapt_flow/jit/compile_agent.py index 94317053fd..667de61ebf 100644 --- a/packages/flow/openadapt_flow/jit/compile_agent.py +++ b/packages/flow/openadapt_flow/jit/compile_agent.py @@ -535,6 +535,40 @@ def __init__( self._baseline: Optional[list[dict[str, Any]]] = None def __enter__(self) -> "Recording": + """The JIT cache (recording, draft bundle, signed records) is + plaintext by design: the draft lifecycle re-seals and signs the + bundle's files directly. Under the default (encryption on), this + capture is named on stderr and in the plaintext ledger, and strict + mode refuses it before anything is recorded. The opt-out lasts for + this capture only.""" + from contextlib import ExitStack + + from openadapt_flow import at_rest + + at_rest.unsealed_write( + "a JIT draft (its recording and bundle are plaintext by design)", + self._owner.program_dir, + ) + self._plaintext = ExitStack() + self._plaintext.enter_context(at_rest.opted_out("a JIT draft")) + try: + return self._enter_capture() + except BaseException: + self._plaintext.close() + raise + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> bool: + try: + return self._exit_capture(exc_type, exc, tb) + finally: + self._plaintext.close() + + def _enter_capture(self) -> "Recording": from openadapt_flow.authoring import AuthoringSession from openadapt_flow.backends._owned import close_owned @@ -642,7 +676,7 @@ def discard_unstarted_coroutine() -> None: raise return self - def __exit__( + def _exit_capture( self, exc_type: Optional[type[BaseException]], exc: Optional[BaseException], diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index c0b46e888e..3b85d83183 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -422,6 +422,13 @@ def build_statement( def _write(path: Path, payload: Mapping[str, Any], *, private: bool = False) -> None: data = (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode("utf-8") + from openadapt_flow import sealed_set + + if sealed_set.is_sealed_path(path): + # An encrypted run (the default): the receipt is a structural file of + # its set, the private openings and the card are sealed with it. + sealed_set.write_bytes(path, data) + return fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) try: with os.fdopen(fd, "wb") as handle: @@ -453,9 +460,17 @@ def write_receipt_record( Idempotent: an existing receipt over the same report bytes is kept. A receipt over different bytes is never silently replaced. """ + from openadapt_flow import sealed_set from openadapt_flow.sealed_maintenance import mutation_lock - with mutation_lock(run_dir): + # An encrypted run's writes go through its sealed writer, which takes the + # set's own lock per write; serialize receipts on a lock of their own. + lock = ( + sealed_set.side_lock(run_dir, "receipt") + if sealed_set.is_sealed(run_dir) + else mutation_lock(run_dir) + ) + with lock: return _write_locked( Path(run_dir), signer, @@ -483,12 +498,7 @@ def _write_locked( from openadapt_flow.runtime.durable.checkpoint import CheckpointStore from openadapt_flow.seal_keys import KeyUnavailable - # Private openings need encrypted-set support before they can be persisted - # beside an encrypted report. A direct caller has the same boundary as CLI. - if sealed_set.is_sealed(run_dir): - raise ReceiptRecordError( - "encrypted_run", "private openings require encrypted storage" - ) + # In an encrypted run the private openings are sealed in its set. try: pending = CheckpointStore(run_dir).read_pending() except Exception as exc: @@ -554,12 +564,14 @@ def _write_locked( out = run_dir / RECEIPT_FILE private = run_dir / PRIVATE_FILE legacy = None - if out.exists(): + if sealed_set.is_file(out): try: - existing = r.loads_strict(out.read_bytes()) + existing = r.loads_strict(sealed_set.read_bytes(out)) if r.is_receipt_envelope(existing): checked = r.verify_receipt( - existing, registry, openings=r.loads_strict(private.read_bytes()) + existing, + registry, + openings=r.loads_strict(sealed_set.read_bytes(private)), ) if ( not checked.ok @@ -590,7 +602,9 @@ def _write_locked( "already_signed", "receipt facts differ from the settled report" ) write_public_card( - run_dir, existing, r.loads_strict(private.read_bytes())["openings"] + run_dir, + existing, + r.loads_strict(sealed_set.read_bytes(private))["openings"], ) return existing except (OSError, ValueError) as exc: @@ -601,7 +615,9 @@ def _write_locked( ): raise ReceiptRecordError("existing_unreadable", "unrecognized receipt file") legacy = run_dir / "run-summary.json" - if legacy.exists() and legacy.read_bytes() != out.read_bytes(): + if sealed_set.is_file(legacy) and sealed_set.read_bytes( + legacy + ) != sealed_set.read_bytes(out): raise ReceiptRecordError( "legacy_summary_conflict", "both summary files exist and differ" ) @@ -611,10 +627,13 @@ def _write_locked( raise ReceiptRecordError(exc.code, str(exc)) from exc if sealed_set.read_bytes(path) != raw: raise ReceiptRecordError("report_changed", "report changed while signing") - if legacy is not None and not legacy.exists(): + if legacy is not None and not sealed_set.is_file(legacy): # Preserve the original bytes; an error before envelope installation # leaves the legacy file and any earlier summary readable. - os.link(out, legacy) + if sealed_set.is_sealed_path(out): + sealed_set.write_bytes(legacy, sealed_set.read_bytes(out)) + else: + os.link(out, legacy) _write(private, r.private_openings(envelope, openings), private=True) _write(out, envelope) write_public_card(run_dir, envelope, openings) @@ -740,9 +759,7 @@ def receipt_after_run( return None from openadapt_flow import sealed_set - if sealed_set.is_sealed(Path(run_dir)): - return "receipt not written: the run directory is encrypted at rest" - if not (Path(run_dir) / "report.json").is_file(): + if not sealed_set.is_file(Path(run_dir) / "report.json"): return None try: from openadapt_flow.handoffs.registry import ledgers_for @@ -861,16 +878,18 @@ def verify_run_receipt( run_dir = Path(run_dir) try: - envelope = loads_strict((run_dir / RECEIPT_FILE).read_text(encoding="utf-8")) + if not sealed_set.is_file(run_dir / RECEIPT_FILE): + raise FileNotFoundError(RECEIPT_FILE) + envelope = loads_strict(sealed_set.read_text(run_dir / RECEIPT_FILE)) except FileNotFoundError: return r._refuse("unsigned", "no receipt.json") except (OSError, ValueError): return r._refuse("malformed", "receipt.json is not JSON") openings = None private = run_dir / PRIVATE_FILE - if private.is_file(): + if sealed_set.is_file(private): try: - openings = loads_strict(private.read_text(encoding="utf-8")) + openings = loads_strict(sealed_set.read_text(private)) except (OSError, ValueError): return r._refuse("malformed", "receipt.private.json is not JSON") result = r.verify_receipt(envelope, registry, openings=openings) diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index dfc59a8aab..77fe6414fc 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -1562,6 +1562,21 @@ def write_bytes(path: Path | str, data: bytes, *, key: Optional[str] = None) -> resumed.finalize() +@contextmanager +def side_lock(path: Path | str, purpose: str) -> Iterator[None]: + """A lock for one operation on ``path`` that also writes through the + sealed set (whose writer takes the set's own lock for each write, and + can't be nested inside it): a private folder per path and purpose.""" + from openadapt_flow import at_rest + + digest = hashlib.sha256(os.fsencode(_abs(path))).hexdigest()[:32] + lock_dir = at_rest._home() / "locks" / f"{purpose}-{digest}" + at_rest._private_dir(lock_dir.parent) + at_rest._private_dir(lock_dir) + with mutation_lock(lock_dir): + yield + + def replace_bytes(path: Path | str, data: bytes) -> None: """Replace ``path`` atomically: through its sealed set when it lies in one (whose writer replaces files atomically), else by a rename.""" diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index 672289de09..d87018ce25 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -79,7 +79,9 @@ def _configure_at_rest() -> None: if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") == "1": import tempfile - _SESSION_AT_REST_HOME = tempfile.mkdtemp(prefix="openadapt-at-rest-home-") + _SESSION_AT_REST_HOME = os.path.realpath( + tempfile.mkdtemp(prefix="openadapt-at-rest-home-") + ) wanted["OPENADAPT_FLOW_AT_REST_HOME"] = _SESSION_AT_REST_HOME if os.environ.get("OPENADAPT_TEST_DEFAULT_AT_REST") != "1": wanted["OPENADAPT_FLOW_PLAINTEXT_AT_REST"] = os.environ.get( From d139238bc4fcd12c0425c1d13d15edf4001f99b0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 03:01:40 -0500 Subject: [PATCH 34/37] flow: more readers of encrypted runs and bundles (default-mode triage) - The JIT capture's plaintext opt-out stack exists from construction, so a capture closed without entering still cleans up. - verify_integrity hashes an encrypted bundle's assets in memory. - The variant router reads the child run's report through the sealed set. - The console shows an encrypted run's pending escalation. - The approver-root pin (a key fingerprint, key directory and roster head, written before the run) is a structural file of a run set. --- .../flow/openadapt_flow/bundle_validation.py | 11 +++++++++ packages/flow/openadapt_flow/console/data.py | 24 ++++++++++++++++++- .../flow/openadapt_flow/jit/compile_agent.py | 11 +++++---- .../openadapt_flow/runtime/variant_router.py | 9 ++++--- packages/flow/openadapt_flow/sealed_set.py | 6 +++++ 5 files changed, 53 insertions(+), 8 deletions(-) diff --git a/packages/flow/openadapt_flow/bundle_validation.py b/packages/flow/openadapt_flow/bundle_validation.py index 6b5505d141..c5b80285d3 100644 --- a/packages/flow/openadapt_flow/bundle_validation.py +++ b/packages/flow/openadapt_flow/bundle_validation.py @@ -1231,6 +1231,17 @@ def _verify_asset_hashes( decrypted_assets: Optional[dict[str, bytes]] = None, ) -> None: bundle = Path(bundle_dir) + if decrypted_assets is None: + from openadapt_flow import sealed_set + + if sealed_set.is_sealed_path(bundle): + # An encrypted bundle (the default): hash each asset's + # authenticated plaintext, read in memory. + decrypted_assets = {} + for rel in stored.file_hashes: + path = bundle_asset_path(bundle, rel) + if sealed_set.is_file(path): + decrypted_assets[rel] = sealed_set.read_bytes(path) for rel, expected in stored.file_hashes.items(): path = bundle_asset_path(bundle, rel) if decrypted_assets is not None: diff --git a/packages/flow/openadapt_flow/console/data.py b/packages/flow/openadapt_flow/console/data.py index 8ea1dbe518..b13ddfd597 100644 --- a/packages/flow/openadapt_flow/console/data.py +++ b/packages/flow/openadapt_flow/console/data.py @@ -530,6 +530,28 @@ def _read_json_opt( return None +def _read_pending(path: Path) -> Optional[dict[str, Any]]: + """The run's pending escalation, in either form: plaintext, or encrypted + (the default) and opened through the run's own checkpoint store. Only + its status and resume index are shown.""" + plain = _read_json_opt(path / "pending_escalation.json", root=path) + if ( + plain is not None + or _contained_file(path, path / "pending_escalation.json.enc") is None + ): + return plain + try: + from openadapt_flow import crypto + from openadapt_flow.runtime.durable.checkpoint import CheckpointStore + + pending = CheckpointStore( + path, key=crypto.resolve_read_key(None) + ).read_pending() + except Exception: # noqa: BLE001 - unreadable: shown as nothing, never guessed + return None + return pending.model_dump(mode="json") if pending is not None else None + + def run_summary(root: Path, path: Path) -> RunSummary: report, err = _load_report(path) paused = any( @@ -679,7 +701,7 @@ def run_detail(root: Path, path: Path) -> dict[str, Any]: if report.halt else None ) - pending = _read_json_opt(path / "pending_escalation.json", root=path) + pending = _read_pending(path) out["pending_escalation"] = ( { "category": "operator_review", diff --git a/packages/flow/openadapt_flow/jit/compile_agent.py b/packages/flow/openadapt_flow/jit/compile_agent.py index 667de61ebf..b9abf3bd47 100644 --- a/packages/flow/openadapt_flow/jit/compile_agent.py +++ b/packages/flow/openadapt_flow/jit/compile_agent.py @@ -533,6 +533,10 @@ def __init__( self.guard: Optional["TeachGuard"] = None self.dispatcher: Optional[RecordingDispatcher] = None self._baseline: Optional[list[dict[str, Any]]] = None + from contextlib import ExitStack + + #: The capture's plaintext opt-out (see ``__enter__``). + self._plaintext = ExitStack() def __enter__(self) -> "Recording": """The JIT cache (recording, draft bundle, signed records) is @@ -541,15 +545,12 @@ def __enter__(self) -> "Recording": capture is named on stderr and in the plaintext ledger, and strict mode refuses it before anything is recorded. The opt-out lasts for this capture only.""" - from contextlib import ExitStack - from openadapt_flow import at_rest at_rest.unsealed_write( "a JIT draft (its recording and bundle are plaintext by design)", self._owner.program_dir, ) - self._plaintext = ExitStack() self._plaintext.enter_context(at_rest.opted_out("a JIT draft")) try: return self._enter_capture() @@ -566,7 +567,9 @@ def __exit__( try: return self._exit_capture(exc_type, exc, tb) finally: - self._plaintext.close() + plaintext = getattr(self, "_plaintext", None) + if plaintext is not None: + plaintext.close() def _enter_capture(self) -> "Recording": from openadapt_flow.authoring import AuthoringSession diff --git a/packages/flow/openadapt_flow/runtime/variant_router.py b/packages/flow/openadapt_flow/runtime/variant_router.py index be8f317c99..1ea2cbf2a3 100644 --- a/packages/flow/openadapt_flow/runtime/variant_router.py +++ b/packages/flow/openadapt_flow/runtime/variant_router.py @@ -530,13 +530,16 @@ def halted(reason: RouteReason, detail: str) -> VariantRunReport: child=spec.name, child_run=child_run, ) + from openadapt_flow import sealed_set + + # The child's run directory is encrypted by default: read in memory. report_path = Path(result.report_path) if result.report_path else None - if report_path is None and (child_dir / "report.json").is_file(): + if report_path is None and sealed_set.is_file(child_dir / "report.json"): report_path = child_dir / "report.json" report_sha256: Optional[str] = None names_variant = False - if report_path is not None and report_path.is_file(): - raw = report_path.read_bytes() + if report_path is not None and sealed_set.is_file(report_path): + raw = sealed_set.read_bytes(report_path) report_sha256 = hashlib.sha256(raw).hexdigest() try: names_variant = RunReport.model_validate_json(raw).variant_route == stamp diff --git a/packages/flow/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index 77fe6414fc..8d54c80163 100644 --- a/packages/flow/openadapt_flow/sealed_set.py +++ b/packages/flow/openadapt_flow/sealed_set.py @@ -275,6 +275,12 @@ class FileKind: "a random per-run capability secret (no recorded data)", ), FileKind(".attended_action.lease", "structural", "an action lease marker"), + FileKind( + "item-approval/approver-root.json", + "structural", + "the run's approver-root pin: a key fingerprint, key directory and " + "roster head, written before the run (no record data)", + ), FileKind( ".report_run_id", "structural", From 7b5393a1bda193f2834ab594a1de0dd6816001e6 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 03:29:09 -0500 Subject: [PATCH 35/37] ci: the default-at-rest suite is required on pull requests, with its triaged skips - tests/default_at_rest_skips.txt: each test skipped under OPENADAPT_TEST_DEFAULT_AT_REST=1, with its reason (group a: the test reads or plants plaintext and the product correctly refuses; group b, open: attended approvals, drafts, business decisions and teach on encrypted input). The matcher takes a test, its class or its file. - flow default at rest joins packages-gate (pull requests only). - Merge origin/main and regenerate CAPABILITIES.md and llms-full.txt. --- .github/workflows/packages.yml | 14 +++++++----- CAPABILITIES.md | 1 + capabilities/CAPABILITIES.md.sha256 | 2 +- llms-full.txt | 34 +++++++++++++++++++++-------- packages/flow/tests/conftest.py | 17 +++++++-------- 5 files changed, 43 insertions(+), 25 deletions(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 0036177c3f..514d3abc46 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -673,10 +673,11 @@ jobs: openadapt_flow/compiler/loop_authoring.py flow-default-at-rest: - # TEMPORARY (#2423): the whole flow suite under the product default, - # encryption at rest on (no plaintext opt-out). Informational while the - # results are triaged; it gates nothing. - name: flow default at rest (shard ${{ matrix.shard }}/${{ matrix.of }}, informational) + # The whole flow suite under the product default: encryption at rest on + # (no plaintext opt-out). Required on pull requests. Tests that read or + # plant plaintext files directly, and known open limitations, are skipped + # in this mode with their reason (tests/default_at_rest_skips.txt, #2423). + name: flow default at rest (shard ${{ matrix.shard }}/${{ matrix.of }}) needs: scope # PR and post-merge tiers. The merge queue skips it: a pull request can # enter the queue only after packages-gate passed with these shards green @@ -826,7 +827,6 @@ jobs: | python ../../scripts/ci/flow_shards.py --shard "$SHARD" --of "$SHARDS" > "$RUNNER_TEMP/shard.txt" wc -l < "$RUNNER_TEMP/shard.txt" - name: Test under the default (encrypted) mode - continue-on-error: true env: OPENADAPT_TEST_DEFAULT_AT_REST: "1" OPENADAPT_TEST_LANE: fast @@ -2099,6 +2099,7 @@ jobs: - verify-clean-install - flow-lint - flow-unit + - flow-default-at-rest - flow-critical - flow-onprem-offline - flow-agent-frameworks @@ -2156,6 +2157,7 @@ jobs: "verify-clean-install": "verify", "flow-lint": "flow", "flow-unit": "flow", + "flow-default-at-rest": "flow", "flow-critical": "flow", "flow-onprem-offline": "flow", "flow-agent-frameworks": "flow", @@ -2190,7 +2192,7 @@ jobs: # it on its merge with main (packages-gate is required there). not_in_queue = {"flow-unit"} # PR tier only: checks a pull request's own diff. - pr_only = {"desktop-release-intent"} + pr_only = {"desktop-release-intent", "flow-default-at-rest"} scope = needs["scope"] outputs = scope.get("outputs", {}) bad = {} diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 972aa09be7..046a342325 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -346,6 +346,7 @@ improvising or retrying when something is off. | Score a candidate before it saves anything: `openadapt-flow readiness` imports 20 to 50 tasks a person did (the save from the browser recording's network capture, else a read-back through the verify config's reader, else refused), runs the candidate agent (`--agent-cmd`) or compiled program (`--program`) on each task in its own headless browser (DevTools on a pipe only, reached through a loopback relay that refuses any request without the run's random token; the page can reach only the app's origins) where the shadow hold refuses every non-GET request to the app origin (autosaves, drafts and locks included) after recording the write it would have made, and a browser-level hold hands every request of every other tab, popup, browser context and worker to the same hold (a write from one of them makes the case `NOT_CHECKED`, reason `extra_target`, and `scope_ok` false). It compares the write field by field with the person's save (identifiers such as `02134` compare as exact text; any extra held write fails the match; uncompared never counts as matched; a prefilled form or other contamination makes a case not comparable), and writes a one-page `scorecard.html` and an aggregates-only `scorecard.json` (matched N of M, risks, field errors, agent and human time, model cost and its source, estimated savings with its formula). Each candidate runs under the flight recorder's egress (`--egress scrubbed` by default, `blocked` or `unscrubbed`) with the OS egress block, and cost is metered by the proxy; a candidate that reports model calls the proxy didn't see is refused for that task. Each imported task names its target record in the candidate's inputs (`record_`). `--keep-session` carries a signed-in session across tasks. A card whose scope failed states what failed in place of the claim. What is checked: no non-GET request to the app origin left any tab, popup, browser context or worker except listed sign-in requests; not covered: GET requests with side effects, WebSocket writes, writes before attach | On main ([#2498](https://github.com/OpenAdaptAI/OpenAdapt/pull/2498)) | Synthetic (MockMed, 20 recorded tasks; scripted agent with 5 planted field errors and 2 wrong-record cases: precision and recall 1.0, 0 writes in the app's own store; an adversarial agent's six routes around the tab (popup form, `window.open`, `Target.createTarget`, a new browser context, a shared worker, a dedicated worker) land 0 writes in the store) | `openadapt-flow readiness`, [READINESS.md](packages/flow/docs/READINESS.md), [benchmark/readiness](packages/flow/benchmark/readiness/README.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](packages/flow/benchmark/skill_cache/README.md) | | Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | +| Try `openadapt wrap` with one command: `uvx --python 3.12 'openadapt[wrap]@latest' wrap --example` (the `wrap` extra brings the agent SDK; the base launcher leaves it out) starts a bundled synthetic clinic app (MockMed) on 127.0.0.1, has OpenAdapt's built-in Claude agent save one note in a headless browser, reads the save back, compiles the run, runs a canary, and admits it with a throwaway key made in the example's own folder (the proposed checks are confirmed automatically, which only a synthetic app allows). Then a new note runs the compiled program over its emitted MCP server with no model calls, and it prints the app's record and the cost of both runs. It needs `ANTHROPIC_API_KEY` (or `OPENAI_API_KEY` with `--provider openai`, `--model` and reviewed `--price` values); the task is packaged data (`openadapt_flow/wrap/examples/`). Because the data is synthetic, screenshots go to the model unscrubbed under the recorded opt-out. Emitted MCP tools now run the program off the server's event loop, so a compiled browser program runs when called over MCP (it failed with Playwright's "Sync API inside the asyncio loop" error before) | In PR | Synthetic (the bundled app, headless Chromium and the real `build_agent` Claude loop with its token-count reservation and spend cap; CI uses a scripted model client in place of the Anthropic SDK). One real run (Claude Opus 5.5, macOS, before release): run 1 made 5 model calls for $0.15 and was admitted; run 2 made none and was read back `VERIFIED` ([benchmark/wrap_example](packages/flow/benchmark/wrap_example/real-run-2026-11-21.json)) | [WRAP.md](packages/flow/docs/WRAP.md), `openadapt_flow.wrap.example`, `openadapt_flow.compile_agent.run_compiled_tool`, `packages/flow/tests/e2e/test_wrap_example_e2e.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Sign-ins with a second factor: a `second_factor` step (`code` for a text-message, email or authenticator code, `approval` for a push approval) waits for a person when it runs, through the runner's control plane, a local command, or the run's own terminal when it has one (on a POSIX terminal or the Windows console; the code is never echoed, and normal input comes back however the read ends). Before anyone is asked, the focused field must be an empty `autocomplete="one-time-code"` input and the page draws it as dots; after the answer the same field must still have focus and be empty. The code is filled once into that element (a field split into one box per character is refused), never retried, and never stored, logged, shown to a model or drawn on screen. No source, a late or malformed answer, a decline, a field that changed, or a backend that can't bind the field stops the step before typing with a closed `second_factor_*` code; an older runtime refuses the bundle. Over the control plane the code is sealed in the person's browser to a one-step key the control plane can't open. The wrap recorder finds a code field from `autocomplete="one-time-code"` alone; it doesn't detect push approvals, and only the local browser backend can take a code | In PR | Synthetic (a notes app with an authenticator page in headless Chromium through the real wrap path: first run, canary, admission, publish staging, a cached run and a declined run, with a byte scan for the TOTP secret and recent codes; headless-browser tests that two codes render the same pixels and that a focus change, a prefilled field or an auto-submitting page are handled; unit tests for every source, late answers, the step shape and every refusal; pty tests that a terminal prompt hides the code, restores echo after a timeout and answers the next prompt; the Windows console reader's deadline and discard logic on a fake keyboard). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, `openadapt_flow.runtime.second_factor_step`, [SECOND_FACTOR.md](packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/test_second_factor_browser.py`, `packages/flow/tests/test_second_factor_terminal.py`, `packages/flow/tests/test_second_factor_console.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](packages/flow/docs/AGENT_FRAMEWORKS.md) | diff --git a/capabilities/CAPABILITIES.md.sha256 b/capabilities/CAPABILITIES.md.sha256 index 3cb555d374..4d03e41523 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -b2786fb1a9fca82ba1ca70d49e8bbe07a07ab91501fca8412029f2bbc4c2af62 +f7fe14aa18e871fdb1b90196d60ad25b73fdf73cad14691031ab56d483843c48 diff --git a/llms-full.txt b/llms-full.txt index f4e616d698..72152c8c73 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -817,6 +817,7 @@ improvising or retrying when something is off. | Score a candidate before it saves anything: `openadapt-flow readiness` imports 20 to 50 tasks a person did (the save from the browser recording's network capture, else a read-back through the verify config's reader, else refused), runs the candidate agent (`--agent-cmd`) or compiled program (`--program`) on each task in its own headless browser (DevTools on a pipe only, reached through a loopback relay that refuses any request without the run's random token; the page can reach only the app's origins) where the shadow hold refuses every non-GET request to the app origin (autosaves, drafts and locks included) after recording the write it would have made, and a browser-level hold hands every request of every other tab, popup, browser context and worker to the same hold (a write from one of them makes the case `NOT_CHECKED`, reason `extra_target`, and `scope_ok` false). It compares the write field by field with the person's save (identifiers such as `02134` compare as exact text; any extra held write fails the match; uncompared never counts as matched; a prefilled form or other contamination makes a case not comparable), and writes a one-page `scorecard.html` and an aggregates-only `scorecard.json` (matched N of M, risks, field errors, agent and human time, model cost and its source, estimated savings with its formula). Each candidate runs under the flight recorder's egress (`--egress scrubbed` by default, `blocked` or `unscrubbed`) with the OS egress block, and cost is metered by the proxy; a candidate that reports model calls the proxy didn't see is refused for that task. Each imported task names its target record in the candidate's inputs (`record_`). `--keep-session` carries a signed-in session across tasks. A card whose scope failed states what failed in place of the claim. What is checked: no non-GET request to the app origin left any tab, popup, browser context or worker except listed sign-in requests; not covered: GET requests with side effects, WebSocket writes, writes before attach | On main ([#2498](https://github.com/OpenAdaptAI/OpenAdapt/pull/2498)) | Synthetic (MockMed, 20 recorded tasks; scripted agent with 5 planted field errors and 2 wrong-record cases: precision and recall 1.0, 0 writes in the app's own store; an adversarial agent's six routes around the tab (popup form, `window.open`, `Target.createTarget`, a new browser context, a shared worker, a dedicated worker) land 0 writes in the store) | `openadapt-flow readiness`, [READINESS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/READINESS.md), [benchmark/readiness](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/readiness/README.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/skill_cache/README.md) | | Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | +| Try `openadapt wrap` with one command: `uvx --python 3.12 'openadapt[wrap]@latest' wrap --example` (the `wrap` extra brings the agent SDK; the base launcher leaves it out) starts a bundled synthetic clinic app (MockMed) on 127.0.0.1, has OpenAdapt's built-in Claude agent save one note in a headless browser, reads the save back, compiles the run, runs a canary, and admits it with a throwaway key made in the example's own folder (the proposed checks are confirmed automatically, which only a synthetic app allows). Then a new note runs the compiled program over its emitted MCP server with no model calls, and it prints the app's record and the cost of both runs. It needs `ANTHROPIC_API_KEY` (or `OPENAI_API_KEY` with `--provider openai`, `--model` and reviewed `--price` values); the task is packaged data (`openadapt_flow/wrap/examples/`). Because the data is synthetic, screenshots go to the model unscrubbed under the recorded opt-out. Emitted MCP tools now run the program off the server's event loop, so a compiled browser program runs when called over MCP (it failed with Playwright's "Sync API inside the asyncio loop" error before) | In PR | Synthetic (the bundled app, headless Chromium and the real `build_agent` Claude loop with its token-count reservation and spend cap; CI uses a scripted model client in place of the Anthropic SDK). One real run (Claude Opus 5.5, macOS, before release): run 1 made 5 model calls for $0.15 and was admitted; run 2 made none and was read back `VERIFIED` ([benchmark/wrap_example](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/wrap_example/real-run-2026-11-21.json)) | [WRAP.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP.md), `openadapt_flow.wrap.example`, `openadapt_flow.compile_agent.run_compiled_tool`, `packages/flow/tests/e2e/test_wrap_example_e2e.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Sign-ins with a second factor: a `second_factor` step (`code` for a text-message, email or authenticator code, `approval` for a push approval) waits for a person when it runs, through the runner's control plane, a local command, or the run's own terminal when it has one (on a POSIX terminal or the Windows console; the code is never echoed, and normal input comes back however the read ends). Before anyone is asked, the focused field must be an empty `autocomplete="one-time-code"` input and the page draws it as dots; after the answer the same field must still have focus and be empty. The code is filled once into that element (a field split into one box per character is refused), never retried, and never stored, logged, shown to a model or drawn on screen. No source, a late or malformed answer, a decline, a field that changed, or a backend that can't bind the field stops the step before typing with a closed `second_factor_*` code; an older runtime refuses the bundle. Over the control plane the code is sealed in the person's browser to a one-step key the control plane can't open. The wrap recorder finds a code field from `autocomplete="one-time-code"` alone; it doesn't detect push approvals, and only the local browser backend can take a code | In PR | Synthetic (a notes app with an authenticator page in headless Chromium through the real wrap path: first run, canary, admission, publish staging, a cached run and a declined run, with a byte scan for the TOTP secret and recent codes; headless-browser tests that two codes render the same pixels and that a focus change, a prefilled field or an auto-submitting page are handled; unit tests for every source, late answers, the step shape and every refusal; pty tests that a terminal prompt hides the code, restores echo after a timeout and answers the next prompt; the Windows console reader's deadline and discard logic on a fake keyboard). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, `openadapt_flow.runtime.second_factor_step`, [SECOND_FACTOR.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/test_second_factor_browser.py`, `packages/flow/tests/test_second_factor_terminal.py`, `packages/flow/tests/test_second_factor_console.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AGENT_FRAMEWORKS.md) | @@ -849,8 +850,8 @@ improvising or retrying when something is off. | Each package installs on its own within a size budget, checked in CI (privacy without desktop, capture without plotting) | Released ([#1270](https://github.com/OpenAdaptAI/OpenAdapt/pull/1270), [#1271](https://github.com/OpenAdaptAI/OpenAdapt/pull/1271), [#1279](https://github.com/OpenAdaptAI/OpenAdapt/pull/1279)) | CI | `.github/workflows/packages.yml` | | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | -| Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | -| Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | +| Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` authenticates the set's header, then destroys its tracked bucket-key copies, in the archive the set was written to (an archive counts only with its marker file), and the run's checkpoints, which are keyed from the run's own data key. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred, unmounted and moved archive, whole-set substitution, backlog race and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECEIPTS.md); [vectors](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | @@ -965,6 +966,7 @@ A test fails when a command has no file or this list is out of date. **Run on premises:** +- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, `restore` for a backup only the recovery code opens, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. - `no-outbound` - `service` @@ -2426,6 +2428,14 @@ postconditions, model requests, effect queries, logs, and reports. Keep those observations inside the declared execution boundary and apply storage, retention, access, and egress controls there. +Encryption at rest is on by default: recordings, bundles and run +directories (screenshots, frames, typed values, reports) are ciphertext on +disk, each under its own data key, wrapped through a per-set bucket key to +this computer's device key and, in organization mode, the organization's key +([`phi_at_rest.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md)). It protects +files at rest, not a running session: anyone who can run commands as the +signed-in person can read them, as Flow does. + See [`SANITIZED_ARTIFACTS.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SANITIZED_ARTIFACTS.md) for the review and exact-hash workflow, [`PRIVACY.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/PRIVACY.md) for the field-level data map, and [`ENTERPRISE_ARCHITECTURE.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ENTERPRISE_ARCHITECTURE.md) for component @@ -2450,13 +2460,19 @@ host hardening, storage encryption, backups, retention, access control, monitoring, effect-verifier integration, update validation, and disaster recovery. -The repository supplies integrity manifests, optional encryption at rest for -bundles, web recordings and the run directories of sealed bundles, destination -policy, local egress checks, and audit primitives. Encryption at rest does not -cover data in process memory, the target application's own storage, file names -and sizes, desktop recordings, or commands outside the list in -[`phi_at_rest.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md), which refuse sealed input; the key is a -passphrase in the environment, not a KMS. A content digest +The repository supplies integrity manifests, encryption at rest by default +for recordings, bundles and run directories, destination policy, local egress +checks, and audit primitives. Encryption at rest does not cover data in +process memory, the target application's own storage, file names and sizes, a +desktop recording's raw capture session while it records, cross-window +(`record --surface`) recordings, the receipt page, the logged artifacts in +[`phi_at_rest.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md), or commands outside its list, which refuse +sealed input. Without an organization policy only this computer's device key +(and a recovery key, if made) opens what it wrote. The device key is a +software key in the OS keychain (or a 0600 file where there is none) until the +Secure Enclave and TPM providers are built: code running as the signed-in +person can use it. Losing it loses the data unless an organization policy or a +recovery key exists. A content digest proves byte identity, not publisher identity. A local hash chain is tamper evident against ordinary changes, not tamper proof against an administrator who can rewrite it. Local approvals record provenance but are not enterprise-IdP diff --git a/packages/flow/tests/conftest.py b/packages/flow/tests/conftest.py index d87018ce25..131ab40e96 100644 --- a/packages/flow/tests/conftest.py +++ b/packages/flow/tests/conftest.py @@ -45,20 +45,19 @@ def _skip_default_at_rest(items: list[pytest.Item]) -> None: is `` | ``; a prefix may name a whole file.""" if not _DEFAULT_AT_REST_SKIPS.is_file(): return - rules: list[tuple[str, str]] = [] + rules: dict[str, str] = {} for line in _DEFAULT_AT_REST_SKIPS.read_text(encoding="utf-8").splitlines(): if not line.strip() or line.startswith("#"): continue prefix, _, reason = line.partition(" | ") - rules.append((prefix.strip(), reason.strip())) + rules[prefix.strip()] = reason.strip() for item in items: - nodeid = item.nodeid.removeprefix("packages/flow/") - for prefix, reason in rules: - if ( - nodeid == prefix - or nodeid.startswith(prefix + "::") - or (prefix.endswith(".py") and nodeid.startswith(prefix)) - ): + nodeid = item.nodeid.removeprefix("packages/flow/").split("[", 1)[0] + parts = nodeid.split("::") + # The test itself, its class, or its whole file. + for depth in range(len(parts), 0, -1): + reason = rules.get("::".join(parts[:depth])) + if reason is not None: item.add_marker(pytest.mark.skip(reason=f"default at rest: {reason}")) break From a4f8e5ebf84f10ab36bac84391bc6595b99209a1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 03:51:07 -0500 Subject: [PATCH 36/37] test(flow): track tests/default_at_rest_skips.txt (*.txt is ignored) --- packages/flow/tests/default_at_rest_skips.txt | 303 ++++++++++++++++++ 1 file changed, 303 insertions(+) create mode 100644 packages/flow/tests/default_at_rest_skips.txt diff --git a/packages/flow/tests/default_at_rest_skips.txt b/packages/flow/tests/default_at_rest_skips.txt new file mode 100644 index 0000000000..0f94f394ea --- /dev/null +++ b/packages/flow/tests/default_at_rest_skips.txt @@ -0,0 +1,303 @@ +# Tests skipped under OPENADAPT_TEST_DEFAULT_AT_REST=1 (#2423 triage). +# | . Group (a): the test reads or plants plaintext and the +# product correctly refuses. Group (b, open): a known product limitation. + +tests/test_admit_pipeline.py::test_a_decision_file_written_without_the_admission_key_admits_nothing | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_admit_pipeline.py::test_a_signed_decision_edited_afterwards_admits_nothing | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_admit_pipeline.py::test_an_agent_admission_stops_applying_when_its_grant_does | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_admit_pipeline.py::test_person_accept_applies_checks_and_records_who_decided | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_after_stop_mockmed.py::test_a_stale_unused_approval_can_be_replaced_but_a_used_one_cannot | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_after_stop_mockmed.py::test_halt_after_an_earlier_write_lists_that_write_as_confirmed | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_after_stop_mockmed.py::test_no_undo_is_offered_for_a_run_with_loop_iterations | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_after_stop_mockmed.py::test_undo_is_not_offered_for_a_finished_run_or_an_absent_change | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_after_stop_mockmed.py::test_undo_never_runs_without_approval | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_annotate.py::test_annotate_on_attaches_proposals_and_applies_safe_upgrade | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_api_step_readback_repair.py::test_a_durable_api_save_without_an_encrypted_store_reads_back_inline | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_api_step_readback_repair.py::test_an_api_save_reads_back_while_the_next_item_runs | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_approval_mode_each_item.py::test_a_phone_decline_after_the_wait_ends_the_pause | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_approval_mode_each_item.py::test_continue_and_a_generic_approve_cant_answer_an_item_approval | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_approval_mode_each_item.py::test_resume_carries_only_a_persons_approval | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_approval_mode_replayer.py::test_without_a_gate_the_report_is_unchanged | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_approved_repair_bridge.py::test_adoption_still_refuses_missing_wrong_or_duplicate_current_record | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_approved_repair_bridge.py::test_canary_inputs_are_fresh_and_match_existing_budget | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_approved_repair_bridge.py::test_candidate_reference_refuses_before_any_canary | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_approved_repair_bridge.py::test_every_canary_requires_its_own_current_report_join | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_approved_repair_bridge.py::test_first_failed_or_cancelled_canary_stays_held_and_is_not_retried | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_approved_repair_bridge.py::test_invalid_or_consumed_repair_never_runs_canary | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_approved_repair_bridge.py::test_normal_signed_repair_canaries_promote_and_select_without_agent | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_approved_repair_bridge.py::test_programmatic_teach_authority_root_is_used_without_ambient_pin | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_artifact_reads.py::test_strict_library_mismatch_refusal_never_prints_the_skill_id | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_artifact_reads.py::test_strict_teach_success_never_prints_a_name_from_its_input | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_artifact_reads.py::test_teach_in_strict_mode_seals_plain_inputs_outputs | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_artifact_reads.py::test_teach_never_writes_over_the_sealed_base | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_artifact_reads.py::test_teach_reads_sealed_inputs_and_writes_sealed | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_artifact_reads.py::test_teach_refusal_on_a_sealed_run_never_prints_its_contents | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_artifact_reads.py::test_teach_refuses_a_plaintext_library_for_sealed_input | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_artifact_reads.py::test_teach_refuses_an_out_that_is_another_input | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_artifact_reads.py::test_teach_success_on_plain_input_names_its_skill | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_actions.py::test_continue_that_halts_later_rotates_to_the_new_exact_pause | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_actions.py::test_crash_after_delivery_started_becomes_uncertain_and_never_retries | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_actions.py::test_durable_halt_automatically_captures_protected_transition_baseline | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_actions.py::test_program_continue_commits_exact_receipt_without_reactuating_source | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_actions.py::test_repeated_halt_on_same_step_gets_a_new_exact_pause_capability | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_actions.py::test_tampered_capability_and_stale_page_refuse | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_actions.py::test_transition_baseline_is_keyed_signed_and_contains_no_raw_phi | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_at_rest.py::test_older_plaintext_attended_run_still_resumes | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_qualification_environment.py::test_attended_qualification_resume_keeps_target_and_rechecks_live_surface | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_attended_source_identity_v13.py::test_missing_historical_program_capability_refuses | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_authoring.py::test_agent_demonstration_is_marked_agent_authored | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_agent_pointer_and_chord_steps_are_recorded | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_continue_does_not_invoke_backend_type_text | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_continue_reads_pause_target_not_a_later_focus_point | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_continue_uses_playwright_input_value_when_text_value_at_missing | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_empty_readable_secret_field_stays_paused | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_masked_empty_secret_records_when_operator_confirms | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_non_secret_empty_field_stays_paused | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_person_pause_input_is_marked_person | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_rdp_recording_stamps_window_hints | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_scripted_actuate_records_events_and_frames | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_authoring.py::test_secret_continue_persists_no_text_and_skips_type_text | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_auto_repair_cli.py::test_a_run_that_cannot_be_repaired_runs_plainly | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_auto_repair_cli.py::test_no_auto_repair_leaves_the_stop_for_a_person | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_browser_attach.py::test_launched_recording_withholds_a_later_document_url_after_a_get_submit | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_browser_attach.py::test_launched_recording_withholds_a_redirect_that_puts_the_value_in_a_path | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_browser_selection.py::test_recorder_refuses_real_native_default_as_a_demonstrated_choice | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_business_decision.py::test_obsolete_operational_capability_is_archived_not_exposed | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_choice_widgets_e2e.py::test_calendar_effects_need_explicit_fixture_risk_review | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_choice_widgets_e2e.py::test_search_folding_links_come_from_the_actual_input_owner | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_choice_widgets_e2e.py::test_the_persons_own_dialog_answer_is_recorded | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compile_identifier_crop.py::test_action_scoped_identifier_region_produces_movable_visual_target | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compile_identifier_crop.py::test_encrypted_save_seals_the_identifier_crop | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compile_identifier_crop.py::test_event_marked_region_wins_and_forces_crop_despite_structured | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compile_identifier_crop.py::test_pixel_only_recording_emits_identifier_crop | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compile_postcondition_ownership.py::test_compilation_preserves_postcondition_owner | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compiler.py::TestCompileRecording::test_bundle_roundtrip | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compiler.py::TestCompileRecording::test_click_template_cropped_correctly | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compiler.py::TestCompileRecording::test_codegen_parses | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compiler.py::TestCompileRecording::test_double_click_event_compiles | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compiler.py::TestCompileRecording::test_layout_fingerprints_are_stored_for_click_steps | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compiler.py::TestCompileRecording::test_region_stable_carries_expected_content_template | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compiler.py::TestCompileRecording::test_scroll_event_compiles | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compiler.py::TestParamRegionHygiene::test_compiled_bundle_records_the_dropped_postcondition | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_compiler.py::test_native_select_compile_preserves_gesture_checks_and_source_aliases | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_console.py::test_adversarial_labels_urls_mrns_and_paths_are_redacted | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_console.py::test_attended_console_owns_one_backend_and_closes_it | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_console.py::test_attended_web_playwright_lifecycle_stays_on_owner_thread | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_console.py::test_attention_preserves_typed_effect_category_over_incidental_marker | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_console.py::test_public_attention_resolver_is_current_bounded_and_symlink_safe | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_console.py::test_run_detail_pause_checkpoints_manifest | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_console.py::test_symlinked_pause_never_enters_attention_queue_or_leaks | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_console.py::test_symlinked_run_metadata_is_never_read | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_credential_capture_capability.py::test_explicit_person_secret_handoff_needs_no_automatic_credential_seam | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_decision_supervisor.py::test_a_decision_is_executed_against_the_pause_it_was_minted_from | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_a_governed_refusal_is_acknowledged_and_re_raised | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_a_lost_ack_survives_restart_without_a_second_action | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_a_reject_from_a_phone_ends_the_right_run | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_a_run_that_is_not_durably_paused_is_never_published | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_an_accepted_pause_is_not_republished_every_cycle | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_an_open_pause_is_published_without_anyone_calling_anything | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_an_uncertain_pause_is_republished_because_the_post_is_idempotent | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_an_uncertain_publish_is_reported_as_unknown_never_as_reachable | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_confirm_and_append_are_serialized_without_a_lost_write | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_every_open_pause_is_published_not_only_the_first | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_lost_ack_recovery_refuses_a_changed_signed_or_idempotency_binding | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_no_waiting_decision_is_a_quiet_cycle_not_an_error | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_one_cycle_publishes_executes_and_acknowledges_without_a_caller | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_one_refused_pause_does_not_silence_the_others | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_recovery_refuses_a_journal_moved_to_another_run | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_recovery_refuses_a_replaced_per_run_key | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_recovery_refuses_when_the_signed_capability_is_missing | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_recovery_restores_a_damaged_or_missing_local_ack_projection | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_recovery_restores_an_outcome_and_plain_digest_changed_together | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_recovery_restores_over_a_fabricated_accepted_outcome | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_recovery_restores_over_a_locally_resigned_run_or_pause_binding | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_relay_ack_record_contains_only_closed_or_opaque_context | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_decision_supervisor.py::test_v1_unicode_lost_ack_replays_from_external_authority | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_deferred_report.py::test_through_the_replayer_and_the_cli | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_desktop_record.py::test_orchestration_captures_then_converts | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_desktop_record.py::test_orchestration_stamps_exact_citrix_replay_binding | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_desktop_record.py::test_orchestration_stamps_identifier_region_into_meta | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_desktop_record.py::test_orchestration_uses_explicit_capture_dir | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_desktop_recorder.py::test_record_desktop_demo_arms_structural_per_click | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_dom_identity.py::test_recorder_captures_structured_identity_on_click | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_dom_identity.py::test_recorder_pixel_backend_omits_structured_identity | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_durable_authority_v13.py::test_crash_after_external_append_repairs_missing_local_projection | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_durable_authority_v13.py::test_deleted_local_attended_projection_is_repaired_from_authority | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_durable_authority_v13.py::test_local_attended_journal_rollback_is_repaired_from_authority | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_durable_program.py::test_program_loop_keeps_each_action_frame_across_checkpoints | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_durable_program.py::test_program_resume_restores_interpreter_and_completes | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_effect_mining.py::test_compile_attaches_mined_effects_when_opted_in | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_egress_guard.py::test_egress_optin_flagged_in_report | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_empty_result_guard.py::test_a_dialog_without_a_mined_check_is_noted | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_empty_result_guard.py::test_compiling_the_openemr_recording_mines_the_no_match_checks | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_encryption_at_rest.py::test_bundle_load_without_key_fails_loudly | the test checks a passphrase or a plaintext default against a version 3 set, which opens with recipient keys +tests/test_encryption_at_rest.py::test_checkpoint_missing_key_fails_loudly | the test checks a passphrase or a plaintext default against a version 3 set, which opens with recipient keys +tests/test_encryption_at_rest.py::test_checkpoint_unencrypted_default_unchanged | the test checks a passphrase or a plaintext default against a version 3 set, which opens with recipient keys +tests/test_encryption_at_rest.py::test_crypto_missing_key_fails_loudly | the test checks a passphrase or a plaintext default against a version 3 set, which opens with recipient keys +tests/test_execution_profiles.py::test_cli_replayer_refuses_missing_required_checkpoint_key_before_build | the test checks a passphrase or a plaintext default against a version 3 set, which opens with recipient keys +tests/test_execution_profiles.py::test_replayer_rechecks_checkpoint_encryption_before_backend_access | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_execution_profiles.py::test_standard_direct_legacy_checkpoint_resume_is_refused | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_field_label_params.py::TestCompileFieldLabel::test_field_label_lands_on_step_and_sidecar | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_field_label_params.py::TestConfirmPass::test_cli_no_channel_keeps_constants | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_field_label_params.py::TestRecorderFieldLabelCapture::test_label_captured_on_type_event | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_field_label_params.py::TestRecorderFieldLabelCapture::test_no_seam_and_failure_are_silent | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_focus_on_postcondition.py::test_the_recorder_keeps_the_focus_around_a_key | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_governed_authorization.py::test_governed_drift_stages_repair_without_mutating_authorized_workflow | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_governed_healing.py::test_e2e_benign_drift_heals_and_promotes | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_governed_healing.py::test_e2e_unarmed_step_still_heals_without_governance_halt | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_governed_healing.py::test_e2e_weakening_heal_is_blocked_and_run_halts | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_handoff_receipts.py::test_a_broken_chain_is_refused | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_handoff_receipts.py::test_a_real_run_writes_a_receipt_that_carries_the_claims_line | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_handoff_receipts.py::test_follow_ups_record_each_change_and_verify_as_a_chain | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_handoff_receipts.py::test_handoff_list_signs_updates_and_shows_the_history | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_handoff_receipts.py::test_sign_updates_refuses_a_receipt_it_cannot_verify_or_did_not_sign | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_heal.py::test_heal_artifacts_persisted_under_run_dir | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_hover_evidence.py::test_recorder_saves_a_hover_frame_before_the_click | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_deferred_document_cdp.py::test_first_action_in_a_new_document_needs_no_prior_owner | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_deferred_document_cdp.py::test_known_navigation_keeps_first_action_and_later_document_action | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_deferred_document_cdp.py::test_same_document_deferred_actions_keep_one_recorded_step | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder.py::test_a_parameters_type_event_carries_its_field_rect | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder.py::test_identifier_field_marking_records_region_and_compiles_crop | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder.py::test_secret_auto_detected_and_never_persisted | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder.py::test_secret_field_region_redacted_in_frames | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder_frames.py::test_frame_events_name_their_frame_chain | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder_frames.py::test_frame_events_record_page_space_points | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder_frames.py::test_frame_field_rect_is_page_space | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder_gestures.py::test_a_native_select_change_is_recorded_as_a_choice | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder_gestures.py::test_checkbox_records_click_without_phantom_type | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_interactive_recorder_gestures.py::test_single_click_survives_the_double_click_hold | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_jit_draft_execution.py::test_the_replayer_refuses_a_draft_and_its_copy | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_jit_fail_closed.py::test_deleting_the_draft_marker_does_not_free_a_draft | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_mobile_attended_decision_e2e.py::test_a_pre_admission_refusal_is_not_a_receipt | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_a_rejected_run_cannot_be_resumed_or_answered_again | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_a_task_that_becomes_stale_while_open_refuses | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_action_outside_allowed_actions_refuses | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_cloud_safe_schema_rejects_evidence_free_text_and_unknown_fields | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_console_route_emits_exactly_the_documented_receipt_contract | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_expired_decision_refuses_before_actuation | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_forged_task_signature_or_capability_refuses_before_actuation | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_halt_to_mobile_task_to_verified_continue_returns_a_terminal_receipt | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_live_state_changing_after_the_displayed_frame_refuses | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_no_notification_contains_protected_content | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_protected_evidence_is_authorization_scoped_no_store_and_bounded | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_reject_is_withheld_where_a_write_may_already_have_landed | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_reject_terminates_the_run_and_the_run_report_says_so | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_rejecting_a_run_that_already_wrote_stays_reconciliation_required | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_same_key_replays_the_receipt_and_a_different_payload_refuses | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_two_operators_cannot_both_decide_the_same_task | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_uncertain_delivery_is_reported_as_uncertain_and_survives_a_fresh_key | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_verified_is_impossible_without_the_complete_contract | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_mobile_attended_decision_e2e.py::test_wrong_pause_and_wrong_bundle_refuse_before_actuation | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_multi_surface_dialog.py::test_the_dialog_answer_is_compiled_onto_the_step_that_raises_it | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_multi_surface_e2e.py::test_recorded_surfaces_keep_no_query_string_or_title | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_multi_surface_governed.py::test_governed_durable_multi_surface_run_reaches_verified | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_multi_surface_governed.py::test_single_surface_results_carry_no_surface_record | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_multi_surface_record.py::test_without_a_terminal_the_recording_is_kept_unconfirmed_and_compile_refuses | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_native_focus_keyboard.py::test_recorder_declines_a_focus_observation_that_cannot_be_frozen | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_native_focus_keyboard.py::test_recorder_freezes_input_focus_even_when_after_focus_is_unavailable | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_native_keyboard_retry.py::test_report_retains_actual_keyboard_attempt_frame_even_with_lost_ack | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_phi_governance.py::test_scrub_drops_identifier_landmark_when_active | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_pixel_scale_replay.py::test_font_change_with_the_layout_unchanged_still_halts | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_pixel_scale_replay.py::test_opting_out_keeps_the_first_step_halt | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_pixel_scale_replay.py::test_record_switch_during_typed_readback_halts_without_retry | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_pixel_scale_replay.py::test_scale_change_during_the_run_halts | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_pixel_scale_replay.py::test_unconfirmable_identity_at_a_new_scale_halts | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_pixel_scale_replay.py::test_wrong_record_at_a_new_scale_still_halts_before_the_write | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_probe_induction.py::test_cli_probe_on_declared_test_copy_certifies_and_logs | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_probe_induction.py::test_probing_a_non_test_target_is_refused | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_program_ir_phase2.py::test_loop_report_shows_per_row_bound_values_not_recorded_default | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_program_ir_phase2.py::test_loop_report_shows_rows_supplied_at_run_time | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_program_sections.py::test_compile_writes_sections_from_the_recorded_form | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_program_transition_evidence.py::test_runtime_retains_exact_ordered_visual_transition_evidence | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_drag_fault_target_halts_before_unreached_endpoint_resolution | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_exact_qualification_accepts_runtime_effect_fault_artifacts | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_fault_target_requires_runtime_emittable_visual_resolution | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_native_selection_receipt_binds_value_commit_and_target | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_prior_drag_requires_exact_compiled_endpoint_resolution | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_prior_fault_prefix_action_requires_exact_qualification_evidence | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_prior_remote_pointer_receipt_binds_exact_fault_prefix | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_prior_right_click_accepts_only_the_runtime_guarded_receipt | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_prior_selection_receipt_binds_value_commit_and_target | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_read_only_prior_remote_click_has_exact_fault_prefix_proof | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_real_pixel_wrong_identity_retains_exact_fault_evidence | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_qualification_fault_contract.py::test_stale_identity_integrity_accepts_both_runtime_emittable_shapes | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_readback_pipeline.py::test_confirmed_readback_settles_the_saved_report | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_readback_pipeline.py::test_pending_report_is_not_saved_as_success | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_readback_pipeline.py::test_refuted_readback_halts_the_item_after_the_fact | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_dialog_records_nonrow_evidence_without_structured_identity | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_can_capture_a_separate_read_only_effect_observer | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_cancels_native_selection_on_input_failure | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_cancels_native_selection_on_intervening_action | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_captures_structural_state_when_backend_exposes_it | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_native_choice_accepts_exact_label_or_unique_enabled_prefix | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_native_selection_keeps_prefix_and_committed_evidence | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_native_selection_rejects_parameters_and_incomplete_readback | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_native_selection_requires_changed_choice_and_typed_match | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_native_selection_requires_retained_preclick_target | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_omits_structural_keys_on_plain_backend | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_scroll_event | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_settle_timeout_on_unstable_screen | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_recorder.py::test_recorder_writes_recording_format | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_remote_display_backend.py::test_agent_drives_remote_session_recording_from_pixels | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_replayer.py::test_a_re_render_that_settles_on_the_target_verifies_once | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_replayer.py::test_happy_path_click_then_param_type | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_replayer.py::test_semantic_drift_aborts_run_with_named_step | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_run_invocation.py::test_common_report_producer_carries_context_before_persistence | the test checks a passphrase or a plaintext default against a version 3 set, which opens with recipient keys +tests/test_runner_client_lib.py::TestCommandMapping::test_managed_replayer_refuses_public_state_mutation_before_run | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_runtime_control_overlay.py::test_replayer_emits_linear_phases_and_exact_persisted_terminal | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_runtime_validation.py::test_attestation_refuses_completed_unverified_as_runtime_evidence | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_runtime_validation.py::test_attestation_refuses_report_without_resolved_target_kind | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_runtime_validation.py::test_bundle_approval_failure_names_the_bundle_flag | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_runtime_validation.py::test_failed_or_wrong_workflow_report_cannot_attest | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_runtime_validation.py::test_report_from_a_different_browser_origin_cannot_attest | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_sanitized_artifact.py::test_compiled_template_bundle_preserves_exact_verified_image_bytes | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_sanitized_artifact.py::test_parameterized_sanitized_recording_compiles_and_injects_runtime_value | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_second_factor.py::test_recording_types_the_persons_code_and_keeps_only_the_param | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_secret_params.py::test_compiler_carries_secret_without_value | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_secret_params.py::test_credential_proposal_is_flagged_secret_without_example | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_secret_params.py::test_recorder_non_secret_param_keeps_value | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_secret_params.py::test_recorder_secret_not_persisted_and_region_redacted | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_self_repair.py::test_healthy_run_never_calls_the_agent | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_server_responses.py::test_a_201_from_the_server_never_makes_the_run_verified | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_standard_change.py::test_a_changed_file_of_another_step_goes_to_a_person | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_standard_change.py::test_a_changed_save_template_goes_to_a_person | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_standard_change.py::test_a_class_the_policy_does_not_allow_goes_to_a_person | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_standard_change.py::test_a_relabel_is_a_standard_change | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_standard_change.py::test_a_relabel_onto_an_unclear_or_risky_control_goes_to_a_person | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_standard_change.py::test_an_unsigned_expired_or_foreign_policy_refuses | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_standard_change.py::test_changes_to_the_save_go_to_a_person | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_standard_change.py::test_revert_from_the_phone_portal | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_standard_change.py::test_the_rules_are_the_same_on_non_web_bundles | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should +tests/test_state_dependency.py::test_known_interstitial_dismissed_by_key_then_step_runs | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_structural_rung.py::test_recorder_captures_structural_locator | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_teach_branch.py::test_cli_teach_branch | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_cli.py::test_teach_keeps_using_a_library_that_descends_from_the_bundle | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_cli.py::test_teach_refuses_a_fix_without_a_real_on_screen_target | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_cli.py::test_teach_rejects_a_halt_the_bundle_does_not_contain | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_cli.py::test_teach_rejects_run_bundle_mismatch_without_writes | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_cli.py::test_teach_rejects_stale_library_for_different_bundle | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_cli.py::test_teach_resolves_modal_once_via_correction_spec | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_cli.py::test_teach_resolves_modal_once_via_recording | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_cli.py::test_teach_reuses_a_library_seeded_from_the_same_bundle | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_placement.py::test_the_refusal_names_the_double_write | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_teach_placement.py::test_the_spliced_step_carries_the_recorded_target | known limitation (b, open): attended approvals, attended drafts, business-decision states and teach on encrypted input are refused in an encrypted run; follow-up seals those stores +tests/test_transaction_outcome.py::test_ledger_projection_failure_keeps_report_and_suppresses_replay | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_tx_request_index.py::test_candidate_metadata_cannot_rescope_same_request_or_authorize_another_target | the test shares state across tests through the at-rest home, which the default-mode session keeps per worker +tests/test_tx_request_index.py::test_default_namespace_never_silently_abandons_legacy_lens_scopes | the test shares state across tests through the at-rest home, which the default-mode session keeps per worker +tests/test_ui_dismiss_and_latency.py::test_a_bare_hash_link_is_not_a_route_change | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_ui_dismiss_and_latency.py::test_a_click_that_starts_nothing_settles_at_once | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_ui_dismiss_and_latency.py::test_a_late_screen_after_a_route_change_is_waited_for | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_ui_dismiss_and_latency.py::test_a_page_busy_before_the_action_does_not_extend_the_wait | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_ui_dismiss_and_latency.py::test_a_request_in_flight_is_waited_for | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_ui_dismiss_and_latency.py::test_a_small_change_the_phash_misses_is_not_the_old_screen | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_ui_dismiss_and_latency.py::test_page_activity_alone_waits_less_than_a_route_change | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_ui_dismiss_and_latency.py::test_the_wait_is_bounded_and_keeps_the_old_frame_on_timeout | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_ui_dismiss_and_latency.py::test_without_the_wait_the_old_screen_is_kept | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_uia_focused_field_label_contract.py::test_real_recorder_and_compiler_keep_related_label_passively | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_undo_proposal.py::test_network_undo_is_verified_written_as_a_proposal_and_waits_for_a_person | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_variant_router.py::test_routed_variant_runs_through_the_replayer_and_its_report_names_it | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_windows_backend.py::test_agent_drives_authoring_recording_over_windows_backend | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_wrap_sign_in.py::test_each_field_is_black_in_every_frame_that_still_shows_it | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_wrap_sign_in.py::test_recordings_that_did_not_opt_in_keep_their_own_handling | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_wrap_sign_in.py::test_the_password_and_its_username_are_recorded_by_name_only | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) +tests/test_wrap_sign_in_browser.py::test_password_candidate_rendering_cannot_expose_the_recorded_username | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) From b3328e0ef3159229cd2ced0b835fb4eb777108ce Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 04:12:47 -0500 Subject: [PATCH 37/37] ci: the default-at-rest shards leave the wall-clock bound to flow core unit --- .github/workflows/packages.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 514d3abc46..54e485ac43 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -834,7 +834,10 @@ jobs: set -uo pipefail mkdir -p runs mapfile -t files < "$RUNNER_TEMP/shard.txt" + # The wall-clock bound needs an uncontended worker; flow core unit + # runs it alone, so it is not repeated here. pytest -n logical --dist loadfile -q -rfE --timeout 300 \ + --deselect=tests/test_tx_acid_servers.py::test_50k_seed_speed_and_8_worker_background_concurrency \ --basetemp=runs/ci-default \ --junitxml=runs/flow-default-at-rest-${{ matrix.shard }}.xml "${files[@]}" - name: Upload the default-mode results