diff --git a/.github/workflows/quickstart-lifecycle.yml b/.github/workflows/quickstart-lifecycle.yml index e18aa5f81f..a06860361d 100644 --- a/.github/workflows/quickstart-lifecycle.yml +++ b/.github/workflows/quickstart-lifecycle.yml @@ -81,4 +81,5 @@ jobs: runs/launcher-lifecycle/artifacts/**/REPORT.md runs/launcher-lifecycle/artifacts/**/report.json runs/launcher-lifecycle/artifacts/**/receipt.json + runs/launcher-lifecycle/artifacts/**/run-summary.json if-no-files-found: warn diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 4f0b980a02..51deb8354c 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -349,11 +349,13 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | -| Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | +| Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](packages/flow/docs/RECEIPTS.md); [vectors](packages/types/tests/vectors/record-run-v1/README.md) | +| Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md) | +| Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | | 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) | -| 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 | 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); 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) | +| 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) | | Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here. The quickstart offers its checked and its stopped run's Seals in one question, showing every public field and the full path to each file; `--show` prints the exact upload | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | | Run authorizations signed with the authorizer's GitHub SSH key (`ssh-keygen -Y sign`, after a summary of what it allows), naming the signing key and bound to the bundle digest, items, profile and Seal keys, and referenced by each Seal; the identity checked against github.com (`--live`) or pinned allowed signers; a pseudonymous operator profile counted from anchored Seals only | Released ([#1401](https://github.com/OpenAdaptAI/OpenAdapt/pull/1401)) | Unit tests with synthetic data; signatures checked against OpenSSH's `ssh-keygen` both ways | `openadapt-flow local-seal authorize`, `local-seal run --authorization`, `local-seal profile`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#run-authorizations-who-authorized-the-runs) | @@ -448,10 +450,11 @@ A test fails when a command has no file or this list is out of date. - `attach-seal` - `countersign` +- `encrypt` - `local-seal`: Offline Seals: customer-held keys, pinned verification, Rekor anchoring, run authorizations, operator profiles, public cards. - `receipt`: Signed write receipts (COSE, SCITT shape): check one offline against pinned keys and print what it did not check; export the public keys; anchor in Rekor. - `redact-report`: Strip session tokens from an existing run's report so it can be sealed again; the original stays local -- `seal` +- `seal`: Hidden alias of `encrypt` for one release. **Run on premises:** diff --git a/CHANGELOG.md b/CHANGELOG.md index c684b08f75..0f2363a264 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ ## Unreleased +### Features + +- **Receipts replace Seals.** A receipt is a signed, itemized record of one run: + what it changed, how each change was checked, and who signed it. It doesn't + grade the run. Every run, with any outcome, now writes `receipt.json` (a DSSE + envelope over an in-toto `record/run/v1` statement) and a private + `receipt.private.json`. `openadapt verify ` checks any + receipt, prints who signed it ("Signed by this computer", "Countersigned by + OpenAdapt Cloud", "Demo key: checks only in this demo"), fails closed on an + unknown key, schema or role, and still verifies every older format, labelled + "older format". `openadapt receipt verify|view|publish|unpublish` replaces + `openadapt seal`, which stays as a hidden alias. A receipt never holds + screenshots, typed values, URLs or page text. +- `openadapt flow encrypt` replaces `flow seal` (a hidden alias for one release). + Desktop's "Seal and encrypt version" is now "Encrypt version". +- The run summary (`run-receipt/v2`) moves from `receipt.json` to + `run-summary.json`, `.md` and `.png`. Older run folders still read. + ### Fixes - `openadapt quickstart` keeps the browser hidden and shows each step in the diff --git a/llms-full.txt b/llms-full.txt index d0e22706e7..a4d00e6819 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -784,11 +784,13 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | -| Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | +| Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECEIPTS.md); [vectors](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/tests/vectors/record-run-v1/README.md) | +| Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md) | +| Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | | 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) | -| 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 | 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); 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) | +| 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) | | Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here. The quickstart offers its checked and its stopped run's Seals in one question, showing every public field and the full path to each file; `--show` prints the exact upload | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | | Run authorizations signed with the authorizer's GitHub SSH key (`ssh-keygen -Y sign`, after a summary of what it allows), naming the signing key and bound to the bundle digest, items, profile and Seal keys, and referenced by each Seal; the identity checked against github.com (`--live`) or pinned allowed signers; a pseudonymous operator profile counted from anchored Seals only | Released ([#1401](https://github.com/OpenAdaptAI/OpenAdapt/pull/1401)) | Unit tests with synthetic data; signatures checked against OpenSSH's `ssh-keygen` both ways | `openadapt-flow local-seal authorize`, `local-seal run --authorization`, `local-seal profile`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#run-authorizations-who-authorized-the-runs) | @@ -883,10 +885,11 @@ A test fails when a command has no file or this list is out of date. - `attach-seal` - `countersign` +- `encrypt` - `local-seal`: Offline Seals: customer-held keys, pinned verification, Rekor anchoring, run authorizations, operator profiles, public cards. - `receipt`: Signed write receipts (COSE, SCITT shape): check one offline against pinned keys and print what it did not check; export the public keys; anchor in Rekor. - `redact-report`: Strip session tokens from an existing run's report so it can be sealed again; the original stays local -- `seal` +- `seal`: Hidden alias of `encrypt` for one release. **Run on premises:** diff --git a/openadapt/cli.py b/openadapt/cli.py index dc4d97c32d..ef74f5cae0 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -35,7 +35,7 @@ from contextlib import contextmanager from importlib import import_module from pathlib import Path -from typing import Optional +from typing import Callable, Optional import click @@ -133,6 +133,22 @@ def resolve_command(self, ctx, args): ): click.echo(group_help(ctx.command_path, root_name), nl=False) ctx.exit() + if ( + not ctx.resilient_parsing + and root_name == "verify" + and len(raw) > 1 + and not raw[1].startswith("-") + and raw[1] not in _verify_operations(self.commands.get("verify")) + and ( + Path(raw[1]).exists() + or "/" in raw[1] + or raw[1].endswith((".json", ".cbor")) + or _is_seal_link(raw[1]) + ) + ): + # `openadapt verify ` checks a receipt; the + # verify subcommands (serve, ledger, effect, ...) are never paths. + raw = ["receipt", "verify", *raw[1:]] args = translate(raw, set(self.commands), normalize) name = normalize(args[0]) if args and normalize else (args[0] if args else "") command = self.commands.get(name) @@ -2068,8 +2084,132 @@ def agent(command_ctx: click.Context) -> None: sys.exit(int(agent_main(list(command_ctx.args)) or 0)) +@main.command( + "receipt", + context_settings={ + "ignore_unknown_options": True, + "allow_extra_args": True, + "help_option_names": [], + }, +) +@click.pass_context +def receipt(command_ctx: click.Context) -> None: + """Check, view and share a run's receipt: `openadapt receipt verify `. + + A receipt is a signed, itemized record of one run: what it changed, how + each change was checked, and who signed it. It doesn't grade the run. + `verify` (also `openadapt verify`) prints who signed it and fails closed + on an unknown key, schema or role; older formats still verify. `view + RUN_DIR` writes the run's offline page and opens it. `publish [RUN_DIR]` + uploads the run's public card (counts, outcomes and digests only) after + you say yes; `unpublish RUN_DIR` takes it down. `keys pin` pins + OpenAdapt Cloud's keys after a person confirms them. + """ + _require_supported_python() + args = list(command_ctx.args) + if args[:1] in ([], ["-h"], ["--help"]): + click.echo(command_ctx.get_help()) + sys.exit(0 if args else 2) + if args[0] == "verify": + + def agent(argv: list[str]) -> int: + agent_main = _optional_engine_entrypoint( + command_ctx, ("openadapt_agent.seal_cli", "openadapt_agent.cli") + ) + if agent_main is None: + click.echo( + "Not verified: this openadapt-agent can't check that format." + ) + return 1 + return int(agent_main(argv) or 0) + + sys.exit(_verify_receipts(args[1:], agent)) + if args[0] == "view": + sys.exit(_view_sealed_runs(args[1:])) + if args[0] == "publish": + sys.exit(_publish_seal(args[1:])) + if args[0] == "unpublish": + sys.exit(_unpublish_seal(args[1:])) + if args[0] == "keys": + agent_main = _optional_engine_entrypoint( + command_ctx, ("openadapt_agent.seal_cli", "openadapt_agent.cli") + ) + if agent_main is None: + click.echo("Error: this openadapt-agent cannot pin keys.", err=True) + sys.exit(1) + sys.exit(int(agent_main(["seal", *args]) or 0)) + raise click.UsageError( + f"No such receipt command '{args[0]}'. Use verify, view, publish, " + "unpublish or keys." + ) + + +def _verify_operations(group: Optional[click.Command]) -> set[str]: + """`openadapt verify` subcommands and operations: never read as a path.""" + from openadapt.cli_tasks import FLOW_NAMES, NATIVE_ROUTES + + names = { + route.split()[1] + for route in FLOW_NAMES.values() + if route.startswith("verify ") and len(route.split()) > 1 + } + names |= {path[1] for path in NATIVE_ROUTES if path[0] == "verify"} + names |= set(getattr(group, "commands", {}) or {}) + return names + + +def _verify_receipts(argv: list[str], agent: Callable[[list[str]], int]) -> int: + """`openadapt verify [--keys FILE]`: any receipt, any format.""" + if not argv or any(arg in ("-h", "--help") for arg in argv): + click.echo( + "Usage: openadapt verify [--keys FILE]\n\n" + "Checks a receipt and prints who signed it. Fails closed on an " + "unknown key, schema or role. Older formats (seal.json, public " + "Seals, run summaries, write and tx receipts) still verify, " + "labelled older format. --keys pins an openadapt.receipt-keys/v1 " + "registry beside this computer's own key." + ) + return 0 if argv else 2 + target, rest = argv[0], argv[1:] + keys = None + if "--keys" in rest: + at = rest.index("--keys") + if at + 1 >= len(rest): + raise click.UsageError("--keys needs a FILE") + keys = Path(rest[at + 1]) + rest = rest[:at] + rest[at + 2 :] + try: + from openadapt.receipt_verify import verify_path + except ImportError: # pragma: no cover - ships with the launcher + click.echo("This install has no receipt verifier.", err=True) + return 1 + + try: + return verify_path( + target, + keys=keys, + extra=rest, + say=click.echo, + invoke_flow=_invoke_flow, + invoke_agent=agent, + legacy_folder=_verify_sealed_runs, + legacy_link=_verify_seal_link, + is_link=_is_seal_link, + ) + except ImportError: + click.echo( + "Not verified: this openadapt-flow or openadapt-types is too old to " + "check receipts. Upgrade with: pip install --upgrade openadapt" + ) + return 1 + except (OSError, ValueError) as exc: + click.echo(f"Not verified: {exc}") + return 1 + + @main.command( "seal", + hidden=True, context_settings={ "ignore_unknown_options": True, "allow_extra_args": True, @@ -2444,14 +2584,30 @@ def _is_seal_link(value: str) -> bool: return parse_link(value) is not None +REQUIRE_PINNED = "--require-pinned" + + def _verify_seal_link(url: str, extra: list[str]) -> int: """`openadapt seal verify `: fetch a hosted Seal and check it here.""" from openadapt.seal_publish import PublishError, check_link, urllib_transport + pinned = None + if extra == [REQUIRE_PINNED]: + # The unified verify: a link's key must be pinned here, like a file's. + from openadapt.receipt_verify import _registry + + def pinned(key_id: str) -> bool: + return any( + k.key_id == key_id and k.status == "active" for k in _registry(None) + ) + + extra = [] if extra: raise click.UsageError("A Seal link takes no other options.") try: - return check_link(url, transport=urllib_transport, say=click.echo) + return check_link( + url, transport=urllib_transport, say=click.echo, pinned=pinned + ) except PublishError as exc: click.echo(str(exc), err=True) return exc.exit_code diff --git a/openadapt/quickstart/__init__.py b/openadapt/quickstart/__init__.py index 1a060f6cbc..73d90e9e32 100644 --- a/openadapt/quickstart/__init__.py +++ b/openadapt/quickstart/__init__.py @@ -48,7 +48,7 @@ def next_steps( def build(outcome: Outcome) -> NextSteps: verify = None if outcome.seal is not None: - verify = hint(f"seal verify {quote(display_path(outcome.root))}") + verify = hint(f"verify {quote(display_path(outcome.root))}") if agent_serves_tutorial: agent = hint("agent serve --allow-run") else: @@ -57,9 +57,7 @@ def build(outcome: Outcome) -> NextSteps: ) return NextSteps( verify=verify, - verify_run=lambda run_dir: hint( - f"seal verify {quote(display_path(run_dir))}" - ), + verify_run=lambda run_dir: hint(f"verify {quote(display_path(run_dir))}"), record=hint( f"flow record --backend web --url {YOUR_APP_URL} --out my-task" ), diff --git a/openadapt/quickstart/engine.py b/openadapt/quickstart/engine.py index e3a3fee07c..f1f03c6aa7 100644 --- a/openadapt/quickstart/engine.py +++ b/openadapt/quickstart/engine.py @@ -746,6 +746,7 @@ def seal_broken(self, broken: BreakFacts) -> bool: except ImportError: return False seal_run(broken.run_dir, home=seal_home(), enqueue=False) + write_run_receipts([broken.run_dir]) return (broken.run_dir / "seal.json").is_file() def seal_pages( @@ -844,6 +845,8 @@ def seal_runs(runs: list[RunFacts]) -> Optional[SealFacts]: from openadapt_flow.offline_seal import seal_home, seal_run except ImportError: return None + # Every run gets a receipt, whatever its outcome; signing isn't grading. + write_run_receipts([run.run_dir for run in runs]) checked = [run for run in runs if run.checked] if not checked: return None @@ -856,6 +859,27 @@ def seal_runs(runs: list[RunFacts]) -> Optional[SealFacts]: return SealFacts(key_id=key_id, sealed=len(checked)) +def write_run_receipts(run_dirs: list[Path]) -> int: + """Write each run's ``receipt.json`` (record/run/v1); returns how many exist.""" + + try: + from openadapt_flow.offline_seal import seal_home, signer_for + from openadapt_flow.receipt_record import write_receipt_record + except ImportError: + return 0 + written = 0 + for run_dir in run_dirs: + if not (Path(run_dir) / "report.json").is_file(): + continue + try: + home = seal_home() + write_receipt_record(Path(run_dir), signer=signer_for(home), home=home) + except Exception: # noqa: BLE001 - a receipt failure never ends the finale + continue + written += 1 + return written + + def return_focus_to_terminal( *, visible: bool, platform: Optional[str] = None, environ=None, run=None ) -> bool: diff --git a/openadapt/quickstart/seal_link.py b/openadapt/quickstart/seal_link.py index a2bffcc50c..dc074b7626 100644 --- a/openadapt/quickstart/seal_link.py +++ b/openadapt/quickstart/seal_link.py @@ -46,7 +46,7 @@ def read_card(run_dir: Path) -> Optional[SealCard]: """The Seal card for ``run_dir``, or None when its files are missing or odd.""" try: - receipt = json.loads((run_dir / "receipt.json").read_text(encoding="utf-8")) + receipt = json.loads(_summary_path(run_dir).read_text(encoding="utf-8")) seal = json.loads((run_dir / "seal.json").read_text(encoding="utf-8")) except (OSError, ValueError): return None @@ -79,3 +79,9 @@ def read_card(run_dir: Path) -> Optional[SealCard]: "SealCard", "read_card", ] + + +def _summary_path(run_dir: Path) -> Path: + """``run-summary.json``; runs from before Flow 3.5 kept it as ``receipt.json``.""" + current = run_dir / "run-summary.json" + return current if current.is_file() else run_dir / "receipt.json" diff --git a/openadapt/quickstart/view.py b/openadapt/quickstart/view.py index 8407ed35df..cd6a73f221 100644 --- a/openadapt/quickstart/view.py +++ b/openadapt/quickstart/view.py @@ -334,6 +334,7 @@ def seal_rows(outcome: Outcome, card: Optional[SealCard], marks: Marks) -> list[ ) lines.append(f"ed25519 over report sha256 {card.short_digest}") if outcome.seal is not None: + lines.append("Signed by this computer") reports = "report" if outcome.seal.sealed == 1 else "reports" lines.append( f"key {outcome.seal.key_id}{dot}{outcome.seal.sealed} {reports} signed" @@ -348,8 +349,8 @@ def seal_lines(outcome: Outcome) -> list[tuple[str, str]]: if page is None: return [] return [ - ("Your Seal", str(display_path(page))), - ("See real Seals from OpenEMR runs", REAL_SEALS_URL), + ("Your receipt", str(display_path(page))), + ("See real receipts from OpenEMR runs", REAL_SEALS_URL), ] @@ -434,10 +435,10 @@ def more_lines(steps: NextSteps, root: Path, seal_page: Optional[Path]) -> list[ f"Try it on your own app: {steps.record}", ] if steps.verify: - lines.append(f"Check every Seal again: {steps.verify}") + lines.append(f"Check every receipt again: {steps.verify}") if seal_page is not None: - lines.append(f"Open your Seal (offline): {display_path(seal_page)}") - lines.append(f"See real Seals from OpenEMR runs: {REAL_SEALS_URL}") + lines.append(f"Open your receipt (offline): {display_path(seal_page)}") + lines.append(f"See real receipts from OpenEMR runs: {REAL_SEALS_URL}") lines.append(f"Read what each run did: {display_path(root)}, one REPORT.md per run") if steps.keep: lines.append(f"Keep it installed: {steps.keep}") @@ -675,14 +676,14 @@ def finale(self, outcome: Outcome, steps: NextSteps) -> None: self._say() card = seal_card(outcome) if outcome.seal is not None: - self._say(f"Your Seal: {card_outcome(card)}") + self._say(f"Your receipt: {card_outcome(card)}") for line in seal_rows(outcome, card, self.marks): self._say(f" {line}") page = outcome.seal_pages.verified if page is not None: self._say(f" Open it: {display_path(page)}") self._say(f" {seal_page_note(outcome)}") - self._say(f" Real Seals from OpenEMR runs: {REAL_SEALS_URL}") + self._say(f" Real receipts from OpenEMR runs: {REAL_SEALS_URL}") self._publish(outcome, steps) self._say() if all_clear(outcome): @@ -1258,7 +1259,7 @@ def _seal(self, outcome: Outcome, card: Optional[SealCard]) -> None: self.console.print( Panel( body, - title=f"[bold cyan] {self.marks.save} Your Seal [/]", + title=f"[bold cyan] {self.marks.save} Your receipt [/]", title_align="left", border_style="cyan", expand=False, @@ -1289,7 +1290,7 @@ def _seal(self, outcome: Outcome, card: Optional[SealCard]) -> None: if self.hyperlinks else REAL_SEALS_URL ) - links.add_row("[dim]Real Seals[/]", f"[cyan]{real}[/]") + links.add_row("[dim]Real receipts[/]", f"[cyan]{real}[/]") self.console.print(links) def finale(self, outcome: Outcome, steps: NextSteps) -> None: diff --git a/openadapt/receipt_verify.py b/openadapt/receipt_verify.py new file mode 100644 index 0000000000..a97d9cc265 --- /dev/null +++ b/openadapt/receipt_verify.py @@ -0,0 +1,387 @@ +"""``openadapt verify ``: check any receipt, of any format. + +A receipt (``record/run/v1``, ``receipt.json``) is checked against the pinned +key registry: this computer's key, Cloud keys pinned with ``openadapt receipt +keys pin``, and any ``--keys FILE``. The verifier prints who signed it and +fails closed on an unknown key, schema or role. + +Every older artifact still verifies, labelled "older format": +``local-seal/v1`` (``seal.json``), ``public-seal/v1``, ``seal-signature/v1`` +(a Cloud-signed Execute receipt), ``run-receipt/v2`` (the run summary), +``write-receipt/v1`` and ``tx-receipt/v1``-``v3``. + +Signing isn't grading: the outcome is printed as the run recorded it, and a +stopped run's receipt is still a valid receipt. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Callable, Optional, Sequence + +OLDER = "older format" + +Say = Callable[[str], None] + + +def _load_json(path: Path) -> Any: + from openadapt_types.receipt import loads_strict + + return loads_strict(path.read_text(encoding="utf-8")) + + +def _registry(keys: Optional[Path]) -> list[Any]: + from openadapt_flow.receipt_record import load_role_registry, local_registry + + extra = load_role_registry(keys) if keys is not None else [] + return local_registry(extra=extra) + + +def _describe(result: Any, say: Say, indent: str = " ") -> None: + for line in result.signer_lines: + say(f"{indent}{line}") + if not result.ok: + if result.detail: + say(f"{indent}({result.detail})") + return + if result.detail: + say(f"{indent}Note: {result.detail}") + statement = result.statement or {} + predicate = statement.get("predicate", {}) + reason = predicate.get("reason_code") + say( + f"{indent}Outcome: {result.outcome}" + + (f" ({reason})" if reason else "") + + ", as the run recorded it. A receipt doesn't grade the run." + ) + checks = predicate.get("checks", {}) + lines = predicate.get("lines", []) + say( + f"{indent}Writes: {len(lines)} " + f"({checks.get('lines_confirmed', 0)} confirmed, " + f"{checks.get('lines_refuted', 0)} refuted, " + f"{checks.get('lines_not_checked', 0)} not checked)" + ) + for name, value in sorted(result.disclosed.items()): + say(f"{indent}{name}: {value}") + + +def verify_record_file( + path: Path, + registry: Sequence[Any], + say: Say, + *, + openings: Optional[Path] = None, + run_folder: bool = False, +) -> int: + from openadapt_flow.receipt_record import PRIVATE_FILE, verify_run_receipt + from openadapt_types.receipt import verify_receipt + + # A run folder's receipt is always checked against the folder's report + # (missing evidence class: no report never verifies a run folder). + if path.name == "receipt.json" and ( + run_folder or (path.parent / "report.json").is_file() + ): + result = verify_run_receipt(path.parent, registry) + else: + sidecar = openings or path.with_name(PRIVATE_FILE) + doc = _load_json(path) + opened = ( + _load_json(sidecar) + if sidecar.is_file() and doc.get("schema") is None + else None + ) + result = verify_receipt(doc, registry, openings=opened) + say(f"{path} receipt (record/run/v1)") + _describe(result, say) + return 0 if result.ok else 1 + + +def _legacy_label(say: Say, path: Path, schema: str) -> None: + say(f"{path} {schema} ({OLDER})") + + +def verify_path( + target: str, + *, + keys: Optional[Path] = None, + extra: Sequence[str] = (), + say: Say = print, + invoke_flow: Callable[[list[str]], int], + invoke_agent: Callable[[list[str]], int], + legacy_folder: Callable[[Path, list[str]], int], + legacy_link: Callable[[str, list[str]], int], + is_link: Callable[[str], bool], +) -> int: + """Verify one target. Returns 0 only when every receipt in it verified.""" + if is_link(target): + say(f"{target} public-seal/v1 ({OLDER})") + if keys is not None: + # Dropped-requirement class: a hosted link is checked against the + # site's published keys, never a --keys registry, so refuse + # rather than ignore the pin. + say( + " Not verified: --keys can't pin a hosted link; download it and verify the file" + ) + return 1 + # Dropped-requirement class: a link's signer must be pinned here, + # exactly as a downloaded file's is. + return legacy_link(target, [*extra, "--require-pinned"]) + path = Path(target) + if path.is_dir(): + return _verify_folder( + path, keys=keys, extra=extra, say=say, legacy_folder=legacy_folder + ) + if not path.is_file(): + say(f"Not verified: {target} is not a file, folder or receipt link") + return 1 + data = path.read_bytes() + if not data.lstrip().startswith(b"{"): + return _verify_cose(path, data, extra=extra, say=say, invoke_flow=invoke_flow) + try: + doc = _load_json(path) + except ValueError: + say(f"{path} Not verified: malformed receipt (not JSON)") + return 1 + from openadapt_types.receipt import ( + OPENINGS_SCHEMA, + is_receipt_card, + is_receipt_envelope, + ) + + if is_receipt_envelope(doc) or is_receipt_card(doc): + return verify_record_file(path, _registry(keys), say) + schema = ( + (doc.get("schema") or doc.get("schema_version")) + if isinstance(doc, dict) + else None + ) + if schema == OPENINGS_SCHEMA: + say( + f"{path} is the receipt's private openings, not a receipt. " + "Verify receipt.json; keep this file private." + ) + return 1 + if schema == "openadapt.run-receipt/v2": + return _verify_run_summary(path, doc, say) + if schema == "openadapt.local-seal/v1": + # A Seal is over its run's report: check the folder it sits in. + _legacy_label(say, path, "local-seal/v1") + # Wrong-subject class: the folder check reads the folder's seal.json, + # so only that file may stand for it. + if path.name != "seal.json": + say(" Not verified: a Seal is checked as its run folder's seal.json") + return 1 + # Dropped-requirement class: --keys is added to, never replaces, the + # other options (--strict, --require-anchor, --require-timestamp). + legacy_extra = list(extra) + ([] if keys is None else ["--keys", str(keys)]) + return legacy_folder(path.parent, legacy_extra) + if isinstance(doc, dict) and {"card", "seal"} <= set(doc): + return _verify_public_seal(path, data, keys, say) + if isinstance(doc, dict) and "seal_signature" in doc: + _legacy_label(say, path, "seal-signature/v1") + return invoke_agent(["seal", "verify", str(path), *extra]) + say(f"{path} Not verified: unknown receipt format ({schema or 'no schema'})") + return 1 + + +def _verify_public_seal(path: Path, data: bytes, keys: Optional[Path], say: Say) -> int: + """``public-seal/v1``: its signature, and its key must be pinned here.""" + from openadapt_flow.public_seal import verify_public_seal + + _legacy_label(say, path, "public-seal/v1") + result = verify_public_seal(data) + if not result.ok: + say(f" Not verified: {result.reason}") + return 1 + pinned = {k.key_id: k for k in _registry(keys)} + key = pinned.get(str(result.key_id)) + if key is None: + say(" Not verified: unknown signer") + say(f" (key {result.key_id} isn't pinned here; pin it with --keys FILE)") + return 1 + if key.status != "active": + say(f" Not verified: the signing key was revoked at {key.revoked_at}") + return 1 + from openadapt_types.receipt import SIGNER_LINES + + say(" " + SIGNER_LINES[key.role].format(org=key.org or "the customer")) + return 0 + + +def _verify_folder( + folder: Path, + *, + keys: Optional[Path], + extra: Sequence[str], + say: Say, + legacy_folder: Callable[[Path, list[str]], int], +) -> int: + def signed(d: Path) -> bool: + return (d / "receipt.json").is_file() or (d / "seal.json").is_file() + + runs = ( + [folder] + if signed(folder) + else sorted(c for c in folder.iterdir() if c.is_dir() and signed(c)) + ) + with_receipt = [r for r in runs if _is_record(r / "receipt.json")] + # A receipt.json that is neither a receipt nor an older run summary is a + # broken receipt: it fails, and a seal.json beside it doesn't rescue it. + broken = [ + r + for r in runs + if r not in with_receipt + and (r / "receipt.json").is_file() + and not _is_summary(r / "receipt.json") + ] + sealed_only = [ + r + for r in runs + if r not in with_receipt and r not in broken and (r / "seal.json").is_file() + ] + unsigned = [r for r in runs if r not in with_receipt + broken + sealed_only] + if not runs: + say(f"Not verified: no receipt in {folder} (no receipt.json or seal.json)") + return 1 + failed = 0 + for run in broken: + say(f"{run / 'receipt.json'} Not verified: malformed receipt") + failed += 1 + for run in unsigned: + say(f"{run} Not verified: no receipt.json or seal.json") + failed += 1 + if with_receipt: + registry = _registry(keys) + for run in with_receipt: + failed += verify_record_file( + run / "receipt.json", registry, say, run_folder=True + ) + if sealed_only: + say(f"{len(sealed_only)} run(s) have only a seal.json ({OLDER})") + # --keys is added to, never replaces, the requested options. + legacy_extra = [*extra] + ([] if keys is None else ["--keys", str(keys)]) + for run in sealed_only: + failed += 1 if legacy_folder(run, legacy_extra) else 0 + total = len(runs) + say(f"{total - failed} of {total} verified") + return 0 if failed == 0 else 1 + + +def _is_record(path: Path) -> bool: + if not path.is_file(): + return False + try: + from openadapt_types.receipt import is_receipt_envelope + + return is_receipt_envelope(_load_json(path)) + except (OSError, ValueError): + return False + + +def _is_summary(path: Path) -> bool: + try: + doc = _load_json(path) + except (OSError, ValueError): + return False + return isinstance(doc, dict) and str(doc.get("schema_version", "")).startswith( + "openadapt.run-receipt/" + ) + + +def _verify_run_summary(path: Path, doc: Any, say: Say) -> int: + """``run-receipt/v2``: unsigned; check its own digest only.""" + _legacy_label(say, path, "run-receipt/v2") + try: + from openadapt_flow.receipt import RunReceipt + + RunReceipt.model_validate(doc) + except Exception as exc: # noqa: BLE001 - any failure is a refusal + say( + f" Not verified: the summary's digest doesn't match ({str(exc).splitlines()[0]})" + ) + return 1 + say(" Digest matches. Not signed: this older summary proves no signer.") + return 0 + + +def _verify_cose( + path: Path, + data: bytes, + *, + extra: Sequence[str], + say: Say, + invoke_flow: Callable[[list[str]], int], +) -> int: + try: + from openadapt_flow.receipt_log import decode_sign1 + from openadapt_flow.tx.receipt import TX_RECEIPT_CONTENT_TYPE + from openadapt_flow.write_receipt import CONTENT_TYPE + + _, headers, _, _, _ = decode_sign1(data) + from openadapt_flow.receipt_log import CTY + + content_type = headers.get(CTY) + except Exception: # noqa: BLE001 + say(f"{path} Not verified: unknown receipt format") + return 1 + if content_type == CONTENT_TYPE: + _legacy_label(say, path, "write-receipt/v1") + return invoke_flow(["receipt", "verify", str(path), *extra]) + if content_type == TX_RECEIPT_CONTENT_TYPE: + return _verify_tx(path, extra, say) + say(f"{path} Not verified: unknown receipt format") + return 1 + + +def _verify_tx(path: Path, extra: Sequence[str], say: Say) -> int: + """``tx-receipt/v1``-``v3``: needs the signer's public key (``--public-key``).""" + from openadapt_flow.tx.receipt import audit_legacy_tx_receipt, verify_tx_receipt + + args = list(extra) + if "--public-key" not in args or args.index("--public-key") + 1 >= len(args): + say(f"{path} tx-receipt ({OLDER})") + say( + " Not verified: unknown signer (pass --public-key FILE, the tx signer's key)" + ) + return 1 + key_path = Path(args[args.index("--public-key") + 1]) + log_dir = args[args.index("--log-dir") + 1] if "--log-dir" in args else None + from cryptography.hazmat.primitives import serialization + + raw = key_path.read_bytes() + try: + key: Any = serialization.load_pem_public_key(raw) + except ValueError: + key = raw + try: + payload = verify_tx_receipt(path, key, log_dir) + schema = str(payload.get("schema_version", "tx-receipt/v3")) + except ValueError as exc: + if "legacy_tx_receipt" not in str(exc): + say(f"{path} tx-receipt ({OLDER})") + say(f" Not verified: {exc}") + return 1 + try: + audit = audit_legacy_tx_receipt(path, key, log_dir) + except ValueError as again: + say(f"{path} tx-receipt ({OLDER})") + say(f" Not verified: {again}") + return 1 + schema = str(audit["source_schema"]) + say(f"{path} {schema.removeprefix('openadapt.')} ({OLDER})") + say(f" Signed by the tx signer key in {key_path}") + return 0 + + +def to_json(result: Any) -> str: + return json.dumps( + { + "ok": result.ok, + "reason": result.reason, + "signer_lines": list(result.signer_lines), + "outcome": result.outcome, + "demo": result.demo, + } + ) diff --git a/openadapt/seal_publish.py b/openadapt/seal_publish.py index ab06c18f86..e238e49233 100644 --- a/openadapt/seal_publish.py +++ b/openadapt/seal_publish.py @@ -274,9 +274,8 @@ def tutorial_provenance(run_dir: Path) -> Optional[str]: except OSError: pass for folder in folders: - try: - receipt = json.loads((folder / "receipt.json").read_text(encoding="utf-8")) - except (OSError, ValueError): + receipt = _read_run_summary(folder) + if receipt is None: continue if ( isinstance(receipt, dict) @@ -556,8 +555,12 @@ def check_link( transport: Transport, origin: Optional[str] = None, say: Callable[[str], None] = print, + pinned: Optional[Callable[[str], bool]] = None, ) -> int: - """Fetch a hosted Seal and check its signature here. 0 when valid.""" + """Fetch a hosted Seal and check its signature here. 0 when valid. + + With ``pinned``, the signing key must also be one this computer trusts + (active in its pinned registry), as a downloaded file's must.""" parsed = parse_link(url, origin) if parsed is None: say(f"not valid: not a hosted Seal link: {url}") @@ -595,6 +598,10 @@ def check_link( if not result.ok: say(f"not valid: {result.reason}") return 1 + if pinned is not None and not pinned(str(result.key_id)): + say(" Not verified: unknown signer") + say(f" (key {result.key_id} isn't pinned here, or was revoked)") + return 1 from openadapt_flow.offline_seal import seal_sha256 if data.get("seal_sha256") not in (None, seal_sha256(doc["seal"])): @@ -793,3 +800,16 @@ def show() -> None: "unpublish", "upload", ] + + +def _read_run_summary(folder: Path) -> Optional[dict]: + """The run summary from ``run-summary.json``, or an older ``receipt.json``.""" + for name in ("run-summary.json", "receipt.json"): + try: + data = json.loads((folder / name).read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + # Any summary, never the signed receipt (a DSSE envelope). + if isinstance(data, dict) and "payloadType" not in data: + return data + return None diff --git a/openadapt/seal_view/__init__.py b/openadapt/seal_view/__init__.py index 25153e478e..4afc3a761f 100644 --- a/openadapt/seal_view/__init__.py +++ b/openadapt/seal_view/__init__.py @@ -1,4 +1,4 @@ -"""Write a sealed run's Seal as one offline HTML page: ``RUN_DIR/seal.html``. +"""Write a signed run's receipt as one offline HTML page: ``RUN_DIR/seal.html``. The page is ``viewer.html`` (built from ``packages/seal-view``; Preact, the program map and the Seal inlined) with the run's own files embedded in it: @@ -52,7 +52,7 @@ def viewer_template() -> str: .read_text(encoding="utf-8") ) except (FileNotFoundError, ModuleNotFoundError) as exc: # pragma: no cover - raise SealViewError("this install has no Seal viewer (viewer.html)") from exc + raise SealViewError("this install has no receipt viewer (viewer.html)") from exc def _text(path: Path) -> Optional[str]: @@ -230,7 +230,7 @@ def render_page(data: Mapping[str, Any], template: Optional[str] = None) -> str: template = template if template is not None else viewer_template() if DATA_SLOT not in template: - raise SealViewError("the Seal viewer has no slot for the run's files") + raise SealViewError("the receipt viewer has no slot for the run's files") # JSON in a script element: escape "<" so no "" can end it early. payload = json.dumps(data, ensure_ascii=False, separators=(",", ":")) payload = payload.replace("<", "\\u003c") @@ -269,7 +269,8 @@ def write_seal_page( keys = local_keys() # A page forwarded to someone else stays a local check, not third-party proof. host = { - "trustWords": "checked against your computer's Seal key", + "trustWords": "checked against this computer's signing key", + "signer": "this_computer", **dict(host or {}), } if program is None or _digest_of(program) != report.get("bundle_content_digest"): @@ -279,7 +280,7 @@ def write_seal_page( keys=keys, program=program, about=about, - host={"unchanged": "The files on disk are unchanged.", **dict(host or {})}, + host=dict(host or {}), commands=commands, ) target = Path(out) if out else run_dir / PAGE_NAME diff --git a/openadapt/seal_view/viewer.html b/openadapt/seal_view/viewer.html index 206896af22..aad7654d39 100644 --- a/openadapt/seal_view/viewer.html +++ b/openadapt/seal_view/viewer.html @@ -1,29 +1,30 @@ - + - -OpenAdapt Seal -
- diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 59d0fa0d28..2c72ea20d8 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -3862,7 +3862,7 @@ def export_qualification_workflow(self, **params: Any) -> dict: if not qualified.get("certification_current"): raise ValueError("Certify this exact workflow version before export") if not qualified["graph"]["bundle"]["encrypted"]: - raise ValueError("Seal and encrypt this workflow version before export") + raise ValueError("Encrypt this workflow version before export") row = self.services.db.get_bundle(workflow_id) or {} exports = self.config.data_dir / "exports" staging = exports / f".{workflow_id}-{uuid.uuid4().hex}.zip" @@ -3915,7 +3915,7 @@ def deploy_qualification_workflow(self, **params: Any) -> dict: if not qualified.get("certification_current"): raise ValueError("Certify this exact workflow version before deployment") if not qualified["graph"]["bundle"]["encrypted"]: - raise ValueError("Seal and encrypt this workflow version before deployment") + raise ValueError("Encrypt this workflow version before deployment") if not self.services.flow_bridge.supports_command("push"): raise ValueError("The bundled Flow runtime does not support governed deployment") env = bundle_key_environment(workflow_id) diff --git a/packages/desktop/src/screens/QualificationLifecycle.test.tsx b/packages/desktop/src/screens/QualificationLifecycle.test.tsx index 50225342ed..2c387ba431 100644 --- a/packages/desktop/src/screens/QualificationLifecycle.test.tsx +++ b/packages/desktop/src/screens/QualificationLifecycle.test.tsx @@ -285,7 +285,7 @@ describe("Qualification lifecycle", () => { [ "the version is not sealed", { encrypted: false }, - "Seal and encrypt this version before you deploy it.", + "Encrypt this version before you deploy it.", ], [ "required capabilities are not covered", diff --git a/packages/desktop/src/screens/QualificationLifecycle.tsx b/packages/desktop/src/screens/QualificationLifecycle.tsx index 8ff3e525cf..87f9db8df4 100644 --- a/packages/desktop/src/screens/QualificationLifecycle.tsx +++ b/packages/desktop/src/screens/QualificationLifecycle.tsx @@ -63,7 +63,7 @@ function secretEnvironmentReference(name: string): string { // that this screen cannot see. function deployBlocker(project: QualificationProject): string { if (!project.graph.bundle.encrypted) { - return "Seal and encrypt this version before you deploy it."; + return "Encrypt this version before you deploy it."; } if (!project.capability_coverage?.satisfied) { return "Run cases that cover every required runner capability before you deploy."; @@ -787,7 +787,7 @@ export function QualificationLifecycle({ void artifactAction(CMD.SEAL_QUALIFICATION_WORKFLOW, "seal") } > - Seal and encrypt version + Encrypt version - )} + ) : null} {others.length ? (

- Also sealed here: + Also signed here: {others.map((o) => ( - {kind === 'stop' ? 'Sealed here: the run stopped at this step' : 'Sealed here: the save its read-backs prove'} + {kind === 'stop' ? 'Signed here: the run stopped at this step' : 'Signed here: the save OpenAdapt confirmed by reading the record back'} @@ -321,11 +321,18 @@ function Iris({ layers, phase, broken, tone }) { useEffect(() => { const root = box.current if (!root) return undefined - const css = getComputedStyle(root) - const color = (name, fallback) => css.getPropertyValue(name).trim() || fallback - const fills = broken - ? [color('--fail', '#ff4d6a'), color('--fail', '#ff4d6a'), color('--fail', '#ff4d6a')] - : [color('--t0', '#4cf0b8'), color('--soft', '#b9fbe5'), color('--t0', '#4cf0b8')] + // The colours come from the theme's roles, read again when the theme changes. + let fills = [] + let lit = '#ffffff' + const readColors = () => { + const css = getComputedStyle(root) + const color = (name, fallback) => css.getPropertyValue(name).trim() || fallback + fills = broken + ? [color('--fail', '#ff4d6a'), color('--fail', '#ff4d6a'), color('--fail', '#ff4d6a')] + : [color('--t0', '#4cf0b8'), color('--soft', '#b9fbe5'), color('--t0', '#4cf0b8')] + lit = color('--seal-ink', '#ffffff') + } + readColors() const alphas = broken ? [0.3, 0.26, 0.22] : [0.62, 0.45, 0.35] const paths = layers.map((layer) => layer.petals.map((p) => ({ path: new Path2D(p.d), at: p.at }))) const draw = (progress) => { @@ -343,20 +350,31 @@ function Iris({ layers, phase, broken, tone }) { for (const p of paths[l]) { const lift = progress == null ? 0 : Math.max(0, 1 - Math.abs(progress - p.at) * 6) ctx.globalAlpha = Math.min(1, alphas[l] + lift * 0.6) - ctx.fillStyle = lift > 0.3 ? '#ffffff' : fills[l] + ctx.fillStyle = lift > 0.3 ? lit : fills[l] ctx.fill(p.path) } }) } draw(null) - if (phase !== 'verify' || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return undefined + // A frame later: the page re-renders with the new theme first. + const themed = new MutationObserver(() => + requestAnimationFrame(() => { + readColors() + draw(null) + }) + ) + themed.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }) + if (phase !== 'verify' || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return () => themed.disconnect() const start = performance.now() let frame = requestAnimationFrame(function tick(now) { const k = (now - start) / SWEEP_MS draw(k > 1.1 ? null : k) if (k <= 1.1) frame = requestAnimationFrame(tick) }) - return () => cancelAnimationFrame(frame) + return () => { + cancelAnimationFrame(frame) + themed.disconnect() + } }, [layers, phase, broken, tone]) return (