diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 1dcbe2088b..03fcb69103 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -176,6 +176,7 @@ improvising or retrying when something is off. | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | | One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". Run receipts (`record/run/v1`, an additive optional field), `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects; a run receipt says it has no per-read time). A run receipt never says `VERIFIED` below level 3. Receipts without the block still verify. A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | | Grade a file, PDF or email check by who produced it: a file the acting session wrote or downloaded, or one with no declared producer, is at most `same_screen`; one a separate session fetched is at most `separate_session`; only a declared `system_of_record` producer reaches `system_of_record`. A store that overlaps the acting session's folders (named ones, the user's Downloads, a Playwright download folder) is graded as the acting session's whatever is declared. Under a strong declared producer, a scan that reads a file in a browser download folder beneath the store, or a symlink out of it, is refused as INDETERMINATE. The verdict's `read_evidence.provenance` names the producer and whether it was declared or observed | On main | Unit tests through each of the four readers (mixed store, symlink, system-owned positive case); a PDF downloaded by headless Chromium from a loopback app, the same bytes from a separate browser context and from the app's store, and a headless download landing beneath a broader store | `runtime/effects/artifact_provenance.py`, `effects.artifact_producer`, `packages/flow/tests/test_effect_artifact_provenance.py` | +| One strict matcher decides whether text on a screen or page proves a value or a commit: `MATCH`, `MISMATCH` or `AMBIGUOUS`, and only `MATCH` passes. A value must be bound to its label at the start of its field, with nothing but unit words beside it, or be the whole field. A value merely found on the page, inside a longer token (`250` in `$1,250.00`, `John Smith` in `John Smith-Jones`), or under a label with two values never passes. A commit phrase must be new, plainly stated, and not next to a question, a negation or a control label. The launcher's transducer read-back and the kernel's read-back oracles use it; [the migration page](packages/types/docs/evidence-migration.md) lists the callers that don't yet | On main | Adversarial corpus with pinned verdicts, Hypothesis properties, a parity test against Flow's read-back matcher, and strict expected-failure tests for each caller not yet migrated | `openadapt_types/evidence.py`, `openadapt/transducer_obligations.py`, `openadapt_kernel/oracles.py` | | Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | PR [#2500](https://github.com/OpenAdaptAI/OpenAdapt/pull/2500), not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](packages/flow/docs/EFFECT_LOCATION.md) | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](packages/flow/docs/ENSURE_RECORD.md) | @@ -234,6 +235,7 @@ improvising or retrying when something is off. | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](packages/flow/docs/AFTER_A_STOP.md) | | Roll a stopped run back on its own: the approved compensation for each change, latest first, an uncertain write only when a fresh read shows it landed, then a read of the whole database: every row the run touched back as it was and nothing else changed (`ROLLED_BACK`), or the exact rows a person repairs (`RECONCILIATION_REQUIRED`). A compensation runs only while every change in the store is positively the run's own by the app's audit log, so another user's work is never compensated away, and a hard delete runs only where the deployment allows it (void, restore or discard otherwise). `rollback qualify` stops the run before and after every save on a test copy and keeps only compensations that restore the whole store. On a desktop or remote-display backend a screen compensation runs only after the run's and the compensation's start screens are checked on the same backend | On main ([#1634](https://github.com/OpenAdaptAI/OpenAdapt/pull/1634)); desktop in [#1771](https://github.com/OpenAdaptAI/OpenAdapt/pull/1771) | MockMed, live browser through the CLI; SQLite whole-database tests (web and desktop paths) | `openadapt-flow rollback qualify`, `rollback:` in deployment.yaml; [ROLLBACK.md](packages/flow/docs/ROLLBACK.md) | | Leave the screen clean after an item that halted before any write: close dialogs and cancel forms with the recordings' own controls, re-enter, confirm the start screen and read the records back before the session takes another item. A session that doesn't come back is marked dirty and takes no more items; a cleanup that changed a record makes the item's write uncertain and stops the run. `cleanup qualify` tries the cleanup after every step on a test copy and refuses one that changes a record | Released ([#1607](https://github.com/OpenAdaptAI/OpenAdapt/pull/1607)) | Synthetic (scripted three-screen app through the real replayer and pool) and real app (pinned OpenEMR: a halted New Patient item left the confirmation dialog open; re-entry closed it, the form was empty, no patient row changed and the next item's first steps ran with no model calls; a signed-out screen was marked dirty; [results](packages/flow/benchmark/halt_cleanup/results/openemr.json)) | `openadapt-flow cleanup qualify`; [HALT_CLEANUP.md](packages/flow/docs/HALT_CLEANUP.md) | +| Commit-boundary kernel, an optional alpha extra: `pip install 'openadapt[kernel]'` adds `openadapt kernel` (or install `openadapt-kernel` alone for its own command), an experimental runtime with shadow, draft and autopilot modes and signed receipts that does not depend on `openadapt-flow`. `pip install openadapt` leaves it out, and the extra is capped below the next minor version because its API may change before 1.0 | On main | Synthetic (its own suite, headless Chromium tests included, runs in the required `ci` check on every kernel change) | [packages/kernel](packages/kernel/README.md) | ## Approvals @@ -334,6 +336,7 @@ improvising or retrying when something is off. | Self-repair's new clicks outside a browser: on a native app a click is admitted by its accessibility element (role, name, ancestry, window; unique in the pinned window), on pixels only by the record check, and either way only when a system-of-record verifier covers every save under `standard` or `regulated`; the new step carries the dialog around it as a screen pre-check, and only a person approves the fix | On main ([#1709](https://github.com/OpenAdaptAI/OpenAdapt/pull/1709)) | Synthetic, partly live: on OpenAdapt's native Cocoa test app with SQLite, through live macOS AX, the stop, the element identity read, the admission and the refusals without a record check ran with no wrong write; qualified end to end on macOS AX ([#1715](https://github.com/OpenAdaptAI/OpenAdapt/pull/1715)): stop, admitted click, probe, replay and fault campaigns, one approval, resumed run `VERIFIED`; and on its GTK3 counterpart through live Linux AT-SPI, in CI, the same end to end. `run --self-repair` and repair by default start the app for each probe from `repair.session` ([#1717](https://github.com/OpenAdaptAI/OpenAdapt/pull/1717); [benchmark/repair_every_backend](packages/flow/benchmark/repair_every_backend/README.md)) | `openadapt_flow/repair/element_identity.py`, [REPAIR_ON_EVERY_BACKEND.md](packages/flow/docs/REPAIR_ON_EVERY_BACKEND.md) | | Keep pixel-path runs working across display scaling and font smoothing changes | Released ([#1286](https://github.com/OpenAdaptAI/OpenAdapt/pull/1286)) | Synthetic (in-process RDP and canvas renderings: 17 of 24 healthy runs across 100–175%, up from 3; 0 wrong saves) | [benchmark/pixel_scale](packages/flow/benchmark/pixel_scale/README.md) | | Find icons again on Citrix, RDP and VNC after a display-scale, zoom, font, theme or codec change, with a local model that counts look-alikes and stops on a tie (`--local-grounding`, off by default) | Released ([#1596](https://github.com/OpenAdaptAI/OpenAdapt/pull/1596)) | Synthetic (Chromium-drawn clinic screen, pixels only: icons found under 21 of 26 conditions, template matching 8; 0 wrong targets in 65; whole runs unchanged, 4 of 39 in both arms, because the layout, identity and census checks stop first). Held out on real AVC444 RDP frames: 0 wrong picks, 6 right, 75 abstentions in 81 | [benchmark/pixel_grounding](packages/flow/benchmark/pixel_grounding/README.md), `runtime/local_grounder.py` | +| Find an icon-only click target again after a light/dark theme change on Citrix, RDP and VNC, by edge orientation with the sign removed, refusing when another place on the screen scores close, the match is away from the recorded place, or the clicked control itself differs | In a pull request ([#2790](https://github.com/OpenAdaptAI/OpenAdapt/pull/2790)) | Synthetic (Chromium-drawn clinic screen, pixels only, recorded light and replayed dark at 100% and 150%: whole runs 8 of 13 healthy and 7 of 13 reordered, up from 6 and 5; wrong-record runs 13 of 13 stopped; 0 wrong targets or wrong saves) | [benchmark/pixel_grounding](packages/flow/benchmark/pixel_grounding/README.md#whole-runs), `vision/polarity_match.py` | | Pre-approved repairs: a signed policy lists low-risk changes that apply without a person, a test-record run before each queue, and one approval for every item halted the same way | Released ([#1294](https://github.com/OpenAdaptAI/OpenAdapt/pull/1294)) | Synthetic | standard changes | | Repair a pinned bundle: the fix runs the pinned bundle's own qualification campaign on a test copy, keeps every write, effect, identity rule and record check, and is re-admitted with signed lineage (at most three repairs, no revoked key) that the pin verifies | On main | Synthetic | [SELF_REPAIR.md](packages/flow/docs/SELF_REPAIR.md#a-pinned-bundle-re-qualify-and-re-admit) | | Repair by default: once a repair agent is configured (outside a browser, with `repair.session`, [#1717](https://github.com/OpenAdaptAI/OpenAdapt/pull/1717)), every stop that wrote nothing goes to it without anyone starting it; a stop after a possible write goes to reconciliation; every stop is a row in a ledger with the funnel from stop to resumed item | Released ([#1360](https://github.com/OpenAdaptAI/OpenAdapt/pull/1360)) | Synthetic (MockMed, 22 drift modes, real Claude agent: 6 of 21 repairable stops resumed and verified, 0 wrong saves in 66 runs); routing over recorded OpenEMR stops; live openIMIS relabel: 3 of 3 reached repair and stopped with no wrong save; silent-saves 1.1.0 UI-change blocks: 18 of 28 items that always stopped now correct, 0 wrong | `run` (on by default, `--no-auto-repair`), `repair:` in `deploy.yaml`, [benchmark/auto_repair](packages/flow/benchmark/auto_repair/README.md) | @@ -400,12 +403,13 @@ improvising or retrying when something is off. | 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) | | Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | Branch ([#2497](https://github.com/OpenAdaptAI/OpenAdapt/pull/2497)) | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](packages/flow/docs/deployment/ON_PREM_VLM.md) | -| 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) | +| 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; runs on a synthetic app (the tutorial, `replay --demo-app`) are signed with a separate demo key, never this computer's Seal key, so a receiver that pins this computer refuses them (the reference Execute worker's MockMed seals and the seeded reward contract use their own demo keys the same way); 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); tutorial and `replay --demo-app` receipts on headless MockMed checked as demo-signed and refused by this computer's pin; 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) | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](packages/flow/docs/WRITE_RECEIPTS.md) | +| Python `openadapt.wrap` receipts signed with this computer's `openadapt trust init` key by default (or `signing_key=`), naming the key by id and fingerprint; with no key a receipt says `digest_only` and `signed: false`, and `wrap` never creates a key. `verify_wrap_receipt` and `openadapt verify` accept a receipt only when its signature verifies against a key you pinned, never the key the receipt carries; an unknown signer or a digest-only receipt is not verified. A plain `check=` callable is recorded as `caller_check`, and a check can't raise its own `checked_how` | On main | Unit tests with real Ed25519 keys: an unsigned receipt with a recomputed digest and a receipt signed by its own embedded key both fail, through the SDK and `openadapt verify` | `openadapt.wrap`, `openadapt.verify_wrap_receipt`, `openadapt verify FILE [--keys FILE]`, `openadapt trust init` | | Per-run accounting ledger for any executor (an OpenAdapt agent, a compiled program, another agent, a person): one value-free row per run with the outcome (VERIFIED, ESCALATED, CAUGHT_ERROR, FAILED, UNKNOWN) and a closed reason, a person's minutes from approval, question, exception and second-factor intervals, model calls and cost (unknown is null, never zero), field names with their checks, and the read-back tier; values only in a local 0600 sidecar; collected from the files guard, verify-run, compiled runs, wrap, item approvals and compile-agent already write, plus readiness shadow runs, guard ledger rows, P7 fallback results and P6 exception answers; a person's decline is ESCALATED, not a caught error | On main | Unit tests with synthetic data: the outcome rule as a table over every engine outcome enum, fixtures for each source (copies of the shadow, guarded-save, fallback and exception files from a synthetic MockMed end-to-end run), the real commit guard against MockMed's fault server end to end, exports scanned for every fixture value and checked with the real Presidio scrubber, push payloads validated against the JSON Schema, push refused with no key | `openadapt-flow ledger add`, `list`, `show`, `summary`, `export`, `push`; [RUN_LEDGER.md](packages/flow/docs/RUN_LEDGER.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own. One screen: map left, Seal and verdict top right, Summary, Steps, Evidence and Raw tabs; light and dark | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests; a link to one step, keyboard tabs and steps, theme switch, phone layout); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](packages/seal-view/README.md) | | Sign in to OpenAdapt Cloud from the terminal: `openadapt login` with no token prints a sign-in link (opened only with `--open`), listens on 127.0.0.1 for the browser's redirect, and redeems Cloud's one-use code with an S256 PKCE verifier that never leaves the process. A first-time user gets a workspace on the way. The credential goes to the OS keychain entry `push` and `report-run` read; a stored token is re-validated as before, and `--token` and `--no-browser` keep the token path | On main | Unit tests with a real loopback listener (state mismatch, refusal, malformed code, timeout, browser opened only on request); end to end against Cloud's `/auth/loopback` and pairing routes in mock mode, both Connect and Cancel | `openadapt login`; [browser_login.py](packages/flow/openadapt_flow/browser_login.py) | diff --git a/capabilities/11-recording-privacy-and-proof/0110-receipts-one-signed-record-per-run-with-any.md b/capabilities/11-recording-privacy-and-proof/0110-receipts-one-signed-record-per-run-with-any.md index 9e1099a040..55cbe5e1c5 100644 --- a/capabilities/11-recording-privacy-and-proof/0110-receipts-one-signed-record-per-run-with-any.md +++ b/capabilities/11-recording-privacy-and-proof/0110-receipts-one-signed-record-per-run-with-any.md @@ -1 +1 @@ -| 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) | +| 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; runs on a synthetic app (the tutorial, `replay --demo-app`) are signed with a separate demo key, never this computer's Seal key, so a receiver that pins this computer refuses them (the reference Execute worker's MockMed seals and the seeded reward contract use their own demo keys the same way); 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); tutorial and `replay --demo-app` receipts on headless MockMed checked as demo-signed and refused by this computer's pin; 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) | diff --git a/capabilities/CAPABILITIES.md.sha256 b/capabilities/CAPABILITIES.md.sha256 index b178c64d02..01a1d80a00 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -6b0c7d386eb68b516766993b4afb1ffe6a0ea4461851850db38a845a47648b81 +edf84a8e86d8b4ee8715734751fa8af1a60bacd4c42d52e0ac6cf064228555f0 diff --git a/llms-full.txt b/llms-full.txt index 128c26753b..989bba2d65 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -100,10 +100,38 @@ openadapt flow replay bundle --url https://staging.your-app.example --run-dir ru ## Verified Results -- **0% silent errors** across 60 real upstream web app upgrades (Gitea, Vikunja, Memos, Mealie), with 60/60 signed Ed25519 receipts. -- **0 warm API calls and no `429` rate limits** once compiled (`219 -> 10` calls on Gemini 3.1 Pro; warm compiled runs execute in `1.88 s` at `$0.000015/run`). -- **5x fewer false alarms** on Multi-Tab Stanford `HealthAdminBench` (`4.2%` vs. `20.8%` false escalations, lifting completion to `50.0%` with 0 regressions). -- **0 / 96 prompt injections** succeeded on `AgentDojo`. + + +Counted from the per-run ledgers in [`benchmarks/public-runs/`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/benchmarks/public-runs/). Each arm's N runs split three ways. **Verified**: the arm reported the run done and the benchmark's own checker agrees. **Silent error**: the arm reported the run done and the checker disagrees. **Halted**: the arm stopped without reporting the run done. The strongest baseline is the baseline arm, run on the same tasks, with the most verified runs. A silent-error count reads *not measured* when the arm's own read-back is the check that scores the run. + +| Benchmark | N | OpenAdapt: verified / silent errors / halted | Strongest baseline | Baseline: verified / silent errors / halted | The baseline reports a run done when | +|---|---|---|---|---|---| +| Real web app upgrades (Gitea, Vikunja, Memos, Mealie) | 60 | 42 / not measured / 18 | Stagehand-style self-heal | 43 / 2 / 15 | every step ran without an error | +| Real web app upgrades, paired gemini-3.1-pro-preview (36 of 60 planned tasks; the run stopped at the API's daily quota) | 36 | 34 / not measured / 2 | Unwrapped gemini-3.1-pro-preview | 17 / 0 / 19 | the agent declared the task done | +| HealthAdminBench, single tab (gpt-5.4 and claude-sonnet-5-5 pooled) | 24 | 5 / 11 / 8 | Unwrapped, same models | 7 / 17 / 0 | every run; it never escalated | +| HealthAdminBench, multi-tab (gpt-5.4 and claude-sonnet-5-5 pooled) | 24 | 11 / 10 / 3 | Unwrapped, same models | 10 / 14 / 0 | every run; it never escalated | +| ST-WebAgentBench (GitLab, ShoppingAdmin, SuiteCRM), gpt-5.4 | 44 | 3 / 22 / 19 | Unwrapped gpt-5.4 | 2 / 42 / 0 | every run; it never escalated | + +How each benchmark checks a run, and when OpenAdapt reports a run done: + +- Real web app upgrades (Gitea, Vikunja, Memos, Mealie): the checker is a read of the app's backend through its REST API after the run. OpenAdapt reports a run done when its read-back found the record through the app's REST API. In this run OpenAdapt's read-back used the same backend check that scores the run, so its silent-error count is not independent and is shown as not measured. +- Real web app upgrades, paired gemini-3.1-pro-preview (36 of 60 planned tasks; the run stopped at the API's daily quota): the checker is a read of the app's backend through its REST API after the run. OpenAdapt reports a run done when its read-back found the record through the app's REST API, and it issued a signed receipt. In this run OpenAdapt's read-back used the same backend check that scores the run, so its silent-error count is not independent and is shown as not measured. +- HealthAdminBench, single tab (gpt-5.4 and claude-sonnet-5-5 pooled): the checker is HealthAdminBench's own grader; a run passes when every subtask passes. OpenAdapt reports a run done when the run ended without OpenAdapt escalating it to a person. +- HealthAdminBench, multi-tab (gpt-5.4 and claude-sonnet-5-5 pooled): the checker is HealthAdminBench's own grader; a run passes when every subtask passes. OpenAdapt reports a run done when the run ended without OpenAdapt escalating it to a person. +- ST-WebAgentBench (GitLab, ShoppingAdmin, SuiteCRM), gpt-5.4: the checker is ST-WebAgentBench's evaluator; a run passes when the task is completed with no policy violated. OpenAdapt reports a run done when the run ended without OpenAdapt escalating it to a person. + +On the paired gemini-3.1-pro-preview run (36 tasks), the unwrapped agent made 219 model calls and OpenAdapt made 10. OpenAdapt's 27 warm replays made 0. + +| Safety benchmark | Measure | Without OpenAdapt | With OpenAdapt | +|---|---|---|---| +| AgentDojo, `gemini-2.5-flash` | prompt injections that succeeded | 35 / 48 | 8 / 48 | +| AgentDojo, `Qwen/Qwen3.5-4B` | prompt injections that succeeded | 7 / 48 | 1 / 48 | +| AgentDojo, `gpt-5.4` | prompt injections that succeeded | 0 / 48 | 0 / 48 | +| AgentDojo, `claude-sonnet-5-5` | prompt injections that succeeded | 0 / 48 | 0 / 48 | +| OS-Harm, 3 models pooled | runs with a harmful outcome or policy violation | 12 / 27 | 3 / 27 | +| OS-Harm, 3 models pooled | runs completed under policy | 11 / 27 | 17 / 27 | + + Full methodology, benchmark tables, and verifiable raw runs: **[openadapt.ai/proof](https://openadapt.ai/proof)** and sanitized per-run JSON ledgers in [`benchmarks/public-runs/`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/benchmarks/public-runs/). @@ -120,7 +148,7 @@ Full methodology, benchmark tables, and verifiable raw runs: **[openadapt.ai/pro | Package | Role | Source | |---|---|---| | [`openadapt`](https://pypi.org/project/openadapt/) | Unified CLI (`quickstart`, `wrap`, `connect`, `record`, `compile`, `run`, `verify`, `kernel`, `agent`, `mcpify`) | [`openadapt/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/openadapt) | -| [`openadapt-kernel`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/kernel) | Commit-boundary kernel: default-deny write ledger, wire/DOM commit interceptor, stepwise live-DOM healer, cross-rail oracles, Ed25519 receipts, stdio MCP | [`packages/kernel/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/kernel) | +| [`openadapt-kernel`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/kernel) | Optional alpha extra (`pip install 'openadapt[kernel]'`). Commit-boundary kernel: default-deny write ledger, wire/DOM commit interceptor, stepwise live-DOM healer, cross-rail oracles, Ed25519 receipts, stdio MCP | [`packages/kernel/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/kernel) | | [`openadapt-flow`](https://pypi.org/project/openadapt-flow/) | Demonstration compiler, certification, qualification, governed replay, auto-repair, and BYOC connector | [`packages/flow/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/flow) | | [`openadapt-agent`](https://pypi.org/project/openadapt-agent/) | MCP server, Agent Skills export, and A2A handoffs | [`packages/agent/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/agent) | | [`openadapt-verify`](https://pypi.org/project/openadapt-verify/) | Standalone Python SDK (`@verified`, `checked_write`, local JIT compiler, `mcpify`) | [`packages/verify/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/verify) | @@ -347,6 +375,7 @@ improvising or retrying when something is off. | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | | One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". Run receipts (`record/run/v1`, an additive optional field), `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects; a run receipt says it has no per-read time). A run receipt never says `VERIFIED` below level 3. Receipts without the block still verify. A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | | Grade a file, PDF or email check by who produced it: a file the acting session wrote or downloaded, or one with no declared producer, is at most `same_screen`; one a separate session fetched is at most `separate_session`; only a declared `system_of_record` producer reaches `system_of_record`. A store that overlaps the acting session's folders (named ones, the user's Downloads, a Playwright download folder) is graded as the acting session's whatever is declared. Under a strong declared producer, a scan that reads a file in a browser download folder beneath the store, or a symlink out of it, is refused as INDETERMINATE. The verdict's `read_evidence.provenance` names the producer and whether it was declared or observed | On main | Unit tests through each of the four readers (mixed store, symlink, system-owned positive case); a PDF downloaded by headless Chromium from a loopback app, the same bytes from a separate browser context and from the app's store, and a headless download landing beneath a broader store | `runtime/effects/artifact_provenance.py`, `effects.artifact_producer`, `packages/flow/tests/test_effect_artifact_provenance.py` | +| One strict matcher decides whether text on a screen or page proves a value or a commit: `MATCH`, `MISMATCH` or `AMBIGUOUS`, and only `MATCH` passes. A value must be bound to its label at the start of its field, with nothing but unit words beside it, or be the whole field. A value merely found on the page, inside a longer token (`250` in `$1,250.00`, `John Smith` in `John Smith-Jones`), or under a label with two values never passes. A commit phrase must be new, plainly stated, and not next to a question, a negation or a control label. The launcher's transducer read-back and the kernel's read-back oracles use it; [the migration page](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/docs/evidence-migration.md) lists the callers that don't yet | On main | Adversarial corpus with pinned verdicts, Hypothesis properties, a parity test against Flow's read-back matcher, and strict expected-failure tests for each caller not yet migrated | `openadapt_types/evidence.py`, `openadapt/transducer_obligations.py`, `openadapt_kernel/oracles.py` | | Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | PR [#2500](https://github.com/OpenAdaptAI/OpenAdapt/pull/2500), not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EFFECT_LOCATION.md) | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ENSURE_RECORD.md) | @@ -405,6 +434,7 @@ improvising or retrying when something is off. | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AFTER_A_STOP.md) | | Roll a stopped run back on its own: the approved compensation for each change, latest first, an uncertain write only when a fresh read shows it landed, then a read of the whole database: every row the run touched back as it was and nothing else changed (`ROLLED_BACK`), or the exact rows a person repairs (`RECONCILIATION_REQUIRED`). A compensation runs only while every change in the store is positively the run's own by the app's audit log, so another user's work is never compensated away, and a hard delete runs only where the deployment allows it (void, restore or discard otherwise). `rollback qualify` stops the run before and after every save on a test copy and keeps only compensations that restore the whole store. On a desktop or remote-display backend a screen compensation runs only after the run's and the compensation's start screens are checked on the same backend | On main ([#1634](https://github.com/OpenAdaptAI/OpenAdapt/pull/1634)); desktop in [#1771](https://github.com/OpenAdaptAI/OpenAdapt/pull/1771) | MockMed, live browser through the CLI; SQLite whole-database tests (web and desktop paths) | `openadapt-flow rollback qualify`, `rollback:` in deployment.yaml; [ROLLBACK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ROLLBACK.md) | | Leave the screen clean after an item that halted before any write: close dialogs and cancel forms with the recordings' own controls, re-enter, confirm the start screen and read the records back before the session takes another item. A session that doesn't come back is marked dirty and takes no more items; a cleanup that changed a record makes the item's write uncertain and stops the run. `cleanup qualify` tries the cleanup after every step on a test copy and refuses one that changes a record | Released ([#1607](https://github.com/OpenAdaptAI/OpenAdapt/pull/1607)) | Synthetic (scripted three-screen app through the real replayer and pool) and real app (pinned OpenEMR: a halted New Patient item left the confirmation dialog open; re-entry closed it, the form was empty, no patient row changed and the next item's first steps ran with no model calls; a signed-out screen was marked dirty; [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/halt_cleanup/results/openemr.json)) | `openadapt-flow cleanup qualify`; [HALT_CLEANUP.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HALT_CLEANUP.md) | +| Commit-boundary kernel, an optional alpha extra: `pip install 'openadapt[kernel]'` adds `openadapt kernel` (or install `openadapt-kernel` alone for its own command), an experimental runtime with shadow, draft and autopilot modes and signed receipts that does not depend on `openadapt-flow`. `pip install openadapt` leaves it out, and the extra is capped below the next minor version because its API may change before 1.0 | On main | Synthetic (its own suite, headless Chromium tests included, runs in the required `ci` check on every kernel change) | [packages/kernel](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/kernel/README.md) | ## Approvals @@ -505,6 +535,7 @@ improvising or retrying when something is off. | Self-repair's new clicks outside a browser: on a native app a click is admitted by its accessibility element (role, name, ancestry, window; unique in the pinned window), on pixels only by the record check, and either way only when a system-of-record verifier covers every save under `standard` or `regulated`; the new step carries the dialog around it as a screen pre-check, and only a person approves the fix | On main ([#1709](https://github.com/OpenAdaptAI/OpenAdapt/pull/1709)) | Synthetic, partly live: on OpenAdapt's native Cocoa test app with SQLite, through live macOS AX, the stop, the element identity read, the admission and the refusals without a record check ran with no wrong write; qualified end to end on macOS AX ([#1715](https://github.com/OpenAdaptAI/OpenAdapt/pull/1715)): stop, admitted click, probe, replay and fault campaigns, one approval, resumed run `VERIFIED`; and on its GTK3 counterpart through live Linux AT-SPI, in CI, the same end to end. `run --self-repair` and repair by default start the app for each probe from `repair.session` ([#1717](https://github.com/OpenAdaptAI/OpenAdapt/pull/1717); [benchmark/repair_every_backend](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/repair_every_backend/README.md)) | `openadapt_flow/repair/element_identity.py`, [REPAIR_ON_EVERY_BACKEND.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/REPAIR_ON_EVERY_BACKEND.md) | | Keep pixel-path runs working across display scaling and font smoothing changes | Released ([#1286](https://github.com/OpenAdaptAI/OpenAdapt/pull/1286)) | Synthetic (in-process RDP and canvas renderings: 17 of 24 healthy runs across 100–175%, up from 3; 0 wrong saves) | [benchmark/pixel_scale](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/pixel_scale/README.md) | | Find icons again on Citrix, RDP and VNC after a display-scale, zoom, font, theme or codec change, with a local model that counts look-alikes and stops on a tie (`--local-grounding`, off by default) | Released ([#1596](https://github.com/OpenAdaptAI/OpenAdapt/pull/1596)) | Synthetic (Chromium-drawn clinic screen, pixels only: icons found under 21 of 26 conditions, template matching 8; 0 wrong targets in 65; whole runs unchanged, 4 of 39 in both arms, because the layout, identity and census checks stop first). Held out on real AVC444 RDP frames: 0 wrong picks, 6 right, 75 abstentions in 81 | [benchmark/pixel_grounding](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/pixel_grounding/README.md), `runtime/local_grounder.py` | +| Find an icon-only click target again after a light/dark theme change on Citrix, RDP and VNC, by edge orientation with the sign removed, refusing when another place on the screen scores close, the match is away from the recorded place, or the clicked control itself differs | In a pull request ([#2790](https://github.com/OpenAdaptAI/OpenAdapt/pull/2790)) | Synthetic (Chromium-drawn clinic screen, pixels only, recorded light and replayed dark at 100% and 150%: whole runs 8 of 13 healthy and 7 of 13 reordered, up from 6 and 5; wrong-record runs 13 of 13 stopped; 0 wrong targets or wrong saves) | [benchmark/pixel_grounding](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/pixel_grounding/README.md#whole-runs), `vision/polarity_match.py` | | Pre-approved repairs: a signed policy lists low-risk changes that apply without a person, a test-record run before each queue, and one approval for every item halted the same way | Released ([#1294](https://github.com/OpenAdaptAI/OpenAdapt/pull/1294)) | Synthetic | standard changes | | Repair a pinned bundle: the fix runs the pinned bundle's own qualification campaign on a test copy, keeps every write, effect, identity rule and record check, and is re-admitted with signed lineage (at most three repairs, no revoked key) that the pin verifies | On main | Synthetic | [SELF_REPAIR.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SELF_REPAIR.md#a-pinned-bundle-re-qualify-and-re-admit) | | Repair by default: once a repair agent is configured (outside a browser, with `repair.session`, [#1717](https://github.com/OpenAdaptAI/OpenAdapt/pull/1717)), every stop that wrote nothing goes to it without anyone starting it; a stop after a possible write goes to reconciliation; every stop is a row in a ledger with the funnel from stop to resumed item | Released ([#1360](https://github.com/OpenAdaptAI/OpenAdapt/pull/1360)) | Synthetic (MockMed, 22 drift modes, real Claude agent: 6 of 21 repairable stops resumed and verified, 0 wrong saves in 66 runs); routing over recorded OpenEMR stops; live openIMIS relabel: 3 of 3 reached repair and stopped with no wrong save; silent-saves 1.1.0 UI-change blocks: 18 of 28 items that always stopped now correct, 0 wrong | `run` (on by default, `--no-auto-repair`), `repair:` in `deploy.yaml`, [benchmark/auto_repair](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/auto_repair/README.md) | @@ -571,12 +602,13 @@ improvising or retrying when something is off. | 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) | | Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | Branch ([#2497](https://github.com/OpenAdaptAI/OpenAdapt/pull/2497)) | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/deployment/ON_PREM_VLM.md) | -| 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) | +| 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; runs on a synthetic app (the tutorial, `replay --demo-app`) are signed with a separate demo key, never this computer's Seal key, so a receiver that pins this computer refuses them (the reference Execute worker's MockMed seals and the seeded reward contract use their own demo keys the same way); 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); tutorial and `replay --demo-app` receipts on headless MockMed checked as demo-signed and refused by this computer's pin; 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) | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRITE_RECEIPTS.md) | +| Python `openadapt.wrap` receipts signed with this computer's `openadapt trust init` key by default (or `signing_key=`), naming the key by id and fingerprint; with no key a receipt says `digest_only` and `signed: false`, and `wrap` never creates a key. `verify_wrap_receipt` and `openadapt verify` accept a receipt only when its signature verifies against a key you pinned, never the key the receipt carries; an unknown signer or a digest-only receipt is not verified. A plain `check=` callable is recorded as `caller_check`, and a check can't raise its own `checked_how` | On main | Unit tests with real Ed25519 keys: an unsigned receipt with a recomputed digest and a receipt signed by its own embedded key both fail, through the SDK and `openadapt verify` | `openadapt.wrap`, `openadapt.verify_wrap_receipt`, `openadapt verify FILE [--keys FILE]`, `openadapt trust init` | | Per-run accounting ledger for any executor (an OpenAdapt agent, a compiled program, another agent, a person): one value-free row per run with the outcome (VERIFIED, ESCALATED, CAUGHT_ERROR, FAILED, UNKNOWN) and a closed reason, a person's minutes from approval, question, exception and second-factor intervals, model calls and cost (unknown is null, never zero), field names with their checks, and the read-back tier; values only in a local 0600 sidecar; collected from the files guard, verify-run, compiled runs, wrap, item approvals and compile-agent already write, plus readiness shadow runs, guard ledger rows, P7 fallback results and P6 exception answers; a person's decline is ESCALATED, not a caught error | On main | Unit tests with synthetic data: the outcome rule as a table over every engine outcome enum, fixtures for each source (copies of the shadow, guarded-save, fallback and exception files from a synthetic MockMed end-to-end run), the real commit guard against MockMed's fault server end to end, exports scanned for every fixture value and checked with the real Presidio scrubber, push payloads validated against the JSON Schema, push refused with no key | `openadapt-flow ledger add`, `list`, `show`, `summary`, `export`, `push`; [RUN_LEDGER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RUN_LEDGER.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own. One screen: map left, Seal and verdict top right, Summary, Steps, Evidence and Raw tabs; light and dark | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests; a link to one step, keyboard tabs and steps, theme switch, phone layout); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/seal-view/README.md) | | Sign in to OpenAdapt Cloud from the terminal: `openadapt login` with no token prints a sign-in link (opened only with `--open`), listens on 127.0.0.1 for the browser's redirect, and redeems Cloud's one-use code with an S256 PKCE verifier that never leaves the process. A first-time user gets a workspace on the way. The credential goes to the OS keychain entry `push` and `report-run` read; a stored token is re-validated as before, and `--token` and `--no-browser` keep the token path | On main | Unit tests with a real loopback listener (state mismatch, refusal, malformed code, timeout, browser opened only on request); end to end against Cloud's `/auth/loopback` and pairing routes in mock mode, both Connect and Cancel | `openadapt login`; [browser_login.py](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/openadapt_flow/browser_login.py) | @@ -1117,6 +1149,38 @@ are part of the qualification boundary, so this does not qualify arbitrary fresh workers. A script-hosted application's own code is covered by its declared version, not the host executable's hash. +## Windows approval: controls without their own window + +Before a save, an approval on Windows reads the app window to check that +nothing changed while the person decided. A text box or label with its own +window is read through two independent sources that must agree, so a value +cut short by the app's accessibility provider stops the item. A control drawn +by its parent, such as a grid cell, a grid column header or the title bar, +has no second source. Its UI Automation value is read twice and must match, +and the screen text over it is still read. If the provider cuts that value +short, a change in the hidden part that also leaves the visible text the same +is not detected. Some providers give such a control no RuntimeId at all +(WinForms grid cells and column headers). That control is then bound by its +path: each element up to an ancestor that has a RuntimeId, by type, position +and index among its siblings, read again before and after each of the two +reads. If a provider swaps in another element with the same type, position +and index, the check reads it as the same control; a changed value still +shows in the two reads or in the screen text. A scroll or resize between the +reads stops the item. A grid or list cell, a header or the title bar is +included even when its provider reports it as editable (WinForms does so +for a read-only grid); a text box never is. These values are used only for +that check: they are never complete values, read-back evidence or the basis +of a VERIFIED result. Read-back, not the approval check, verifies what a +save wrote. An +editable control, a password field, a control whose password status is +unknown, or one whose two reads differ still stops the item. + +A native Windows stale-identity fault covers the whole screen, so the +keyboard lease that checks the target refuses and the save halts. The fault +receipt then binds to the engine's own plain screenshot, and only when its +SHA-256 equals the frame the fault driver signed. Otherwise no receipt is +recorded and the campaign rejects the case. + ## Validated on Every published result used synthetic patients, claims and records. diff --git a/packages/flow/README.md b/packages/flow/README.md index 36cb8f5c09..8c07393f32 100644 --- a/packages/flow/README.md +++ b/packages/flow/README.md @@ -395,6 +395,13 @@ passed. `--seed-mockmed` registers two simulated MockMed workflows, an honest app and one that drops the save, which return results without opening a browser. +Results about MockMed, a synthetic app, are signed with the worker's demo key, +not its own key. That covers the seeded workflows and any bundle the worker +replays in process on its bundled demo app. `GET /health` names the worker's +key as `issuer_key_fingerprint` and the demo key as `demo_key_fingerprint`. A +client that pins `issuer_key_fingerprint` refuses a demo seal, and the seal +page and the `X-OpenAdapt-Demo` header say it was a synthetic demo app. + `openadapt-flow emit-mcp bundle --out server.py` writes a standalone MCP server for one bundle. Web and desktop tools use the same governed `run` CLI. Start the server with `--config deploy.yaml --profile standard diff --git a/packages/flow/docs/RECEIPTS.md b/packages/flow/docs/RECEIPTS.md index a72e8cb94c..bc2252ca8c 100644 --- a/packages/flow/docs/RECEIPTS.md +++ b/packages/flow/docs/RECEIPTS.md @@ -91,6 +91,22 @@ OpenAdapt Cloud countersigns the same envelope; it doesn't issue a separate object. An unknown key, role or schema fails closed, even beside a valid signature, and so does a demo key next to a real one. +### Runs on a synthetic app use the demo key + +The tutorial and `replay --demo-app` run on MockMed, a synthetic app. Their +`receipt.json` is signed with this computer's **demo key**, kept under +`/demo`. It is never the Seal key, and never a key named by +`OPENADAPT_SEAL_KEY`. A receipt has no field that marks a run as synthetic, +and the receiver's registry decides what a key means. So a synthetic run +signed with this computer's key would read like proof about a real system. + +- A receiver that pins this computer's key refuses the receipt + (`unknown_signer`), and so does `openadapt verify` by default. +- A receiver that pins the demo key with the role `demo` sees "Demo key: + checks only in this demo". +- Adding this computer's signature to it is refused as a mixed demo + signature. + ## Check one ```bash diff --git a/packages/flow/docs/REWARD_WORKER.md b/packages/flow/docs/REWARD_WORKER.md index 37645ecd04..40874dc102 100644 --- a/packages/flow/docs/REWARD_WORKER.md +++ b/packages/flow/docs/REWARD_WORKER.md @@ -169,7 +169,10 @@ python -m openadapt_flow serve-reward --seed-mockmed --port 8788 ``` `--seed-mockmed` writes two contract bundles and their stores under the data -directory and serves the tier-2 one when `--contract` is omitted. +directory and serves the tier-2 one when `--contract` is omitted. The seeded +contracts describe MockMed, a synthetic app, so their certificates and every +reward receipt for them are signed with the demo key under `/demo`, +not the worker's own key. A client that pins the worker's key refuses them. `contracts/mockmed` reads `mockmed/records.db` through the `sqlite` recipe, channel `db`, tier 2. The database starts with two rows for the duplicate diff --git a/packages/flow/docs/TUTORIAL.md b/packages/flow/docs/TUTORIAL.md index fa71ce04f3..4521e6fd81 100644 --- a/packages/flow/docs/TUTORIAL.md +++ b/packages/flow/docs/TUTORIAL.md @@ -117,6 +117,11 @@ free-form halt reason. It carries the bundle digest, so anyone can run the same public tutorial and compare. The complete field set is in [`RECEIPTS.md`](RECEIPTS.md). +The tutorial's signed `receipt.json` is signed with the demo key, not this +computer's Seal key, because MockMed is a synthetic app. A receiver that pins +this computer's key refuses it, so it can't pass for proof about a real +system. See [`RECEIPTS.md`](RECEIPTS.md#runs-on-a-synthetic-app-use-the-demo-key). + ## Drive the same stages by hand ```bash diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 2bfde4a3bf..419fd36341 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -1116,12 +1116,15 @@ def _undo_run_target_problem(args: argparse.Namespace, workflow) -> Optional[str def _print_terminal_receipt( - run_dir: Path, report, *, require_opt_in: bool = False + run_dir: Path, report, *, require_opt_in: bool = False, synthetic: bool = False ) -> None: from openadapt_flow.receipt_record import receipt_after_run note = receipt_after_run( - run_dir, require_opt_in=require_opt_in, expected_report=report + run_dir, + require_opt_in=require_opt_in, + expected_report=report, + synthetic=synthetic, ) if note: print(note, file=sys.stderr) @@ -1174,7 +1177,10 @@ def _finish_replay( _maybe_report_break(run_dir, report) _maybe_report_run(run_dir, report, args, backend_kind=backend_kind) if args is not None: - _print_terminal_receipt(run_dir, report) + # --demo-app replays run on the bundled synthetic app: demo key. + _print_terminal_receipt( + run_dir, report, synthetic=bool(getattr(args, "demo_app", False)) + ) _maybe_attest_run(run_dir, report, args) if getattr(report, "execution_profile", None) in {"standard", "regulated"}: return 0 if outcome == "VERIFIED" else 1 @@ -13428,14 +13434,19 @@ def _cmd_serve_reward(args: argparse.Namespace) -> int: contract = args.contract seeded_paths: dict[str, Path] = {} seeded_store: Optional[tuple[Path, Path]] = None + key_dir: Optional[Path] = None if args.seed_mockmed: from openadapt_flow.execute.keys import ( + DEMO_KEY_DIR, fingerprint_of, load_or_create_private_key, ) from openadapt_flow.tutorial import seed_demo_reward - key = load_or_create_private_key(data_dir) + # The seeded contracts are about synthetic MockMed: the demo key signs + # them, never this worker's own key. + demo_dir = data_dir / DEMO_KEY_DIR + key = load_or_create_private_key(demo_dir) issuer_key_id = "self_signed:" + fingerprint_of(key.public_key()) seeded_paths, store_db, store_screen = seed_demo_reward( data_dir, key, issuer_key_id @@ -13443,9 +13454,12 @@ def _cmd_serve_reward(args: argparse.Namespace) -> int: seeded_store = (store_db, store_screen) if contract is None: contract = str(seeded_paths["tier2"]) + seeded = {Path(p).resolve() for p in seeded_paths.values()} + if Path(contract).resolve() in seeded: + key_dir = demo_dir if contract is None: raise SystemExit("serve-reward needs --contract or --seed-mockmed") - worker = RewardWorker(contract, data_dir, token=args.token) + worker = RewardWorker(contract, data_dir, token=args.token, key_dir=key_dir) print("openadapt-flow reference reward worker") print(f" http://{args.host}:{args.port}") print(f" data dir {data_dir}") @@ -13457,7 +13471,10 @@ def _cmd_serve_reward(args: argparse.Namespace) -> int: ) print(f" certificate {'present' if worker.certificate else 'absent'}") print(f" token {worker.token}") - print(" issuer self_signed") + print( + " issuer self_signed" + + (" (demo key: synthetic MockMed contract)" if key_dir is not None else "") + ) print(f" fingerprint {worker.fingerprint}") print(f" {REWARD_NOTICE}") for label, path in seeded_paths.items(): diff --git a/packages/flow/openadapt_flow/execute/app.py b/packages/flow/openadapt_flow/execute/app.py index 5deefc4ee9..2953400ce7 100644 --- a/packages/flow/openadapt_flow/execute/app.py +++ b/packages/flow/openadapt_flow/execute/app.py @@ -61,6 +61,9 @@ def health() -> dict[str, Any]: "service": "openadapt-execute-ref", "issuer": "self_signed", "issuer_key_fingerprint": store.fingerprint, + # Results about the bundled synthetic demo app are signed with + # this key instead. Pin issuer_key_fingerprint, not this one. + "demo_key_fingerprint": store.demo_fingerprint, "production_seal": False, } @@ -95,7 +98,7 @@ def get_receipt( body = receipt.model_dump(mode="json") return JSONResponse( content=body, - headers=_issuer_headers(store), + headers=_issuer_headers(store, demo=store.is_demo_execution(execution_id)), ) @app.get("/seals/{seal_id}", response_model=None) @@ -107,6 +110,7 @@ def get_seal( # Local analog of a public verify page: the seal has no PHI. del authorization seal = store.get_seal(seal_id) + demo = seal.issuer_key_fingerprint == store.demo_fingerprint accept = request.headers.get("accept", "") want_json = request.query_params.get("format") == "json" or ( _JSON in accept and "text/html" not in accept @@ -114,9 +118,12 @@ def get_seal( if want_json: return JSONResponse( content=seal.model_dump(mode="json"), - headers=_issuer_headers(store), + headers=_issuer_headers(store, demo=demo), ) - return HTMLResponse(_render_seal_html(seal), headers=_issuer_headers(store)) + return HTMLResponse( + _render_seal_html(seal, demo=demo), + headers=_issuer_headers(store, demo=demo), + ) @app.post("/mcp", response_model=None) async def mcp_endpoint( @@ -200,12 +207,17 @@ def _require_bearer(store: ExecuteService, authorization: Optional[str]) -> None raise HTTPException(status_code=401, detail="invalid bearer token") -def _issuer_headers(store: ExecuteService) -> dict[str, str]: - return { +def _issuer_headers(store: ExecuteService, *, demo: bool = False) -> dict[str, str]: + headers = { "X-OpenAdapt-Issuer": "self_signed", - "X-OpenAdapt-Issuer-Fingerprint": store.fingerprint, + "X-OpenAdapt-Issuer-Fingerprint": ( + store.demo_fingerprint if demo else store.fingerprint + ), "X-OpenAdapt-Production-Seal": "false", } + if demo: + headers["X-OpenAdapt-Demo"] = "synthetic-demo-app" + return headers async def _json_object(request: Request) -> dict[str, Any]: @@ -325,7 +337,7 @@ def _call_mcp_tool(store: ExecuteService, name: str, arguments: dict[str, Any]) raise ExecuteServiceError(404, "unknown_tool", f"no MCP tool named {name!r}") -def _render_seal_html(seal: SelfSignedSealV1) -> str: +def _render_seal_html(seal: SelfSignedSealV1, *, demo: bool = False) -> str: receipt = seal.receipt outcome = html.escape(str(receipt.get("outcome", ""))) receipt_id = html.escape(str(receipt.get("receipt_id", ""))) @@ -333,6 +345,12 @@ def _render_seal_html(seal: SelfSignedSealV1) -> str: digest = html.escape(str(receipt.get("workflow_digest", ""))) fingerprint = html.escape(seal.issuer_key_fingerprint) notice = html.escape(seal.notice) + demo_banner = ( + '\n " + if demo + else "" + ) return f""" @@ -349,7 +367,7 @@ def _render_seal_html(seal: SelfSignedSealV1) -> str: + {demo_banner}

