diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 8803a83408..54e485ac43 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -672,6 +672,182 @@ jobs: openadapt_flow/compiler/induction.py \ openadapt_flow/compiler/loop_authoring.py + flow-default-at-rest: + # 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 + # 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 + 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" + # 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 + 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 @@ -882,6 +1058,33 @@ 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" + # 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 @@ -1899,6 +2102,7 @@ jobs: - verify-clean-install - flow-lint - flow-unit + - flow-default-at-rest - flow-critical - flow-onprem-offline - flow-agent-frameworks @@ -1956,6 +2160,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", @@ -1990,7 +2195,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 0694f95760..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) | @@ -378,8 +379,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 +495,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/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 ce6569dcc8..4d03e41523 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -93e2f3c7e6f63fe1c2bc96a55ee62c99a582690971839a0e84e250ce01d421da +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/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 4e923f1586..57a6303500 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/openadapt/quickstart/engine.py b/openadapt/quickstart/engine.py index 6fe2add29a..266f37684a 100644 --- a/openadapt/quickstart/engine.py +++ b/openadapt/quickstart/engine.py @@ -228,12 +228,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 @@ -382,7 +385,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) @@ -402,12 +405,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.""" @@ -827,7 +842,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, @@ -917,8 +932,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 c5c5c7b1ba..e5a1161f2a 100644 --- a/openadapt/quickstart/images.py +++ b/openadapt/quickstart/images.py @@ -154,9 +154,11 @@ def terminal_answers(protocol: str, *, timeout_s: float = 0.5) -> bool: 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..2670fbb1a7 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): @@ -39,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() @@ -53,9 +57,11 @@ 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) + 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) @@ -103,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 @@ -119,6 +129,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 acae595951..0627f2d41a 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) @@ -238,7 +272,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") @@ -301,7 +335,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 own_keys = keys is None @@ -325,6 +359,7 @@ def write_seal_page( own_keys=own_keys, ) 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..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 @@ -198,3 +204,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/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/desktop/tests/conftest.py b/packages/desktop/tests/conftest.py index e8a4208cd3..4c7f000d83 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") # The stop queue also lists Flow's exception registry under # OPENADAPT_HOME; keep a developer's real cards out of every test. monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path_factory.mktemp("openadapt-home"))) diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 53975fd0c6..93b2b178ba 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -17,6 +17,51 @@ ## Unreleased +### 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. +- 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. 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 - A sign-in that asks for a second factor (a code by text message or email, 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." + } +} diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index 92d99d457c..12e12611c4 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -1057,6 +1057,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`](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 @@ -1081,13 +1089,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`](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. 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 f479d8e1ab..6b06e77336 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 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)). 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 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). | | 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..5a3f0741f2 --- /dev/null +++ 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, `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/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index eed6e671c4..fe49f559b3 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -604,6 +604,8 @@ 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 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 | |---|---:| diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index f0fa959e13..db3a96ebb4 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -13,35 +13,51 @@ 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, 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` | | --- | --- | --- | | 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 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 | -| 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. `--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 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; @@ -49,9 +65,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 +78,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 +109,264 @@ files included. It fails if any of them holds plaintext. What stays readable is listed under [What is not encrypted](#what-is-not-encrypted). +## Key hierarchy + +Every new recording, bundle and run directory (sealed-set format version 3) +has three layers of keys: + +``` +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`, 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 | + +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 | +| --- | --- | --- | +| 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. `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 +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 (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, 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 +{ + "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. + 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). 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). 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 + +`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. 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 + +- `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. 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 +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` 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. + +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 + +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 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 +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 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. 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 +recorder, before the first write, is not built yet. + ## 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 +| `OPENADAPT_POLICY` | A policy file, when no machine policy exists. | +| `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). | +| `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. 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. +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 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: 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. @@ -167,7 +415,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 @@ -180,7 +428,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 @@ -240,12 +488,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. @@ -380,17 +633,23 @@ 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. +- 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. ## The identity template is not encryption diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index be64fcce9b..66a046e9be 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 @@ -503,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 @@ -526,17 +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": - 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 + 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): @@ -1496,7 +1481,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( @@ -1806,10 +1791,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 it yet: the desktop recording policy applies. - _recording_encryption_key( + # cannot encrypt a cross-window recording yet: logged (strict refuses). + if _recording_encryption_key( args, surfaces[0].kind if surfaces else host_surface_kind() - ) + ): + _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 (): @@ -1957,6 +1943,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=getattr(args, "_recording_key", None), ) _stamp_recording_surface(out, backend) print(f"Recording written to {out}") @@ -8457,17 +8444,18 @@ 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 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): + report = RunReport.model_validate_json(artifacts.read_text(report_path)) + except (OSError, ValueError): # a SealedSetError is a ValueError print("report-run failed: report.json is unreadable or invalid") return 1 @@ -9802,6 +9790,7 @@ def build_parser() -> argparse.ArgumentParser: "an irreversible step on every run." ), ) + _at_rest_cli.add_no_encrypt(p) p.set_defaults(func=_cmd_compile) p = sub.add_parser( @@ -10319,6 +10308,7 @@ def build_parser() -> argparse.ArgumentParser: _add_browser_session_flags(p) _add_deployment_flags(p, worklist=True) _add_attest_flags(p) + _at_rest_cli.add_no_encrypt(p) p.set_defaults(func=_cmd_replay) p = sub.add_parser( @@ -10586,6 +10576,7 @@ def build_parser() -> argparse.ArgumentParser: ), ) _add_approval_flags(p) + _at_rest_cli.add_no_encrypt(p) p.set_defaults(func=_cmd_run) sa = sub.add_parser( @@ -10614,6 +10605,7 @@ 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) @@ -13596,6 +13588,7 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.cli_undo:_cmd_undo_approve", "openadapt_flow.cli_undo:_cmd_undo_run", } + | _at_rest_cli.SEALED_READY ) @@ -13653,6 +13646,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 ) @@ -13672,6 +13666,7 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.__main__:_cmd_push", "openadapt_flow.__main__:_cmd_seal", } + | _at_rest_cli.READ_ONLY ) @@ -14110,12 +14105,12 @@ 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): + 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 # 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 @@ -14189,52 +14184,53 @@ def main( return 2 from openadapt_flow import at_rest - 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 + with _at_rest_cli.no_encrypt_scope(args, _cmd_record): # this command only + 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 known-ID list may not be used: halt before any step runs. + 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/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/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 fcd09f42a3..14da1c2083 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -2,30 +2,42 @@ 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`. - -* 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. +:mod:`openadapt_flow.sealed_set` and :mod:`openadapt_flow.crypto`, by default +and with no setup. + +* 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 + 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. + +Stdlib only (``keyring`` and ``cryptography`` are imported lazily), so +:mod:`openadapt_flow.crypto` can import it on every load. """ from __future__ import annotations @@ -38,15 +50,30 @@ 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 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-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" +#: 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 +99,42 @@ 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}") + + +@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 (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: """Whether the deployment configured a key (rather than the local one).""" return bool( @@ -174,6 +237,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,11 +364,223 @@ def _read(path: Path) -> str: return text +# -- 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" + ) + failure = result.get("error") + if isinstance(failure, BaseException): + raise KeyStoreUnavailable( + f"the OS keychain refused a {what} ({type(failure).__name__})" + ) from failure + 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()}" + + +#: 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(SOFTWARE_KEY_PREFIX): + return False + try: + raw = base64.urlsafe_b64decode(text[len(SOFTWARE_KEY_PREFIX) :].encode("ascii")) + except (ValueError, UnicodeEncodeError): + return False + return len(raw) == 32 + + +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: + 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 device key ({exc}). Set " + f"OPENADAPT_BUNDLE_KEY, or {HOME_ENV} to a writable private " + "directory. Nothing was written." + ) from exc + + def local_key() -> str: - """Return this machine's at-rest key, creating it on first use.""" + """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_key(path) + return _local_passphrase(path) except OSError as exc: raise LocalKeyError( f"Flow could not create or read its local encryption key at {path} " @@ -312,42 +589,176 @@ def local_key() -> str: ) from exc -def _local_key(path: Path) -> str: +def _local_passphrase(path: Path) -> str: with _lock: 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) + _private_dir(path.parent) 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: + if not _link_new(path, (text + "\n").encode("ascii")): return _read(path) - finally: - tmp.unlink() 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 -#: 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 _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: + from cryptography.hazmat.primitives.asymmetric import ec + + _private_dir(path.parent) + 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": + 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( + "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 _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,6 +778,46 @@ 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 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.""" 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/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/cli_at_rest.py b/packages/flow/openadapt_flow/cli_at_rest.py new file mode 100644 index 0000000000..798592ea48 --- /dev/null +++ b/packages/flow/openadapt_flow/cli_at_rest.py @@ -0,0 +1,317 @@ +"""``openadapt-flow at-rest``: who can open encrypted runs, recovery and shredding. + +- ``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. +- ``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. + +See docs/phi_at_rest.md. +""" + +from __future__ import annotations + +import argparse +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, " + "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 + from openadapt_flow import key_hierarchy as kh + + try: + 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 (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(), **status} + if args.json: + print(json.dumps(status, indent=2, sort_keys=True)) + return 0 + print(f"Encryption at rest: {mode}") + 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 set: deprecated.") + return 0 + + +def _cmd_recovery_create(args: argparse.Namespace) -> int: + from openadapt_flow import key_hierarchy as kh + + 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 + 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 + + +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 + + 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: + record = sealed_set.shred(root) + except sealed_set.SealedSetError as exc: + 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 " + "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 + 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 + + +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. +SEALED_READY: frozenset[str] = frozenset( + { + "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", + } +) +#: 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( + { + "openadapt_flow.cli_at_rest:_cmd_status", + "openadapt_flow.cli_at_rest:_cmd_recovery_create", + "openadapt_flow.cli_at_rest:_cmd_archive", + } +) + + +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 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 + 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: + """``--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 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 + ): + return at_rest.opted_out("--no-encrypt") + return nullcontext() + + +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", + help=( + "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 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( + "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( + "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( + "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", + 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") + s.set_defaults(func=_cmd_shred) 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/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/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index 4f37d944a4..35b959b74d 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", diff --git a/packages/flow/openadapt_flow/compiler/distill.py b/packages/flow/openadapt_flow/compiler/distill.py index 0d00b9c8d6..c70cf658aa 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,39 @@ 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() or "" + ) + 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 +557,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 +599,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/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/crypto.py b/packages/flow/openadapt_flow/crypto.py index 6400120eb3..ede435b4e4 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: @@ -361,6 +363,8 @@ def _container_key( #: 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/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..5c409c4d41 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 @@ -244,6 +247,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 = _POLICY + + def record_desktop_capture( out_dir: Path | str, *, @@ -260,6 +268,7 @@ def record_desktop_capture( recorder_factory: Optional[RecorderFactory] = None, convert: Optional[ConvertFn] = None, stop: Optional[Callable[[], bool]] = None, + encryption_key: Optional[str] | object = POLICY, announce: bool = True, ) -> Path: """Record a live desktop demonstration and convert it to a recording. @@ -337,10 +346,151 @@ def record_desktop_capture( # backstop. _require_capture_extra() + # 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. + 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." + ) + 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 + 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] + except BaseException: + if staging is not None: + 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 + + +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. + + 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, sealed_set + + if at_rest.strict(): + at_rest.unsealed_write("a desktop raw capture session", str(out_dir)) + return sealed_set.new_artifact_key(explicit, "a desktop recording", out_dir) + + +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/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/hosted.py b/packages/flow/openadapt_flow/hosted.py index 4acdd590ba..a9484dc1be 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 @@ -1928,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. @@ -1939,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. @@ -2425,19 +2471,24 @@ 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" ) 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..1526126082 100644 --- a/packages/flow/openadapt_flow/interactive_recorder.py +++ b/packages/flow/openadapt_flow/interactive_recorder.py @@ -95,7 +95,7 @@ PlaywrightBackend, ) from openadapt_flow.ir import StructuralLocator, structural_locator_is_locatable -from openadapt_flow.recorder import Recorder +from openadapt_flow.recorder import POLICY, Recorder from openadapt_flow.section_capture import SECTION_CONTEXT_JS from openadapt_flow.submit_binding import ( OBSERVE_SUBMIT_BINDING_JS, @@ -2334,7 +2334,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 = POLICY, event_clock: Optional[list[float]] = None, ) -> None: self._url = url diff --git a/packages/flow/openadapt_flow/jit/compile_agent.py b/packages/flow/openadapt_flow/jit/compile_agent.py index 94317053fd..b9abf3bd47 100644 --- a/packages/flow/openadapt_flow/jit/compile_agent.py +++ b/packages/flow/openadapt_flow/jit/compile_agent.py @@ -533,8 +533,45 @@ 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 + 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 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.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: + plaintext = getattr(self, "_plaintext", None) + if plaintext is not None: + plaintext.close() + + def _enter_capture(self) -> "Recording": from openadapt_flow.authoring import AuthoringSession from openadapt_flow.backends._owned import close_owned @@ -642,7 +679,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/key_hierarchy.py b/packages/flow/openadapt_flow/key_hierarchy.py new file mode 100644 index 0000000000..68c01247de --- /dev/null +++ b/packages/flow/openadapt_flow/key_hierarchy.py @@ -0,0 +1,1464 @@ +"""Who can open an encrypted run: the key hierarchy behind sealed-set v3. + +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 + 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 threading +import time +from contextlib import contextmanager +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Final, Iterator, 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" +#: ``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" + +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" + + +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] = _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" + + +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.""" + + +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 -------------------------------------------------------------- + + +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_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 importlib + + winreg: Any = importlib.import_module("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).""" + 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 = [] + 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 + 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(raw) + body = data.get("Policy", data) if isinstance(data, dict) else None + return json.loads(body) if isinstance(body, (str, bytes)) else body + 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 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) + 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(): + 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: + 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. 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 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") + 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'") + 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") + 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=_max_unarchived(raw.get("max_unarchived", 50), source), + 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") + 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) + 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)), + } + + +_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 _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. + + Organization mode refuses without its active organization recipient and + 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() + runtime, viewer = _device_for(policy) + 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: dict[str, Any] = { + "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": + 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 + + +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 _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 {location}: only a local or mounted path " + "(file://) is supported yet; s3:// and smb:// are not built." + ) + 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 _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 + 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: + 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 + 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. 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": + 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: + 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): + 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 + raise NoRecipientKey( + f"this computer has no key record for bucket {bucket_id}. Open it as the " + "organization (copy its archive record into " + f"{buckets_dir()} and set {ORG_KEY_FILE_ENV}), or it was shredded." + ) + + +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] = [] + 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) + 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 and not from_header: + 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, 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, + 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 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") + 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 []} + keys, deferred = _candidates(from_header=from_header) + needs_restore = False + for key in keys: + try: + fpr = key.fpr + except KeyHierarchyError: + continue + stanza = stanzas.get(fpr) + if stanza is None: + 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) + 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] + 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( + "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 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" + + +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_root(location) / f"{bucket_id}.json" + if target.is_file(): + target.unlink() + return not os.path.lexists(target) + except (OSError, KeyHierarchyError): + return False + + +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 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, 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. + """ + _record_path(bucket_id) # validates the id + removed: list[str] = [] + 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": records, + "key_archive": key_archive, + "complete": complete, + } + + +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]: + folder = _pending_dir() + return sorted(p.stem for p in folder.glob("*.json")) if folder.is_dir() else [] + + +def _archive_pending_locked() -> tuple[int, int]: + done = failed = 0 + 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")) + 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 _archive_locked(bucket): + done += 1 + else: + failed += 1 + 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]: + 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", + "RecoveryRestoreRequired", + "Policy", + "Recipient", + "SoftwareKey", + "ARCHIVE_MARKER", + "archive", + "archive_pending", + "bucket_lock", + "clear_pending_shred", + "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/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/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/offline_seal.py b/packages/flow/openadapt_flow/offline_seal.py index 7d03054e9d..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", @@ -403,10 +405,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 +479,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 +613,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 +645,34 @@ 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 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 + + 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 +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 path.is_file(): + 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(path.read_bytes()).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/public_seal.py b/packages/flow/openadapt_flow/public_seal.py index f89e0a1e4a..ab55500f4e 100644 --- a/packages/flow/openadapt_flow/public_seal.py +++ b/packages/flow/openadapt_flow/public_seal.py @@ -283,9 +283,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/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/recorder.py b/packages/flow/openadapt_flow/recorder.py index 25771d7386..2f4f19f97e 100644 --- a/packages/flow/openadapt_flow/recorder.py +++ b/packages/flow/openadapt_flow/recorder.py @@ -62,6 +62,7 @@ from PIL import Image, ImageDraw from openadapt_flow import sealed_set as _sealed +from openadapt_flow.at_rest import POLICY from openadapt_flow.backend import ( Backend, PageCloseExpectationBackend, @@ -228,7 +229,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 = POLICY, finalize_on_finish: bool = True, capture_hover: bool = False, event_clock: Optional[list[float]] = None, @@ -273,6 +274,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 = _sealed.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 64b714eb81..92e62feec2 100644 --- a/packages/flow/openadapt_flow/records/run.py +++ b/packages/flow/openadapt_flow/records/run.py @@ -109,8 +109,22 @@ 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 at_rest, sealed_set + + # The values read are record data: encrypted when written beside an + # 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" ) return out diff --git a/packages/flow/openadapt_flow/repair/agent_teach.py b/packages/flow/openadapt_flow/repair/agent_teach.py index 743914220e..d81cf58031 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())) ) @@ -122,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/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.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/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/attended.py b/packages/flow/openadapt_flow/runtime/durable/attended.py index 0117b24da3..ba8cb0cc1f 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 @@ -2328,12 +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" - 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/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 f9ab6757d1..b0663f61f3 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. 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 @@ -504,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: @@ -529,6 +549,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 90ada7c526..b73b1f3141 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,35 @@ 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 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. 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: + 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 +211,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,21 +252,30 @@ 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: - # 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/runtime/durable/resume.py b/packages/flow/openadapt_flow/runtime/durable/resume.py index 683f05a825..9fe0138447 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 + # 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/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/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/openadapt_flow/sealed_set.py b/packages/flow/openadapt_flow/sealed_set.py index 9416f65096..8d54c80163 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,13 +64,18 @@ FORMAT: Final[str] = "openadapt-flow-sealed-set" FORMAT_VERSION: Final[int] = 1 SEALED_SUFFIX: Final[str] = ".enc" +#: 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"} ) 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/" @@ -89,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.""" @@ -194,6 +204,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, ...]] = ( @@ -243,6 +254,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" ), @@ -263,7 +275,36 @@ 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", + "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, + # 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 +406,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 +510,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 +531,188 @@ def _wrapping_aad(header: dict[str, object]) -> bytes: ).encode("utf-8") -def _data_key(header: dict[str, object], passphrase: str) -> bytes: +_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" +_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"}) + + +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._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 + + 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 _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 + + if header.get("shredded"): + raise SealedSetError( + "this encrypted set was shredded: its bucket key was destroyed, so " + "nobody can open it" + ) + 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") + inline = inline if isinstance(inline, dict) else None + try: + 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") + # 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, 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: + raise SealedSetError(str(exc)) from exc + 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") + stanzas = header.get("stanzas") + stanza = next( + ( + s + for s in (stanzas if isinstance(stanzas, list) else []) + 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 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 +748,9 @@ 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]) -> Any: + if header.get("version") == ENVELOPE_VERSION: + return _open_v3(header) return crypto.SetKey(_data_key(header, passphrase)) @@ -658,7 +889,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 +935,94 @@ 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 key hierarchy replaces for new sets).""" + if not passphrase: + return False + from openadapt_flow import at_rest + + return at_rest.explicit_key() or passphrase != at_rest.existing_key() + + +def _new_v3( + kind: str, passphrase: Optional[str] +) -> 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: + policy = kh.load_policy() + if _explicit_passphrase(passphrase) and policy.mode != "org": + return None + bucket = kh.new_bucket(kind, policy) + except kh.KeyHierarchyError as exc: + raise SealedSetError(f"Not writing an encrypted {kind}: {exc}") from exc + 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", + "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, + "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) + + +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, + 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. @@ -718,13 +1037,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._new = False self._hashes: dict[str, str] = {} self._lines: dict[str, list[bytes]] = {} self._lock = threading.RLock() @@ -732,8 +1052,10 @@ 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) 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) @@ -746,6 +1068,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) + created = _new_v3(kind, passphrase) + if created is not None: + self._header, self._key = created[0], created[1] # type: ignore[assignment] + self._new = True + self._write_header() + return + if not passphrase: + raise SealedSetKeyError(missing_key_message(self.root, kind)) salt = crypto.SetKey.new_salt() self._header = { "format": FORMAT, @@ -759,7 +1089,60 @@ def _initialize(self, passphrase: 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 # type: ignore[assignment] + 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) 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 +1177,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: @@ -920,9 +1303,28 @@ 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 = getattr(self._key, "bucket", None) + if bucket is None: + return + 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 + self._new = False + # -- path-based helpers ------------------------------------------------------ # @@ -1014,6 +1416,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)) @@ -1135,6 +1568,33 @@ 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.""" + 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: @@ -1189,8 +1649,230 @@ 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 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 + 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"] + ] + 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.""" + from openadapt_flow import key_hierarchy as kh + + 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 + + +_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: 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)) + with mutation_lock(base): + header = read_header(base) + 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: + 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, + ) + 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) + return _finish_shred(base, header) + + __all__ = [ "BUNDLE_FILES", + "ENVELOPE_VERSION", + "V3Key", + "key_record_of", + "shred", + "store_passphrase", "HEADER", "LIBRARY_FILES", "RECORDING_ENV_KEY", @@ -1199,6 +1881,8 @@ def require_readable(path: Path | str, what: str) -> None: "SealedSet", "SealedSetError", "SealedSetKeyError", + "SealedSetRestoreRequired", + "restore", "SealedSetWriter", "append_line", "classify", 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/openadapt_flow/tutorial.py b/packages/flow/openadapt_flow/tutorial.py index 5b3fdb6014..6f72aac260 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/public-artifacts.json b/packages/flow/public-artifacts.json index a918b66b01..f54224474c 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -564,6 +564,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", diff --git a/packages/flow/pyproject.toml b/packages/flow/pyproject.toml index fb2fe9d33c..415ab90227 100644 --- a/packages/flow/pyproject.toml +++ b/packages/flow/pyproject.toml @@ -95,7 +95,9 @@ 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", + # 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", # 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 @@ -148,6 +150,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 ba5300693f..131ab40e96 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 @@ -25,9 +26,77 @@ 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: 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[prefix.strip()] = reason.strip() + for item in items: + 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 + + +_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: + """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.""" + + 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 = 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( + "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: @@ -62,7 +131,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, @@ -72,9 +147,25 @@ 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_FLOW_AT_REST_HOME": str(root / ".at-rest-home"), + # 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", + # 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). + "OPENADAPT_FLOW_KEY_STORE": "file", + "OPENADAPT_ENCRYPT_AT_REST": None, + "OPENADAPT_POLICY": None, + "OPENADAPT_RECOVERY_CODE": None, + "OPENADAPT_ORG_KEY_FILE": None, } @@ -133,6 +224,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 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) diff --git a/packages/flow/tests/fixtures/cli_surface.json b/packages/flow/tests/fixtures/cli_surface.json index 0f24997a3d..e47752224c 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,13 @@ "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,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", "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 +37,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", @@ -226,7 +233,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", @@ -234,7 +241,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", @@ -330,6 +337,7 @@ "approve": [], "approve-sanitized": [], "approver-grant": [], + "at-rest": [], "attach-seal": [], "bench": [], "benchmark": [], @@ -1208,6 +1216,241 @@ "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": [], + "restore": [], + "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 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": [ + { + "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": [ { @@ -2307,6 +2550,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": {}, @@ -20815,6 +21072,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": {}, @@ -23714,6 +23985,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": {}, diff --git a/packages/flow/tests/test_at_rest_default.py b/packages/flow/tests/test_at_rest_default.py index 2f30410473..9131456691 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" @@ -43,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(): @@ -138,20 +150,21 @@ 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 = _legacy_recording(tmp_path / "rec") # 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( 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") @@ -164,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)) @@ -214,11 +227,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 +258,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 +305,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( @@ -377,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" @@ -390,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( @@ -525,18 +553,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_at_rest_review_round3.py b/packages/flow/tests/test_at_rest_review_round3.py new file mode 100644 index 0000000000..b6be2fdc4b --- /dev/null +++ b/packages/flow/tests/test_at_rest_review_round3.py @@ -0,0 +1,278 @@ +"""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 + + +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 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) 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_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_desktop_record.py b/packages/flow/tests/test_desktop_record.py index 1763cc3a8b..1c560a517d 100644 --- a/packages/flow/tests/test_desktop_record.py +++ b/packages/flow/tests/test_desktop_record.py @@ -1109,3 +1109,196 @@ 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()) + + +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() + + +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_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): 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 new file mode 100644 index 0000000000..1211ce5403 --- /dev/null +++ b/packages/flow/tests/test_key_hierarchy.py @@ -0,0 +1,996 @@ +"""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 _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 + ) + 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, monkeypatch) -> 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" + 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" + 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", + "recipients": [ + { + "role": "org", + "type": kh.RSA_OAEP_3072, + "public_key": base64.b64encode(spki).decode(), + } + ], + "key_archive": str(_make_archive(tmp_path / "archive")), + } + ) + ) + monkeypatch.setenv(kh.POLICY_ENV, str(policy)) + 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( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + 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 + + +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)]) + 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:") + + +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) + # 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 + + +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 + + +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" + ) + + +# -- 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 + _make_archive(blocker) + 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() + _make_archive(blocker) + _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"{}"}) + + +# -- 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) + 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)): + _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() + + +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).key # refused when used + + +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() + + +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_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 ( 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 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 a5956bdbc5..0cac6f61a9 100644 --- a/packages/flow/uv.lock +++ b/packages/flow/uv.lock @@ -68,6 +68,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" @@ -323,6 +332,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" @@ -2840,6 +2857,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" }, ] @@ -2987,7 +3005,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" }, @@ -3062,6 +3080,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" }, @@ -5257,6 +5276,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 f9bfce3b70..c238266d02 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -74,3 +74,8 @@ 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_POLICY", raising=False) + monkeypatch.delenv("OPENADAPT_RECOVERY_CODE", raising=False) 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. diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index 6366c1ada8..f5c6f8e555 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -921,6 +921,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() @@ -930,10 +931,12 @@ 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() + 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): @@ -1169,6 +1172,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( @@ -1189,14 +1194,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