diff --git a/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md b/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md index d59f7d9bb4..3ac972cf52 100644 --- a/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md +++ b/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md @@ -1 +1 @@ -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, signed (A2A 1.0 section 8.4, EdDSA JWS by the Seal key that signs receipts; no server if the key can't be opened), JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c, 2026-11-30, sandbox server with `--a2a-tck-scenarios`): 121 automated checks passed, 0 failed, 142 skipped (gRPC, push, cancel, auth scenarios), MUST 78.7% because the TCK counts skipped and manual checks as not passed ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)); a second implementation, the A2A JavaScript SDK 1.3.0, ran a workflow and verified a second key's handoff over JSON-RPC and HTTP+JSON and checked the card signature with independent JWS and RFC 8785 libraries, all on one computer ([benchmark/a2a_interop](packages/flow/benchmark/a2a_interop/README.md)); the card signature verified by the `a2a-sdk` verifier and refused when changed, unpinned or relabelled (the TCK leaves signing to manual checks) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, signed (A2A 1.0 section 8.4, EdDSA JWS by the Seal key that signs receipts; no server if the key can't be opened), JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, the card opened through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a strict-mode sealed run folder (stubbed Flow process, real sealed set and receipt hook) whose receipt and card go through the bridge's `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c, 2026-11-30, sandbox server with `--a2a-tck-scenarios`): 121 automated checks passed, 0 failed, 142 skipped (gRPC, push, cancel, auth scenarios), MUST 78.7% because the TCK counts skipped and manual checks as not passed ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)); a second implementation, the A2A JavaScript SDK 1.3.0, ran a workflow and verified a second key's handoff over JSON-RPC and HTTP+JSON and checked the card signature with independent JWS and RFC 8785 libraries, all on one computer ([benchmark/a2a_interop](packages/flow/benchmark/a2a_interop/README.md)); the card signature verified by the `a2a-sdk` verifier and refused when changed, unpinned or relabelled (the TCK leaves signing to manual checks) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | diff --git a/packages/agent/tests/test_handoff_at_rest_bridge.py b/packages/agent/tests/test_handoff_at_rest_bridge.py new file mode 100644 index 0000000000..57cfadba09 --- /dev/null +++ b/packages/agent/tests/test_handoff_at_rest_bridge.py @@ -0,0 +1,105 @@ +"""``get_handoff`` through the bridge for a run encrypted at rest (strict mode). + +The Flow process is stubbed, but it leaves what a strict run leaves: a sealed +run folder whose report is ciphertext on disk, and the receipt written by the +same hook the CLI calls after a run (``receipt_after_run``). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +pytest.importorskip("cryptography") + +from conftest import FlowCliStub # noqa: E402 +from test_handoff_e2e import WRITE_REPORT_RESULTS, _registry # noqa: E402 + +import openadapt_agent.runner as runner_mod # noqa: E402 +from openadapt_flow import at_rest, crypto, sealed_set # noqa: E402 +from openadapt_flow import handoff as h # noqa: E402 +from openadapt_flow.agent.bridge import AgentBridge # noqa: E402 +from openadapt_flow.agent.handoff_tools import HandoffTools # noqa: E402 +from openadapt_flow.offline_seal import signer_for # noqa: E402 +from openadapt_flow.receipt_record import receipt_after_run # noqa: E402 + + +class SealedRunStub(FlowCliStub): + """`openadapt-flow run` under strict at rest, stubbed: a sealed run folder.""" + + def __init__(self, env: dict[str, str], **kwargs): + super().__init__(**kwargs) + self.env = env + self.notes: list[str | None] = [] + + def __call__(self, cmd, *args, **kwargs): + import subprocess + + self.calls.append(list(cmd)) + run_dir = Path(cmd[cmd.index("--run-dir") + 1]) + with sealed_set.writing(run_dir, "run", crypto.resolve_key(None)): + sealed_set.write_text(run_dir / "report.json", json.dumps(self.report)) + self.notes.append(receipt_after_run(run_dir, env=self.env)) + return subprocess.CompletedProcess(cmd, self.exit_code, stdout="", stderr="") + + +@pytest.fixture() +def strict_env(tmp_path, monkeypatch): + for name in ( + at_rest.OPT_OUT_ENV, + at_rest.ENCRYPT_ENV, + crypto.ENV_KEY, + sealed_set.RECORDING_ENV_KEY, + "OPENADAPT_POLICY", + "OPENADAPT_RECEIPT", + "OPENADAPT_SEAL_KEY", + ): + monkeypatch.delenv(name, raising=False) + env = { + "OPENADAPT_SEAL_HOME": str(tmp_path / "seal-home"), + at_rest.HOME_ENV: str(tmp_path / "at-rest-home"), + at_rest.MODE_ENV: "strict", + } + for key, value in env.items(): + monkeypatch.setenv(key, value) + at_rest._reset_for_tests() + yield env + at_rest._reset_for_tests() + + +@pytest.mark.parametrize("public", [False, True]) +def test_a_strict_run_hands_off_its_receipt_through_the_bridge( + monkeypatch, bundles_root, runner_config, success_report, strict_env, public +): + signer = signer_for(Path(strict_env["OPENADAPT_SEAL_HOME"])) + report = dict( + success_report, + results=WRITE_REPORT_RESULTS, + started_at="2026-11-21T01:02:03Z", + change_ledger=[], + ) + stub = SealedRunStub(strict_env, exit_code=0, report=report) + monkeypatch.setattr(runner_mod, "_run_flow_process", stub) + bridge = AgentBridge(bundles_root, runner_config, allow_run=True, mode="production") + bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer) + + workflow = next(iter(bridge.catalog)) + result = bridge.dispatch( + "run_workflow", + {"workflow": workflow, "inputs": {"note": "x"}, "request_id": "strict-0001"}, + ) + assert stub.notes and str(stub.notes[0]).startswith("receipt:"), stub.notes + run_dir = Path(runner_config.runs_dir) / result["run_id"] + assert sealed_set.is_sealed(run_dir) + assert not (run_dir / "report.json").exists() + + doc = bridge.dispatch("get_handoff", {"run_id": result["run_id"], "public": public}) + verdict = h.verify_handoff(doc, _registry(signer)) + assert verdict.ok, verdict.to_dict() + assert verdict.payload["bound"] is True + # The receipt says what the run's report says; never upgraded. + assert verdict.outcome == "VERIFIED" + assert doc["payload"]["content"]["outcome"] == result["outcome"] + sealed_set.open_set(run_dir).verify_all() diff --git a/packages/agent/tests/test_handoff_e2e.py b/packages/agent/tests/test_handoff_e2e.py index 4b03a2775d..22479f7f18 100644 --- a/packages/agent/tests/test_handoff_e2e.py +++ b/packages/agent/tests/test_handoff_e2e.py @@ -18,6 +18,7 @@ import asyncio import base64 +import contextlib import hashlib import json import socket @@ -56,6 +57,20 @@ "ok": True, "effect_verified": True, "postconditions_ok": True, + # A write is confirmed only with a declared effect contract and its + # evidence (as in Flow's tests/test_handoff.py); without them the + # receipt says UNKNOWN (effect_not_declared). + "effect_contract_hashes": ["sha256:" + "a" * 64], + "effect_evidence": [ + { + "effect_contract_hash": "sha256:" + "a" * 64, + "substrate": "api", + "initial_verdict": "confirmed", + "final_verdict": "confirmed", + "observed_effect": "present", + "verification_tier": 1, + } + ], }, ] @@ -91,7 +106,13 @@ def signer(): @pytest.fixture() def bridge(monkeypatch, bundles_root, runner_config, success_report, signer): - report = dict(success_report, results=WRITE_REPORT_RESULTS, started_at="2026-11-21T01:02:03Z") + report = dict( + success_report, + results=WRITE_REPORT_RESULTS, + started_at="2026-11-21T01:02:03Z", + # No change ledger means unknown write coverage: the receipt says UNKNOWN. + change_ledger=[], + ) monkeypatch.setattr( runner_mod, "_run_flow_process", ReceiptWritingStub(signer, exit_code=0, report=report) ) @@ -108,6 +129,13 @@ def _free_port() -> int: @pytest.fixture() def a2a_url(bridge): + with _serve_a2a(bridge) as url: + yield url + + +@contextlib.contextmanager +def _serve_a2a(bridge): + """Serve ``bridge`` over A2A on a free local port; yield its base URL.""" config = a2a_server.A2AConfig(port=_free_port()) server = uvicorn.Server( uvicorn.Config( @@ -241,12 +269,7 @@ async def scenario(): handoff, good, tampered, swapped = asyncio.run(scenario()) assert good["integrity"] == "intact" assert good["signer_roles"] == ["this_computer"] - # The stubbed run has no read-back, so its receipt says UNKNOWN (receipts - # say VERIFIED only on a level 3 or 4 read). The verdict copies the - # receipt's outcome and never upgrades it. - statement = json.loads(base64.b64decode(handoff["receipt"]["payload"])) - assert statement["predicate"]["outcome"] == "UNKNOWN" - assert good["outcome"] == "UNKNOWN" + assert good["outcome"] == "VERIFIED" assert good["what_this_proves"][0] == h.WHAT_A_SIGNATURE_PROVES assert tampered["integrity"] == "refused" and tampered["reason"] == "bad_signature" assert good["payload"]["bound"] is True diff --git a/packages/agent/tests/test_handoff_sandbox.py b/packages/agent/tests/test_handoff_sandbox.py new file mode 100644 index 0000000000..685b0db32b --- /dev/null +++ b/packages/agent/tests/test_handoff_sandbox.py @@ -0,0 +1,218 @@ +"""Sandbox runs never carry a receipt, over MCP or A2A, and say why. + +A ``record/run/v1`` receipt has no field that marks a run as synthetic, and a +receiver's own key registry, not the signed statement, decides what a key +means. A receipt for a sandbox run, signed with this computer's key, would +read like proof about a real system, so ``get_handoff`` refuses sandbox runs +before it reads any run folder. +""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path + +import pytest + +pytest.importorskip("a2a.server.routes") +pytest.importorskip("uvicorn") +pytest.importorskip("cryptography") + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from openadapt_types import receipt as r # noqa: E402 +from test_handoff_e2e import ( # noqa: E402 + WRITE_REPORT_RESULTS, + _registry, + _result_from, + _send, + _serve_a2a, +) + +from openadapt_agent.bridge import AgentBridge, BridgeError # noqa: E402 +from openadapt_agent.runner import RunnerConfig # noqa: E402 +from openadapt_agent.sandbox import SANDBOX_WORKFLOW, SandboxEngine # noqa: E402 +from openadapt_flow import handoff as h # noqa: E402 +from openadapt_flow.agent.handoff_tools import ( # noqa: E402 + NO_PROVENANCE, + SANDBOX_NO_RECEIPT, + HandoffTools, +) +from openadapt_flow.receipt_record import write_receipt_record # noqa: E402 +from openadapt_flow.seal_keys import SoftwareSigner # noqa: E402 + + +@pytest.fixture() +def signer(): + return SoftwareSigner(Ed25519PrivateKey.generate(), "generated") + + +@pytest.fixture() +def sandbox_bridge(tmp_path, signer): + runs = tmp_path / "sandbox" + engine = SandboxEngine(runs, engine="simulated") + bridge = AgentBridge(None, RunnerConfig(runs_dir=runs), sandbox=engine, mode="sandbox") + bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer) + yield bridge + engine.close() + + +def _run(bridge, request_id): + return bridge.dispatch( + "run_workflow", + { + "workflow": SANDBOX_WORKFLOW, + "inputs": {"note": "Synthetic follow-up"}, + "request_id": request_id, + }, + ) + + +def _plant_receipt(run_dir: Path, signer) -> None: + """A real signed receipt in a sandbox run's folder (no sandbox path writes one).""" + run_dir.mkdir(parents=True, exist_ok=True) + report = { + "workflow_name": SANDBOX_WORKFLOW, + "execution_outcome": "VERIFIED", + "run_id": run_dir.name, + "started_at": "2026-11-21T01:02:03Z", + "change_ledger": [], + "results": WRITE_REPORT_RESULTS, + } + (run_dir / "report.json").write_text(json.dumps(report)) + write_receipt_record(run_dir, signer=signer, flow_version="3.4.0") + assert (run_dir / r.RECEIPT_FILE).is_file() + + +@pytest.mark.parametrize("public", [False, True]) +def test_a_sandbox_run_never_carries_a_receipt_and_says_why(sandbox_bridge, signer, public): + result = _run(sandbox_bridge, "sandbox-handoff-1") + assert result["mode"] == "sandbox" and result["outcome"] == "done" + # Even with a real signed receipt in the run's folder, the result never + # travels with one. + _plant_receipt(Path(sandbox_bridge.runner_config.runs_dir) / result["run_id"], signer) + assert "get_handoff" in [spec.name for spec in sandbox_bridge.list_tool_specs()] + with pytest.raises(BridgeError) as caught: + sandbox_bridge.dispatch("get_handoff", {"run_id": result["run_id"], "public": public}) + assert SANDBOX_NO_RECEIPT in str(caught.value) + + +def test_a2a_sandbox_artifact_says_why_it_has_no_receipt(sandbox_bridge): + with _serve_a2a(sandbox_bridge) as url: + task = asyncio.run( + _send( + url, + { + "skill": SANDBOX_WORKFLOW, + "inputs": {"note": "Synthetic follow-up"}, + "request_id": "sandbox-a2a-0001", + }, + ) + ) + assert _result_from(task)["mode"] == "sandbox" + parts = [part for artifact in task.artifacts for part in artifact.parts] + assert not [p for p in parts if p.HasField("raw") and p.media_type == h.MEDIA_TYPE] + texts = [p.text for p in parts if p.HasField("text")] + assert any(SANDBOX_NO_RECEIPT in text for text in texts), texts + + +# -- provenance comes from the stored record, not the server's current mode -- + + +def _production_bridge(bundles_root, runs, signer): + bridge = AgentBridge( + bundles_root, RunnerConfig(runs_dir=runs), allow_run=True, mode="production" + ) + bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer) + return bridge + + +def _orphan(bridge, run_id, mode): + """A run record left running by a process that is gone (pid None).""" + store = bridge.service.store + record = store.new_record( + request_id=f"req-{run_id}", workflow=SANDBOX_WORKFLOW, mode="sandbox", run_id=run_id + ) + if mode is None: + del record["mode"] + else: + record["mode"] = mode + record["pid"] = None + store.write(record) + return record + + +@pytest.mark.parametrize("public", [False, True]) +def test_a_finished_sandbox_run_reopened_under_production_never_carries_a_receipt( + sandbox_bridge, bundles_root, signer, public +): + result = _run(sandbox_bridge, "sandbox-restart-1") + runs = Path(sandbox_bridge.runner_config.runs_dir) + _plant_receipt(runs / result["run_id"], signer) + production = _production_bridge(bundles_root, runs, signer) + reopened = production.dispatch("get_run", {"run_id": result["run_id"], "wait_seconds": 0}) + assert reopened["mode"] == "sandbox" + with pytest.raises(BridgeError) as caught: + production.dispatch("get_handoff", {"run_id": result["run_id"], "public": public}) + assert SANDBOX_NO_RECEIPT in str(caught.value) + + +def test_an_interrupted_sandbox_run_recovered_under_production_keeps_its_mode( + bundles_root, tmp_path, signer +): + runs = tmp_path / "runs" + production = _production_bridge(bundles_root, runs, signer) + run_id = "run-sandbox-orphan-1" + _orphan(production, run_id, "sandbox") + # A genuine receipt for this run's own report sits in its folder. + _plant_receipt(runs / run_id, signer) + # Restarted under production: get_run rebuilds the interrupted result + # from the stored record, which ran in sandbox mode. + result = production.dispatch("get_run", {"run_id": run_id, "wait_seconds": 0}) + assert result["reason"] == "interrupted" and result["mode"] == "sandbox" + stored = production.service.store.read(run_id) + assert stored["state"] == "finished" and stored["mode"] == "sandbox" + assert stored["result"]["mode"] == "sandbox" + with pytest.raises(BridgeError) as caught: + production.dispatch("get_handoff", {"run_id": run_id}) + assert SANDBOX_NO_RECEIPT in str(caught.value) + + +@pytest.mark.parametrize("mode", [None, "staging"]) +def test_a_run_record_without_a_known_mode_never_carries_a_receipt( + bundles_root, tmp_path, signer, mode +): + runs = tmp_path / "runs" + production = _production_bridge(bundles_root, runs, signer) + run_id = "run-no-provenance-1" + _orphan(production, run_id, mode) + _plant_receipt(runs / run_id, signer) + production.dispatch("get_run", {"run_id": run_id, "wait_seconds": 0}) + stored = production.service.store.read(run_id) + assert stored["state"] == "finished" and stored.get("mode") == mode + with pytest.raises(BridgeError) as caught: + production.dispatch("get_handoff", {"run_id": run_id}) + assert NO_PROVENANCE in str(caught.value) + + +@pytest.mark.parametrize( + "record", + [ + None, + {"state": "running", "mode": "production"}, + {"state": "finished", "mode": "attended"}, # disagrees with the result + {"state": "finished"}, + ], +) +def test_get_handoff_needs_a_finished_record_whose_mode_matches(tmp_path, signer, record): + run = tmp_path / "run-direct-1" + _plant_receipt(run, signer) + with pytest.raises(BridgeError) as caught: + HandoffTools(registry=_registry(signer), signer=signer).get( + run.name, + public=False, + result_for=lambda _run_id: {"outcome": "done", "mode": "production"}, + run_dir_for=lambda _run_id: run, + record_for=lambda _run_id: record, + ) + assert NO_PROVENANCE in str(caught.value) diff --git a/packages/flow/docs/A2A.md b/packages/flow/docs/A2A.md index 3afcce8506..f1d95276db 100644 --- a/packages/flow/docs/A2A.md +++ b/packages/flow/docs/A2A.md @@ -85,16 +85,36 @@ says nothing about any run. That is what the run's receipt is for. ## When a run has no receipt Flow writes `receipt.json` after every `openadapt-flow run` and `replay`. -Three kinds of run have none: - -- **Sandbox runs.** `--mode sandbox` runs on a synthetic app, not through - the Flow CLI. -- **Encrypted runs.** With `OPENADAPT_FLOW_AT_REST=strict`, the run folder is - encrypted at rest and Flow writes no receipt. +Two kinds of run have none: + +- **Sandbox runs.** `--mode sandbox` runs on MockMed, a synthetic app, not + through the Flow CLI. `get_handoff` refuses any result whose `mode` is + `sandbox`, before it reads the run folder. A `record/run/v1` receipt has no + field that marks a run as synthetic, and the receiver's key registry, not + the signed statement, decides what a key means. A sandbox receipt signed + with this computer's key would therefore read like proof about a real + system. The result's `mode: "sandbox"` is the marker instead. - **Runs with receipts off.** Runs with `OPENADAPT_RECEIPT=off`. For these, `get_handoff` refuses, and the A2A artifact carries the run result -without a handoff. +with a text part that says why, and no handoff. + +Encrypted runs do have one. With `OPENADAPT_FLOW_AT_REST=strict` the run +folder is encrypted at rest, and the receipt is still written: `receipt.json` +stays plaintext beside the run, and the public card (`receipt.card.json`) is +sealed with it ([phi_at_rest.md](phi_at_rest.md), "Receipts"). `get_handoff` +reads `receipt.json` as it is. With `public`, it opens the card through the +run's sealed set, in memory. Either way it attaches the receipt only when the +receipt's signed `report.json` digest matches this run's own report, read +through the sealed set; a receipt from another run, even one signed by the +same key, is refused. That check needs the at-rest key, so without it +`get_handoff` refuses. It writes nothing. The signed statement is the same +as for a plaintext run of the same report. + +Whether a run may carry a receipt at all is decided from its stored run +record: the record must be finished and name `attended` or `production` as +the mode it ran under. A runs folder reopened under another mode keeps each +run's original mode, and a record with no known mode gets no receipt. ## Same rules as MCP diff --git a/packages/flow/docs/HANDOFF_RECEIPTS.md b/packages/flow/docs/HANDOFF_RECEIPTS.md index 4acc9e431e..0b2e9dc3bd 100644 --- a/packages/flow/docs/HANDOFF_RECEIPTS.md +++ b/packages/flow/docs/HANDOFF_RECEIPTS.md @@ -157,7 +157,9 @@ These rules apply to the verdict: `openadapt agent serve --handoffs` adds two read-only tools: - **`get_handoff {run_id}`** returns the run's public result as the payload, - with its receipt attached. + with its receipt attached. For an encrypted run it opens the public card + through the run's sealed set. It refuses sandbox runs and runs without a receipt + ([A2A.md](A2A.md), "When a run has no receipt"). - **`verify_handoff {handoff}`** returns the verdict, checked against the server's pinned keys. diff --git a/packages/flow/openadapt_flow/agent/bridge.py b/packages/flow/openadapt_flow/agent/bridge.py index feb0a20bff..8d34fe3f79 100644 --- a/packages/flow/openadapt_flow/agent/bridge.py +++ b/packages/flow/openadapt_flow/agent/bridge.py @@ -880,6 +880,7 @@ def _handoff_dispatch(self, name: str, arguments: dict) -> dict: "get_run", {"run_id": run_id, "wait_seconds": 0} ), run_dir_for=self._safe_run_dir, + record_for=self.service.store.read, ) def _list_workflows(self) -> dict: diff --git a/packages/flow/openadapt_flow/agent/handoff_tools.py b/packages/flow/openadapt_flow/agent/handoff_tools.py index 7ad1f6a567..d662dcea4c 100644 --- a/packages/flow/openadapt_flow/agent/handoff_tools.py +++ b/packages/flow/openadapt_flow/agent/handoff_tools.py @@ -13,7 +13,7 @@ from __future__ import annotations from pathlib import Path -from typing import Any, Callable, Optional, Sequence +from typing import Any, Callable, Mapping, Optional, Sequence _READ_ONLY = { "readOnlyHint": True, @@ -25,6 +25,25 @@ HANDOFF_TOOLS = ("get_handoff", "verify_handoff") +#: Why a sandbox run never carries a receipt. A ``record/run/v1`` receipt has +#: no field that marks a run as synthetic, and the receiver's key registry, +#: not the signed statement, decides a key's role. So a receipt for a sandbox +#: run, signed with this computer's key, would read like proof about a real +#: system. Sandbox results say ``mode: "sandbox"`` instead. +SANDBOX_NO_RECEIPT = ( + "sandbox runs carry no receipt: they run on a synthetic app, and a signed " + "receipt has no field that marks a run as synthetic, so it could pass for " + "proof about a real system. The result's mode says sandbox." +) + +#: The modes whose runs may carry a receipt, read from the run's stored +#: record (the mode it ran under), never from this server's current mode. +RECEIPT_MODES = ("attended", "production") +NO_PROVENANCE = ( + "the run's stored record doesn't show a finished run in attended or " + "production mode, so its receipt isn't attached" +) + class HandoffTools: """The handoff tool surface over one bridge's runs folder.""" @@ -131,13 +150,36 @@ def get( public: bool, result_for: Callable[[str], dict[str, Any]], run_dir_for: Callable[[str], Path], + record_for: Callable[[str], Optional[Mapping[str, Any]]], ) -> dict[str, Any]: + """The run's result with its receipt attached, or a refusal. + + ``record_for`` returns the run's stored record. Whether a receipt may + travel is decided from that record's own mode, after ``result_for`` + has settled the run: a sandbox, unfinished or unlabelled record never + gets one, whatever mode this server runs in now. + """ from openadapt_flow.agent.bridge import BridgeError from openadapt_flow.handoff import HandoffError, make_handoff, receipt_for_run result = result_for(run_id) + if result.get("mode") == "sandbox" or result.get("sandbox"): + # Checked before any run folder is read, so a sandbox run that + # somehow has a receipt file still never travels with one. + raise BridgeError(f"no handoff for this run: {SANDBOX_NO_RECEIPT}") if result.get("outcome") == "running": raise BridgeError("the run is still running; it has no receipt yet") + record = record_for(run_id) + if not isinstance(record, Mapping): + raise BridgeError(f"no handoff for this run: {NO_PROVENANCE}") + if record.get("mode") == "sandbox": + raise BridgeError(f"no handoff for this run: {SANDBOX_NO_RECEIPT}") + if ( + record.get("state") != "finished" + or record.get("mode") not in RECEIPT_MODES + or record.get("mode") != result.get("mode") + ): + raise BridgeError(f"no handoff for this run: {NO_PROVENANCE}") try: receipt = receipt_for_run(run_dir_for(run_id), public=public) return make_handoff( diff --git a/packages/flow/openadapt_flow/agent/service.py b/packages/flow/openadapt_flow/agent/service.py index bf385391d8..00468fb61c 100644 --- a/packages/flow/openadapt_flow/agent/service.py +++ b/packages/flow/openadapt_flow/agent/service.py @@ -26,7 +26,7 @@ from openadapt_flow.agent.approval import report_approval, waiting_for_person from openadapt_flow.agent.cards import WorkflowCard, coerce_inputs, input_problems -from openadapt_flow.agent.contract import REASONS, build_result, reason_for_run +from openadapt_flow.agent.contract import MODES, REASONS, build_result, reason_for_run from openadapt_flow.agent.runner import FlowRunner, is_safe_run_id from openadapt_flow.agent.runs import RunStore, pid_alive from openadapt_flow.readback_ladder import checked_how_from_report @@ -295,12 +295,19 @@ def __init__( def _result( self, reason: str, record: Mapping[str, Any], **extra: Any ) -> dict[str, Any]: + # A result says the mode its run was recorded under, never this + # server's: a runs folder reopened under another mode (an interrupted + # run rebuilt on restart, a reviewed run refreshed) keeps its sandbox + # provenance. Only a record with no recognized mode falls back to this + # server's mode for display; get_handoff decides from the stored + # record and refuses one whose mode is missing or unknown. + stored_mode = record.get("mode") return build_result( reason, workflow=record.get("workflow"), run_id=record.get("run_id"), request_id=record.get("request_id"), - mode=self.mode, + mode=stored_mode if stored_mode in MODES else self.mode, **extra, ) diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index 4191be4811..81b316d883 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -36,6 +36,7 @@ import base64 import hashlib +import hmac import json from dataclasses import dataclass, field from pathlib import Path @@ -57,7 +58,19 @@ class HandoffError(ValueError): - """A handoff that can't be built (never a verification result).""" + """A handoff that can't be built (never a verification result). + + ``code`` is a closed reason when the refusal has one (``RUN_BINDING_CODES``). + """ + + def __init__(self, message: str = "", *, code: Optional[str] = None) -> None: + super().__init__(message) + self.code = code + + +#: Why a run's receipt was not attached: it names another run's report, or +#: this run's report could not be read to check that it doesn't. +RUN_BINDING_CODES = ("receipt_run_mismatch", "run_report_unreadable") def _sha256(data: bytes) -> str: @@ -293,19 +306,89 @@ def bind_payload( return bound +def _report_subject(receipt: Mapping[str, Any]) -> Optional[str]: + """The SHA-256 the receipt's signed statement names for ``report.json``.""" + from openadapt_types import receipt as r + + envelope = receipt["envelope"] if r.is_receipt_card(receipt) else receipt + try: + statement = r.loads_strict( + base64.b64decode(str(envelope["payload"]), validate=True) + ) + subjects = [ + s + for s in statement.get("subject") or [] + if isinstance(s, Mapping) and s.get("name") == "report.json" + ] + except (AttributeError, KeyError, TypeError, ValueError): + return None + if len(subjects) != 1 or not isinstance(subjects[0].get("digest"), Mapping): + return None + digest = subjects[0]["digest"].get("sha256") + return digest if isinstance(digest, str) else None + + +def _check_run_binding(run_dir: Path, receipt: Mapping[str, Any]) -> None: + """Refuse a receipt that is not over this run's own ``report.json``. + + A receipt in the folder can be genuine, signed by this computer's key, + and still belong to another run. Its signed ``report.json`` subject must + equal the SHA-256 of this run's report. An encrypted run's report is read + through its sealed set, whose authenticated index checks the bytes; with + no at-rest key nothing authenticates the report, so the receipt is + refused rather than attached unbound. Fails closed. + """ + from openadapt_flow import sealed_set + + signed = _report_subject(receipt) + path = Path(run_dir) / "report.json" + try: + if path.is_symlink(): + raise OSError("report.json is a symlink") + raw = sealed_set.read_bytes(path) + except Exception: # noqa: BLE001 - no readable report, no binding + raise HandoffError( + "this run's report can't be read (an encrypted run needs its " + "at-rest key), so its receipt can't be matched to the run", + code="run_report_unreadable", + ) from None + if signed is None or not hmac.compare_digest(signed, _sha256(raw)): + raise HandoffError( + "the receipt in that run folder is for a different run's report", + code="receipt_run_mismatch", + ) + + def receipt_for_run(run_dir: Path, *, public: bool = False) -> dict[str, Any]: - """Read a run's ``receipt.json`` (or its public card) for attaching.""" + """Read a run's ``receipt.json`` (or its public card) for attaching. + + ``receipt.json`` is plaintext on disk even beside an encrypted run. An + encrypted run seals its card with the run, so the card is read through + the run's sealed set, in memory only. Either way the receipt must be over + this run's own report (:func:`_check_run_binding`), which for an + encrypted run needs the at-rest key. Nothing is written. + """ from openadapt_types import receipt as r + from openadapt_flow import sealed_set + path = Path(run_dir) / (r.CARD_FILE if public else r.RECEIPT_FILE) try: - return _check_receipt_document(_loads_strict(path.read_text("utf-8"))) + if public and sealed_set.is_sealed_path(path): + if not sealed_set.is_file(path): + raise FileNotFoundError(path.name) + raw: str | bytes = sealed_set.read_bytes(path) + else: + raw = path.read_text("utf-8") + receipt = _check_receipt_document(_loads_strict(raw)) except FileNotFoundError: raise HandoffError(f"no {path.name} in that run folder") from None except (OSError, UnicodeDecodeError, ValueError) as exc: if isinstance(exc, HandoffError): raise raise HandoffError(f"{path.name} is not a readable receipt") from None + _check_run_binding(Path(run_dir), receipt) + return receipt # -- verification ---------------------------------------------------------------- @@ -708,6 +791,7 @@ def detached_path(payload_path: Path) -> Path: "SCHEMA", "VERDICT_SCHEMA", "RECEIVER_STATES", + "RUN_BINDING_CODES", "ReceiverRecord", "Verdict", "bind_payload", diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 4935e25da3..40a451cc37 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -772,7 +772,11 @@ def public_reveal(run_dir: Path) -> list[str]: summary = read_run_summary(run_dir) or {} reveal = ["flow_version"] try: - report = loads_strict((Path(run_dir) / "report.json").read_text("utf-8")) + # Through the sealed set, so an encrypted run's card opens the same + # fields as a plaintext run's. + from openadapt_flow import sealed_set + + report = loads_strict(sealed_set.read_text(Path(run_dir) / "report.json")) except (OSError, ValueError): report = {} if ( diff --git a/packages/flow/tests/test_handoff_at_rest.py b/packages/flow/tests/test_handoff_at_rest.py new file mode 100644 index 0000000000..bc0346ed71 --- /dev/null +++ b/packages/flow/tests/test_handoff_at_rest.py @@ -0,0 +1,319 @@ +"""Handoffs from an encrypted run (``OPENADAPT_FLOW_AT_REST=strict``). + +A real sealed run folder, the receipt written by the same hook the CLI calls +after a run (``receipt_after_run``), and the handoff built and checked the way +``get_handoff`` and ``verify_handoff`` do. The receipt must be the same as for +a plaintext run of the same report, and nothing but the allow-listed receipt +files may sit on disk in plaintext. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +from pathlib import Path +from typing import Any, Iterator + +import pytest + +pytest.importorskip("cryptography") + +from openadapt_types import receipt as r # noqa: E402 + +from openadapt_flow import at_rest, crypto, sealed_set # noqa: E402 +from openadapt_flow import handoff as h +from openadapt_flow.agent.bridge import BridgeError # noqa: E402 +from openadapt_flow.agent.handoff_tools import HandoffTools # noqa: E402 +from openadapt_flow.offline_seal import signer_for # noqa: E402 +from openadapt_flow.receipt_record import public_reveal, receipt_after_run # noqa: E402 +from tests.test_handoff import REPORT # noqa: E402 + +#: A marker in the report's text that must never reach disk in plaintext. +MARKER = "Type the triage note" + + +@pytest.fixture() +def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, str]]: + for name in ( + at_rest.OPT_OUT_ENV, + at_rest.MODE_ENV, + at_rest.ENCRYPT_ENV, + crypto.ENV_KEY, + sealed_set.RECORDING_ENV_KEY, + "OPENADAPT_POLICY", + "OPENADAPT_RECEIPT", + "OPENADAPT_SEAL_KEY", + ): + monkeypatch.delenv(name, raising=False) + home = tmp_path / "seal-home" + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(home)) + monkeypatch.setenv(at_rest.HOME_ENV, str(tmp_path / "at-rest-home")) + at_rest._reset_for_tests() + yield {"OPENADAPT_SEAL_HOME": str(home)} + at_rest._reset_for_tests() + + +def _report_bytes(**changes: Any) -> bytes: + return json.dumps({**REPORT, **changes}, indent=2).encode("utf-8") + + +def _sealed_run(root: Path, name: str = "run-handoff-1", **changes: Any) -> Path: + run = root / name + with sealed_set.writing(run, "run", crypto.resolve_key(None)): + sealed_set.write_bytes(run / "report.json", _report_bytes(**changes)) + assert sealed_set.is_sealed(run) + return run + + +def _plain_run(root: Path, name: str = "run-handoff-1", **changes: Any) -> Path: + run = root / name + run.mkdir(parents=True) + (run / "report.json").write_bytes(_report_bytes(**changes)) + return run + + +def _finished(mode: str = "production") -> Any: + """``record_for``: the stored record of a finished run in ``mode``.""" + return lambda run_id: {"run_id": run_id, "state": "finished", "mode": mode} + + +def _statement(receipt: dict[str, Any]) -> dict[str, Any]: + envelope = receipt["envelope"] if r.is_receipt_card(receipt) else receipt + return json.loads(base64.b64decode(envelope["payload"])) + + +def _without_salts(statement: dict[str, Any]) -> dict[str, Any]: + """The statement with its salted commitments left out (salts are random).""" + predicate = dict(statement["predicate"]) + predicate.pop("disclosure", None) + return {**statement, "predicate": predicate} + + +def _registry(signer: Any) -> list[r.RoleKey]: + return r.parse_registry( + { + "schema": r.REGISTRY_SCHEMA, + "keys": [{**signer.registry_entry(), "role": "this_computer"}], + } + ) + + +def _assert_no_plaintext_leak(run: Path) -> None: + opened = sealed_set.open_set(run) + opened.verify_all() + for path in run.rglob("*"): + if not path.is_file(): + continue + rel = path.relative_to(run).as_posix() + kind = sealed_set.classify("run", rel) + if kind is not None and kind.classification == "structural": + continue + assert MARKER.encode() not in path.read_bytes(), rel + + +@pytest.mark.parametrize("public", [False, True]) +def test_a_strict_run_gets_the_same_receipt_and_a_handoff_that_verifies( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + env: dict[str, str], + public: bool, +) -> None: + signer = signer_for(Path(env["OPENADAPT_SEAL_HOME"])) + + plain = _plain_run(tmp_path / "plain") + note = receipt_after_run(plain, env=env) + assert note is not None and note.startswith("receipt:"), note + + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + assert at_rest.strict() + sealed = _sealed_run(tmp_path / "sealed") + note = receipt_after_run(sealed, env={**env, at_rest.MODE_ENV: "strict"}) + assert note is not None and note.startswith("receipt:"), note + + # The receipt files the docs allow in plaintext are plaintext; the report + # is not. + assert (sealed / r.RECEIPT_FILE).is_file() + assert not (sealed / "report.json").is_file() + _assert_no_plaintext_leak(sealed) + + # Same statement whether the run is encrypted or not. + plain_receipt = h.receipt_for_run(plain, public=public) + sealed_receipt = h.receipt_for_run(sealed, public=public) + assert _without_salts(_statement(sealed_receipt)) == _without_salts( + _statement(plain_receipt) + ) + assert _statement(sealed_receipt)["subject"][0]["digest"]["sha256"] == ( + hashlib.sha256(_report_bytes()).hexdigest() + ) + if public: + # The card is sealed with the run on disk and opened in memory; it + # opens the same fields either way. + assert (sealed / f"{r.CARD_FILE}.enc").is_file() + assert not (sealed / r.CARD_FILE).exists() + assert sorted(sealed_receipt["openings"]) == sorted(plain_receipt["openings"]) + + # get_handoff through the tool the bridge calls, then verify_handoff. + tools = HandoffTools() + result = {"outcome": "done", "run_id": sealed.name, "mode": "production"} + doc = tools.get( + sealed.name, + public=public, + result_for=lambda _run_id: result, + run_dir_for=lambda _run_id: sealed, + record_for=_finished(), + ) + verdict = h.verify_handoff(doc, _registry(signer)) + assert verdict.ok, verdict.to_dict() + assert verdict.integrity == "intact" + assert verdict.outcome == "VERIFIED" + assert verdict.payload["bound"] is True + + # Building the handoff wrote nothing new in plaintext. + _assert_no_plaintext_leak(sealed) + + +def test_a_strict_run_without_the_at_rest_key_refuses_its_receipt( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: dict[str, str] +) -> None: + """Without the key nothing authenticates which run's report the plaintext + receipt.json is over, so it is refused rather than attached unbound.""" + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + sealed = _sealed_run(tmp_path / "sealed") + assert receipt_after_run(sealed, env={**env, at_rest.MODE_ENV: "strict"}) + + # Another computer, or this one after the key moved: no at-rest key. + monkeypatch.setenv(at_rest.HOME_ENV, str(tmp_path / "empty-at-rest-home")) + at_rest._reset_for_tests() + + def get(public: bool) -> dict[str, Any]: + return HandoffTools().get( + sealed.name, + public=public, + result_for=lambda _run_id: {"outcome": "done", "mode": "production"}, + run_dir_for=lambda _run_id: sealed, + record_for=_finished(), + ) + + # receipt.json is plaintext on disk, but the report it must match is not + # readable without the key: refused, with a closed code underneath. + with pytest.raises(BridgeError) as caught: + get(False) + assert str(caught.value).startswith( + "no handoff for this run: this run's report can't be read" + ) + with pytest.raises(h.HandoffError) as direct: + h.receipt_for_run(sealed) + assert direct.value.code == "run_report_unreadable" + # The card is sealed with the run: without the key, a clear refusal. + with pytest.raises(BridgeError) as caught: + get(True) + assert str(caught.value) == ( + "no handoff for this run: receipt.card.json is not a readable receipt" + ) + + +def test_a_tampered_receipt_in_a_strict_run_is_refused_not_passed_on( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: dict[str, str] +) -> None: + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + sealed = _sealed_run(tmp_path / "sealed") + assert receipt_after_run(sealed, env={**env, at_rest.MODE_ENV: "strict"}) + # Plant ciphertext where a plaintext receipt is expected: the handoff + # refuses; it never passes the bytes on. + (sealed / r.RECEIPT_FILE).write_bytes(b'{"ciphertext": "AAAA"}') + with pytest.raises(BridgeError, match="no handoff for this run"): + HandoffTools().get( + sealed.name, + public=False, + result_for=lambda _run_id: {"outcome": "done", "mode": "production"}, + run_dir_for=lambda _run_id: sealed, + record_for=_finished(), + ) + + +@pytest.mark.parametrize("strict", [False, True]) +@pytest.mark.parametrize("public", [False, True]) +def test_a_receipt_from_another_run_signed_by_the_same_key_is_refused( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + env: dict[str, str], + strict: bool, + public: bool, +) -> None: + """Two runs, two different reports, one key: each receipt is genuine, but + a receipt moved into the other run's folder must not travel with it.""" + signer = signer_for(Path(env["OPENADAPT_SEAL_HOME"])) + run_env = dict(env) + if strict: + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + run_env[at_rest.MODE_ENV] = "strict" + make = _sealed_run if strict else _plain_run + first = make(tmp_path / "a", "run-a", run_id="run-a") + second = make( + tmp_path / "b", + "run-b", + run_id="run-b", + started_at="2026-11-22T04:05:06Z", + workflow_name="Another workflow", + ) + for run in (first, second): + assert receipt_after_run(run, env=run_env) + + def get(run: Path) -> dict[str, Any]: + return HandoffTools(signer=signer).get( + run.name, + public=public, + result_for=lambda _run_id: {"outcome": "done", "mode": "production"}, + run_dir_for=lambda _run_id: run, + record_for=_finished(), + ) + + # Each run's own receipt hands off and verifies. + for run in (first, second): + assert h.verify_handoff(get(run), _registry(signer)).ok + + # Move run-b's receipt into run-a's folder: same key, wrong run. + name = r.CARD_FILE if public else r.RECEIPT_FILE + if public and strict: + # The card is sealed with the run: move it through the sealed set. + sealed_set.write_bytes(first / name, sealed_set.read_bytes(second / name)) + else: + (first / name).write_bytes((second / name).read_bytes()) + with pytest.raises(BridgeError) as caught: + get(first) + assert str(caught.value) == ( + "no handoff for this run: the receipt in that run folder is for a " + "different run's report" + ) + with pytest.raises(h.HandoffError) as direct: + h.receipt_for_run(first, public=public) + assert direct.value.code == "receipt_run_mismatch" + + +def test_an_encrypted_tutorial_run_s_card_opens_the_same_fields( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: dict[str, str] +) -> None: + """The card opens the program name only for the synthetic tutorial, and + reads the signed report to decide; an encrypted report must decide the same.""" + report = json.dumps({"governed_approval_source": "openadapt-flow-tutorial"}) + summary = json.dumps({"provenance": "synthetic-tutorial"}) + + plain = tmp_path / "plain" + plain.mkdir() + (plain / "report.json").write_text(report) + (plain / "run-summary.json").write_text(summary) + + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + sealed = tmp_path / "sealed" + with sealed_set.writing(sealed, "run", crypto.resolve_key(None)): + sealed_set.write_text(sealed / "report.json", report) + sealed_set.write_text(sealed / "run-summary.json", summary) + + assert public_reveal(plain) == ["flow_version", "program_name"] + assert public_reveal(sealed) == public_reveal(plain) diff --git a/scripts/ci/flow_test_durations.json b/scripts/ci/flow_test_durations.json index f2748f5217..87afa399be 100644 --- a/scripts/ci/flow_test_durations.json +++ b/scripts/ci/flow_test_durations.json @@ -339,6 +339,7 @@ "tests/test_halt_cleanup.py": 1.1, "tests/test_halt_detail.py": 10.1, "tests/test_halt_learn_loop.py": 1.0, + "tests/test_handoff_at_rest.py": 0.8, "tests/test_hard_invariants.py": 0.3, "tests/test_hardening_flywheel.py": 19.0, "tests/test_harness2_adapter.py": 9.2,