Local Execute receipt

{notice}

diff --git a/packages/flow/openadapt_flow/execute/dispatch.py b/packages/flow/openadapt_flow/execute/dispatch.py index 49b71608d5..41bf087e31 100644 --- a/packages/flow/openadapt_flow/execute/dispatch.py +++ b/packages/flow/openadapt_flow/execute/dispatch.py @@ -10,7 +10,7 @@ import hashlib import json -from dataclasses import dataclass +from dataclasses import dataclass, replace from pathlib import Path from typing import Any, Callable, Optional @@ -58,6 +58,9 @@ class DispatchResult: compensation_effect_verified: bool workflow_digest: str evidence_digest: str + #: The run was on the worker's bundled demo app (a synthetic projection or + #: an in-process replay on MockMed). Its seal is signed with the demo key. + demo_app: bool = False def default_runner( @@ -103,7 +106,7 @@ def synthetic_runner( strength = EffectStrengthV1(request.minimum_effect_strength) if admission.break_it or _request_break_it(request): - return _result( + result = _result( outcome=ExecuteTerminalOutcomeV1.RECONCILIATION_REQUIRED, authorization_passed=True, identity_passed=True, @@ -115,7 +118,8 @@ def synthetic_runner( workflow_digest=request.workflow_digest, evidence_tag="synthetic-banner-lie", ) - return _result( + return replace(result, demo_app=True) + result = _result( outcome=ExecuteTerminalOutcomeV1.VERIFIED, authorization_passed=True, identity_passed=True, @@ -127,6 +131,7 @@ def synthetic_runner( workflow_digest=request.workflow_digest, evidence_tag="synthetic-verified", ) + return replace(result, demo_app=True) def live_replay( @@ -217,7 +222,11 @@ def live_replay( except Exception as exc: # The replay may have dispatched a write before it failed. raise DispatchError(f"local replay failed: {exc}", pre_effect=False) from exc - return project_run_report(report, workflow_digest=request.workflow_digest) + # In process, the worker replays only on the demo app it serves itself. + return replace( + project_run_report(report, workflow_digest=request.workflow_digest), + demo_app=True, + ) def _surface_replay( diff --git a/packages/flow/openadapt_flow/execute/keys.py b/packages/flow/openadapt_flow/execute/keys.py index 900493d811..752a5ef35f 100644 --- a/packages/flow/openadapt_flow/execute/keys.py +++ b/packages/flow/openadapt_flow/execute/keys.py @@ -19,6 +19,9 @@ ) _KEY_NAME = "ed25519.pem" +#: Subdirectory of a worker's data dir that holds its demo key: the key that +#: signs results about the bundled synthetic demo app, never the worker's key. +DEMO_KEY_DIR = "demo" _PUB_NAME = "ed25519.pub" diff --git a/packages/flow/openadapt_flow/execute/service.py b/packages/flow/openadapt_flow/execute/service.py index 052b6903e5..f6e7f013dc 100644 --- a/packages/flow/openadapt_flow/execute/service.py +++ b/packages/flow/openadapt_flow/execute/service.py @@ -32,6 +32,7 @@ default_runner, ) from openadapt_flow.execute.keys import ( + DEMO_KEY_DIR, fingerprint_of, load_or_create_private_key, load_or_create_token, @@ -85,6 +86,13 @@ def __init__( self._key: Ed25519PrivateKey = load_or_create_private_key(self.data_dir) self.token = load_or_create_token(self.data_dir, token) self.fingerprint = fingerprint_of(self._key.public_key()) + # Runs on the bundled demo app (MockMed) are signed with a separate + # demo key, so a client that pins this worker's key never accepts a + # seal about a synthetic app as proof about a real system. + self._demo_key: Ed25519PrivateKey = load_or_create_private_key( + self.data_dir / DEMO_KEY_DIR + ) + self.demo_fingerprint = fingerprint_of(self._demo_key.public_key()) self.runner = runner or functools.partial( default_runner, deployment=Path(deployment).expanduser() if deployment else None, @@ -170,6 +178,14 @@ def get_receipt(self, execution_id: str) -> ExecuteEvidenceReceiptV1: assert_no_forbidden_keys(payload) return ExecuteEvidenceReceiptV1.model_validate(payload) + def is_demo_execution(self, execution_id: str) -> bool: + """Whether this execution's seal was signed with the demo key.""" + path = self._execution_path(execution_id) / "seal.json" + if not path.is_file(): + return False + payload = json.loads(path.read_text(encoding="utf-8")) + return payload.get("issuer_key_fingerprint") == self.demo_fingerprint + def get_seal(self, seal_id: str) -> SelfSignedSealV1: execution_id = self._execution_id_for_seal(seal_id) path = self._execution_path(execution_id) / "seal.json" @@ -226,22 +242,25 @@ def _run(self, execution_id: str, request: ExecuteRequestV1) -> None: if exc.pre_effect else _reconciliation_required_result(request, str(exc)) ) - self._finalize_fault(execution_id, request, fault) + self._finalize_fault(execution_id, request, fault, demo=admission.synthetic) return except Exception as exc: self._finalize_fault( execution_id, request, _reconciliation_required_result(request, str(exc)), + demo=admission.synthetic, ) return + demo = admission.synthetic or result.demo_app try: - self._finalize(execution_id, request, result) + self._finalize(execution_id, request, result, demo=demo) except Exception as exc: self._finalize_fault( execution_id, request, _reconciliation_required_result(request, str(exc)), + demo=demo, ) def _finalize_fault( @@ -249,6 +268,8 @@ def _finalize_fault( execution_id: str, request: ExecuteRequestV1, fault: DispatchResult, + *, + demo: bool = False, ) -> None: """Seal a fault receipt, or hand the run to a person if that fails. @@ -258,7 +279,7 @@ def _finalize_fault( person has to check the record before anything is retried. """ try: - self._finalize(execution_id, request, fault) + self._finalize(execution_id, request, fault, demo=demo) except Exception: logger.exception( "could not seal the fault receipt for %s; waiting for reconciliation", @@ -283,6 +304,8 @@ def _finalize( execution_id: str, request: ExecuteRequestV1, result: DispatchResult, + *, + demo: bool = False, ) -> None: receipt_id = _new_id("receipt") issued_at = _now() @@ -316,9 +339,9 @@ def _finalize( payload = receipt.model_dump(mode="json") assert_no_forbidden_keys(payload) canonical = _canonical_json(payload) - signature = sign_bytes(self._key, canonical) + signature = sign_bytes(self._demo_key if demo else self._key, canonical) seal = SelfSignedSealV1( - issuer_key_fingerprint=self.fingerprint, + issuer_key_fingerprint=self.demo_fingerprint if demo else self.fingerprint, signature=signature, production_seal=False, meter_usd=0.0, diff --git a/packages/flow/openadapt_flow/offline_seal.py b/packages/flow/openadapt_flow/offline_seal.py index fe997d3958..bce0b51414 100644 --- a/packages/flow/openadapt_flow/offline_seal.py +++ b/packages/flow/openadapt_flow/offline_seal.py @@ -223,6 +223,26 @@ def signer_for( raise LocalSealError(exc.code, str(exc)) from exc +#: Where the demo key lives under the Seal home. It is a different key from +#: the Seal key, so a receiver that pins this computer's key never accepts a +#: receipt for a run on a synthetic app. +DEMO_KEY_DIR = "demo" + + +def demo_signer_for(home: Optional[Path] = None) -> "SealSigner": + """The demo key that signs receipts for runs on synthetic apps. + + Generated on first use under ``/demo``. It is never the Seal key + and never a key from ``OPENADAPT_SEAL_KEY``: whoever pins it does so with + the ``demo`` role, whose verdict says it checks only inside that demo. + """ + from openadapt_flow.execute.keys import load_or_create_private_key + from openadapt_flow.seal_keys import SoftwareSigner + + root = (home or seal_home()) / DEMO_KEY_DIR + return SoftwareSigner(load_or_create_private_key(root), "generated", "demo") + + def public_key_entry( home: Optional[Path] = None, *, signer: Optional["SealSigner"] = None ) -> dict[str, str]: diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 4935e25da3..ace896c52f 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -567,12 +567,19 @@ def write_receipt_record( env: Optional[Mapping[str, str]] = None, expected_report: Optional["RunReport"] = None, handoff_ledgers: Sequence[Any] = (), + synthetic: bool = False, ) -> dict[str, Any]: """Write ``receipt.json`` and ``receipt.private.json`` for a finished run. ``handoff_ledgers`` (``openadapt_flow.handoffs.HandoffLedger``): the run's handoffs in them go on the receipt as counterparty confirmation lines. + ``synthetic``: the run was on a synthetic app (the tutorial, ``replay + --demo-app``). The receipt is signed with the demo key + (:func:`openadapt_flow.offline_seal.demo_signer_for`), never this + computer's Seal key, so it can't pass for proof about a real system. A + ``signer`` can't be combined with it. + Idempotent: an existing receipt over the same report bytes is kept. A receipt over different bytes is never silently replaced. """ @@ -586,6 +593,10 @@ def write_receipt_record( if sealed_set.is_sealed(run_dir) else mutation_lock(run_dir) ) + if synthetic and signer is not None: + raise ReceiptRecordError( + "synthetic_signer", "a synthetic run is signed only with the demo key" + ) with lock: return _write_locked( Path(run_dir), @@ -595,6 +606,7 @@ def write_receipt_record( env, expected_report, handoff_ledgers, + synthetic, ) @@ -606,6 +618,7 @@ def _write_locked( env: Optional[Mapping[str, str]], expected_report: Optional["RunReport"], handoff_ledgers: Sequence[Any] = (), + synthetic: bool = False, ) -> dict[str, Any]: from openadapt_types import receipt as r @@ -643,7 +656,12 @@ def _write_locked( digest = hashlib.sha256(raw).hexdigest() if flow_version is None: from openadapt_flow import __version__ as flow_version - chosen = signer or signer_for(home, env=env) + if synthetic: + from openadapt_flow.offline_seal import demo_signer_for, seal_home + + chosen = demo_signer_for(home or seal_home(env)) + else: + chosen = signer or signer_for(home, env=env) try: evidence_key = chosen.public_raw() except KeyUnavailable as exc: @@ -676,7 +694,8 @@ def _write_locked( statement = _awaiting_counterparty(statement, placed) kid = r.key_id(chosen.public_raw()) entry = chosen.registry_entry() - registry = [r.RoleKey(kid, entry["public_key"], "this_computer")] + role = "demo" if synthetic else "this_computer" + registry = [r.RoleKey(kid, entry["public_key"], role)] out = run_dir / RECEIPT_FILE private = run_dir / PRIVATE_FILE legacy = None @@ -861,8 +880,12 @@ def receipt_after_run( *, require_opt_in: bool = False, expected_report: Optional["RunReport"] = None, + synthetic: bool = False, ) -> Optional[str]: - """CLI hook: write the run's receipt. Never raises, never changes the exit code.""" + """CLI hook: write the run's receipt. Never raises, never changes the exit code. + + ``synthetic`` signs with the demo key (see :func:`write_receipt_record`). + """ env = os.environ if env is None else env if require_opt_in and env.get(ENV_MODE, "").strip().lower() not in { "1", @@ -887,6 +910,7 @@ def receipt_after_run( env=env, expected_report=expected_report, handoff_ledgers=ledgers_for(env), + synthetic=synthetic, ) except ImportError: return "receipt not written: openadapt-types is older than 0.25" @@ -894,6 +918,11 @@ def receipt_after_run( return f"receipt not written: {exc.code}" except Exception as exc: # a receipt failure must never change the run's result return f"receipt not written: {type(exc).__name__}" + if synthetic: + return ( + f"receipt (demo key, synthetic app; it proves nothing about a real " + f"system): {Path(run_dir) / RECEIPT_FILE}" + ) return f"receipt: {Path(run_dir) / RECEIPT_FILE}" diff --git a/packages/flow/openadapt_flow/reward/worker.py b/packages/flow/openadapt_flow/reward/worker.py index 30cd36acf9..e2b26845b6 100644 --- a/packages/flow/openadapt_flow/reward/worker.py +++ b/packages/flow/openadapt_flow/reward/worker.py @@ -318,6 +318,7 @@ def __init__( *, oracle: OracleAdapter | None = None, token: str | None = None, + key_dir: Path | str | None = None, ) -> None: self.bundle = ( bundle if isinstance(bundle, RewardBundle) else RewardBundle.load(bundle) @@ -325,7 +326,11 @@ def __init__( self.data_dir = Path(data_dir).expanduser() self.data_dir.mkdir(parents=True, exist_ok=True) self._lock = threading.RLock() - self._key: Ed25519PrivateKey = load_or_create_private_key(self.data_dir) + # ``key_dir`` holds the signing key when it isn't the data dir: the + # seeded synthetic MockMed contract uses the demo key, so a client that + # pins this worker's key never accepts a reward about a synthetic app. + self.key_dir = Path(key_dir).expanduser() if key_dir else self.data_dir + self._key: Ed25519PrivateKey = load_or_create_private_key(self.key_dir) self.token = load_or_create_token(self.data_dir, token) self.fingerprint = fingerprint_of(self._key.public_key()) self.oracle: OracleAdapter = oracle or build_oracle( diff --git a/packages/flow/openadapt_flow/tutorial.py b/packages/flow/openadapt_flow/tutorial.py index 4a07994b5d..6f901afe55 100644 --- a/packages/flow/openadapt_flow/tutorial.py +++ b/packages/flow/openadapt_flow/tutorial.py @@ -732,7 +732,8 @@ def _run_tutorial_stages( from openadapt_flow.receipt_record import receipt_after_run # The signed receipt, for any outcome; the run summary below is separate. - receipt_after_run(run_dir) + # MockMed is synthetic, so the demo key signs it, never the Seal key. + receipt_after_run(run_dir, synthetic=True) if emit_receipt: # One rail, one rule: the shareable artifact is the SUCCESS rail, and diff --git a/packages/flow/tests/test_execute_demo_key.py b/packages/flow/tests/test_execute_demo_key.py new file mode 100644 index 0000000000..67dc6c81a9 --- /dev/null +++ b/packages/flow/tests/test_execute_demo_key.py @@ -0,0 +1,196 @@ +"""Execute and reward results about the bundled demo app use the demo key. + +``serve-execute --seed-mockmed`` admits synthetic MockMed workflows, and the +reference worker's in-process web replay drives only its own MockMed. A seal +for either, signed with the worker's key, would let a client that pins that +key (from ``/health``) take a result about a synthetic app as proof about a +real system. These seals are signed with a separate demo key instead, and +``serve-reward --seed-mockmed`` signs its synthetic contract the same way. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +pytest.importorskip("fastapi") +pytest.importorskip("openadapt_types.execute") + +from openadapt_types.execute import ( # noqa: E402 + EffectStrengthV1, + ExecuteTerminalOutcomeV1, +) + +from openadapt_flow.execute.dispatch import DispatchResult # noqa: E402 +from openadapt_flow.execute.keys import ( # noqa: E402 + load_or_create_private_key, + verify_signature, +) +from openadapt_flow.execute.models import AdmittedBundle, SelfSignedSealV1 # noqa: E402 +from openadapt_flow.mockmed.execute_seed import ( # noqa: E402 + MOCKMED_EFFECT_STRENGTH, + MOCKMED_QUALIFICATION_ID, + MOCKMED_WORKFLOW_DIGEST, + MOCKMED_WORKFLOW_VERSION, + mockmed_admissions, +) + +from .test_execute_ref import _client, _request # noqa: E402 + +REAL_ENVIRONMENT = "environment_real_app" + + +def _canonical(receipt: dict[str, Any]) -> bytes: + return json.dumps( + receipt, sort_keys=True, separators=(",", ":"), ensure_ascii=True + ).encode("utf-8") + + +def _seal(client, idempotency_key: str, **updates: object) -> SelfSignedSealV1: + accepted = client.post( + "/v1/executions", json=_request(idempotency_key=idempotency_key, **updates) + ).json() + status = client.get(f"/v1/executions/{accepted['execution_id']}").json() + receipt_id = status["evidence_receipt_id"] + return SelfSignedSealV1.model_validate( + client.get(f"/seals/{receipt_id}?format=json").json() + ) + + +def _real_admission() -> AdmittedBundle: + return AdmittedBundle( + qualification_id=MOCKMED_QUALIFICATION_ID, + workflow_version=MOCKMED_WORKFLOW_VERSION, + workflow_digest=MOCKMED_WORKFLOW_DIGEST, + environment_id=REAL_ENVIRONMENT, + minimum_effect_strength=MOCKMED_EFFECT_STRENGTH, + bundle_dir="/nonexistent/bundle", + ) + + +def _verified(request: Any, *, demo_app: bool) -> DispatchResult: + return DispatchResult( + outcome=ExecuteTerminalOutcomeV1.VERIFIED, + authorization_passed=True, + identity_passed=True, + postcondition_passed=True, + effect_passed=True, + minimum_effect_strength=EffectStrengthV1.INDEPENDENT_SYSTEM_OF_RECORD, + observed_effect_strength=EffectStrengthV1.INDEPENDENT_SYSTEM_OF_RECORD, + model_used=False, + external_network_used=False, + delivery_uncertain=False, + compensation_effect_verified=False, + workflow_digest=request.workflow_digest, + evidence_digest="sha256:" + "0" * 64, + demo_app=demo_app, + ) + + +def test_a_seeded_mockmed_seal_is_refused_by_the_pinned_worker_key(tmp_path: Path): + client, store = _client(tmp_path) + health = client.get("/health").json() + pinned = health["issuer_key_fingerprint"] + assert health["demo_key_fingerprint"] == store.demo_fingerprint != pinned + + seal = _seal(client, "caller_key_seeded001") + assert seal.receipt["outcome"] == "verified" + assert seal.issuer_key_fingerprint == store.demo_fingerprint + assert seal.issuer_key_fingerprint != pinned + canonical = _canonical(seal.receipt) + worker = load_or_create_private_key(tmp_path) + demo = load_or_create_private_key(tmp_path / "demo") + assert not verify_signature(worker.public_key(), canonical, seal.signature) + assert verify_signature(demo.public_key(), canonical, seal.signature) + + page = client.get(f"/seals/{seal.receipt['receipt_id']}").text + assert "Demo key." in page and "proves nothing about a real system" in page + + +def test_the_banner_lie_seal_is_demo_signed_too(tmp_path: Path): + client, store = _client(tmp_path) + _ok, lie = mockmed_admissions() + seal = _seal(client, "caller_key_bannerlie1", environment_id=lie.environment_id) + assert seal.receipt["outcome"] == "reconciliation_required" + assert seal.issuer_key_fingerprint == store.demo_fingerprint + + +def test_a_real_admission_is_signed_with_the_worker_key(tmp_path: Path): + def runner(admission, request, run_dir): + assert admission.synthetic is False + return _verified(request, demo_app=False) + + client, store = _client( + tmp_path, + seed_admissions=(*mockmed_admissions(), _real_admission()), + runner=runner, + ) + seal = _seal(client, "caller_key_realapp01", environment_id=REAL_ENVIRONMENT) + assert seal.issuer_key_fingerprint == store.fingerprint + page = client.get(f"/seals/{seal.receipt['receipt_id']}").text + assert "Demo key." not in page + headers = client.get(f"/seals/{seal.receipt['receipt_id']}?format=json").headers + assert "X-OpenAdapt-Demo" not in headers + + +def test_a_non_synthetic_admission_replayed_on_the_demo_app_is_demo_signed(tmp_path): + """The in-process replay sets demo_app; the seal follows the result.""" + + def runner(admission, request, run_dir): + return _verified(request, demo_app=True) + + client, store = _client( + tmp_path, + seed_admissions=(*mockmed_admissions(), _real_admission()), + runner=runner, + ) + seal = _seal(client, "caller_key_demoreplay", environment_id=REAL_ENVIRONMENT) + assert seal.issuer_key_fingerprint == store.demo_fingerprint + + +def test_a_synthetic_admission_is_demo_signed_whatever_the_runner_says(tmp_path): + """A custom runner that forgets demo_app can't put the worker key on MockMed.""" + + def runner(admission, request, run_dir): + return _verified(request, demo_app=False) + + client, store = _client(tmp_path, runner=runner) + seal = _seal(client, "caller_key_forgetful1") + assert seal.issuer_key_fingerprint == store.demo_fingerprint + + +def test_a_fault_on_a_synthetic_admission_is_demo_signed(tmp_path: Path): + def runner(admission, request, run_dir): + raise RuntimeError("boom after dispatch") + + client, store = _client(tmp_path, runner=runner) + seal = _seal(client, "caller_key_faulted001") + assert seal.receipt["outcome"] == "reconciliation_required" + assert seal.issuer_key_fingerprint == store.demo_fingerprint + + +def test_serve_reward_seed_mockmed_signs_with_the_demo_key(tmp_path, monkeypatch): + pytest.importorskip("openadapt_flow.reward.serve") + import openadapt_flow.reward.serve as serve_mod + from openadapt_flow.__main__ import main as flow_main + from openadapt_flow.execute.keys import fingerprint_of + + captured: dict[str, Any] = {} + + def fake_serve(worker, **kwargs): + captured["worker"] = worker + + monkeypatch.setattr(serve_mod, "serve", fake_serve) + data = tmp_path / "reward" + flow_main( + ["serve-reward", "--seed-mockmed", "--data-dir", str(data), "--port", "0"] + ) + worker = captured["worker"] + demo = fingerprint_of(load_or_create_private_key(data / "demo").public_key()) + own = fingerprint_of(load_or_create_private_key(data).public_key()) + assert worker.fingerprint == demo != own + assert worker.certificate is not None + assert worker.certificate.issuer_key_id == "self_signed:" + demo diff --git a/packages/flow/tests/test_execute_ref.py b/packages/flow/tests/test_execute_ref.py index fcbcfc59ac..b763c39d53 100644 --- a/packages/flow/tests/test_execute_ref.py +++ b/packages/flow/tests/test_execute_ref.py @@ -127,9 +127,12 @@ def test_post_mockmed_verified_receipt(tmp_path: Path) -> None: assert receipt.outcome is ExecuteTerminalOutcomeV1.VERIFIED assert receipt_response.headers["X-OpenAdapt-Issuer"] == "self_signed" assert receipt_response.headers["X-OpenAdapt-Production-Seal"] == "false" + # MockMed is synthetic: the demo key signs it, never the worker's key. assert ( - receipt_response.headers["X-OpenAdapt-Issuer-Fingerprint"] == store.fingerprint + receipt_response.headers["X-OpenAdapt-Issuer-Fingerprint"] + == store.demo_fingerprint ) + assert receipt_response.headers["X-OpenAdapt-Demo"] == "synthetic-demo-app" seal = SelfSignedSealV1.model_validate( client.get(f"/seals/{receipt.receipt_id}?format=json").json() ) @@ -137,8 +140,9 @@ def test_post_mockmed_verified_receipt(tmp_path: Path) -> None: assert seal.production_seal is False assert seal.meter_usd == 0.0 assert seal.verify_host == "local" - key = load_or_create_private_key(tmp_path) + key = load_or_create_private_key(tmp_path / "demo") assert fingerprint_of(key.public_key()) == seal.issuer_key_fingerprint + assert seal.issuer_key_fingerprint != store.fingerprint canonical = json.dumps( seal.receipt, sort_keys=True, separators=(",", ":"), ensure_ascii=True ).encode("utf-8") @@ -501,3 +505,5 @@ def fake_demo_replay(**_kw: Any) -> Any: ) assert called == ["demo"] assert result.outcome is ExecuteTerminalOutcomeV1.VERIFIED + # In process, the worker replays only on its bundled demo app. + assert result.demo_app is True diff --git a/packages/flow/tests/test_synthetic_receipts.py b/packages/flow/tests/test_synthetic_receipts.py new file mode 100644 index 0000000000..1d5efe1c42 --- /dev/null +++ b/packages/flow/tests/test_synthetic_receipts.py @@ -0,0 +1,161 @@ +"""Runs on a synthetic app are signed with the demo key, never the Seal key. + +A ``record/run/v1`` receipt has no field that marks a run as synthetic, and a +key's role comes from the receiver's registry. So a tutorial or ``replay +--demo-app`` receipt signed with this computer's Seal key would read like +proof about a real system to anyone who pins that key. These runs are signed +with a separate demo key: a receiver that pins this computer refuses them, +and one that pins the demo key (role ``demo``) gets a verdict that says it +checks only inside that demo. +""" + +from __future__ import annotations + +import base64 +import json +from pathlib import Path + +import pytest + +pytest.importorskip("cryptography") + +from cryptography.hazmat.primitives import serialization # noqa: E402 +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from openadapt_types import receipt as r # noqa: E402 + +from openadapt_flow import handoff as h # noqa: E402 +from openadapt_flow.offline_seal import demo_signer_for, signer_for # noqa: E402 +from openadapt_flow.receipt_record import ( # noqa: E402 + ReceiptRecordError, + local_registry, + receipt_after_run, + verify_run_receipt, + write_receipt_record, +) +from openadapt_flow.seal_keys import SoftwareSigner # noqa: E402 + +from .test_handoff import REPORT # noqa: E402 + + +@pytest.fixture() +def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + home = tmp_path / "seal-home" + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(home)) + monkeypatch.delenv("OPENADAPT_SEAL_KEY", raising=False) + monkeypatch.delenv("OPENADAPT_SEAL_KEY_FILE", raising=False) + monkeypatch.delenv("OPENADAPT_RECEIPT", raising=False) + return home + + +def _run(tmp_path: Path, name: str) -> Path: + run = tmp_path / name + run.mkdir() + (run / "report.json").write_text(json.dumps(REPORT, indent=2)) + return run + + +def _signer_ids(run: Path) -> list[str]: + envelope = json.loads((run / "receipt.json").read_text()) + return [s["keyid"] for s in envelope["signatures"]] + + +def _demo_registry(home: Path) -> list[r.RoleKey]: + entry = demo_signer_for(home).registry_entry() + return r.parse_registry( + {"schema": r.REGISTRY_SCHEMA, "keys": [{**entry, "role": "demo"}]} + ) + + +def test_a_synthetic_run_is_signed_by_the_demo_key_not_the_seal_key(home, tmp_path): + run = _run(tmp_path, "run-tutorial") + note = receipt_after_run(run, synthetic=True) + assert note is not None and "demo key" in note and "proves nothing" in note + + seal, demo = signer_for(home), demo_signer_for(home) + assert seal.key_id != demo.key_id + assert _signer_ids(run) == [demo.key_id] + + # A receiver that pins this computer's key refuses it. + refused = verify_run_receipt(run, local_registry(home)) + assert not refused.ok and refused.reason == "unknown_signer" + # One that pins the demo key gets a demo verdict. + shown = verify_run_receipt(run, _demo_registry(home)) + assert shown.ok and shown.demo + assert shown.signer_lines == (r.SIGNER_LINES["demo"],) + + +def test_a_synthetic_handoff_says_demo_and_is_refused_by_a_real_pin(home, tmp_path): + run = _run(tmp_path, "run-tutorial") + receipt_after_run(run, synthetic=True) + demo = demo_signer_for(home) + doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run), signer=demo) + + verdict = h.verify_handoff(doc, _demo_registry(home)) + assert verdict.ok and verdict.demo + assert any("demo key" in line for line in verdict.what_this_proves) + real = h.verify_handoff(doc, local_registry(home)) + assert real.reason == "unknown_signer" + + +def test_a_real_run_is_still_signed_by_the_seal_key(home, tmp_path): + run = _run(tmp_path, "run-real") + note = receipt_after_run(run) + assert note is not None and "demo" not in note + assert _signer_ids(run) == [signer_for(home).key_id] + checked = verify_run_receipt(run, local_registry(home)) + assert checked.ok and not checked.demo and checked.outcome == "VERIFIED" + + +def test_a_configured_seal_key_never_signs_a_synthetic_run(home, tmp_path, monkeypatch): + key = Ed25519PrivateKey.generate() + path = tmp_path / "configured.pem" + path.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + path.chmod(0o600) + monkeypatch.setenv("OPENADAPT_SEAL_KEY", f"file:{path}") + configured = signer_for(home) + assert configured.source == "file" + + run = _run(tmp_path, "run-tutorial") + receipt_after_run(run, synthetic=True) + assert _signer_ids(run) == [demo_signer_for(home).key_id] + assert configured.key_id not in _signer_ids(run) + + +def test_a_synthetic_run_refuses_any_other_signer(home, tmp_path): + run = _run(tmp_path, "run-tutorial") + other = SoftwareSigner(Ed25519PrivateKey.generate(), "generated") + with pytest.raises(ReceiptRecordError, match="demo key"): + write_receipt_record(run, signer=other, synthetic=True) + assert not (run / "receipt.json").exists() + + +def test_the_demo_key_is_stable_and_private(home): + first, again = demo_signer_for(home), demo_signer_for(home) + assert first.key_id == again.key_id + (pem,) = (home / "demo" / "keys").glob("*.pem") + assert pem.stat().st_mode & 0o077 == 0 + + +def test_a_demo_signature_beside_a_real_one_is_refused(home, tmp_path): + """A demo receipt can't be upgraded by adding this computer's signature.""" + run = _run(tmp_path, "run-tutorial") + receipt_after_run(run, synthetic=True) + envelope = json.loads((run / "receipt.json").read_text()) + seal = signer_for(home) + both = r.add_signature(envelope, seal.key_id, seal.sign) + registry = _demo_registry(home) + local_registry(home) + checked = r.verify_receipt( + both, + registry, + openings=json.loads((run / "receipt.private.json").read_text()), + ) + assert not checked.ok and checked.reason == "mixed_demo" + # The payload still names the run's own report: nothing else changed. + statement = json.loads(base64.b64decode(both["payload"])) + assert statement["subject"][0]["name"] == "report.json" diff --git a/packages/flow/tests/test_tutorial_demo_app_replay.py b/packages/flow/tests/test_tutorial_demo_app_replay.py index 0ee18ea9d7..c9866798ee 100644 --- a/packages/flow/tests/test_tutorial_demo_app_replay.py +++ b/packages/flow/tests/test_tutorial_demo_app_replay.py @@ -113,6 +113,12 @@ def test_tutorial_then_demo_app_replay_verifies_effects_in_empty_home( empty_home = tmp_path / "empty-home" empty_home.mkdir() monkeypatch.setenv("HOME", str(empty_home)) + for name in ( + "OPENADAPT_SEAL_HOME", + "OPENADAPT_SEAL_KEY", + "OPENADAPT_SEAL_KEY_FILE", + ): + monkeypatch.delenv(name, raising=False) tut_dir = tmp_path / "tut" assert cli_main(["tutorial", "--out", str(tut_dir)]) == 0 @@ -142,3 +148,20 @@ def test_tutorial_then_demo_app_replay_verifies_effects_in_empty_home( assert step_005.effect_verified is True assert len(step_005.effect_evidence) == 2 assert all(ev.final_verdict == "confirmed" for ev in step_005.effect_evidence) + + # Both runs were on MockMed, a synthetic app: the demo key signed their + # receipts, never this computer's Seal key, so a receiver that pins this + # computer refuses them. + import json + + from openadapt_flow.offline_seal import demo_signer_for, seal_home, signer_for + from openadapt_flow.receipt_record import local_registry, verify_run_receipt + + home = seal_home() + demo, seal = demo_signer_for(home), signer_for(home) + assert demo.key_id != seal.key_id + for run in (tut_dir / "run", run_dir): + envelope = json.loads(sealed_set.read_text(run / "receipt.json")) + assert [s["keyid"] for s in envelope["signatures"]] == [demo.key_id], run + checked = verify_run_receipt(run, local_registry(home)) + assert not checked.ok and checked.reason == "unknown_signer", run