From e76f5f104247794696fb4b601ba2baef43408968 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:30:26 -0700 Subject: [PATCH 01/12] feat(goose): AMW StreamableHttp proxy, PreToolUse permit hook, fallback idempotency key (SEL-484) - Proxies @modelcontextprotocol/server-filesystem read_text_file/write_file - Permit rules; Goose PreToolUse hook blocks unpermitted calls before they run - Idempotency key = verified caller + tool + canonical args hash + agent-session-id; agent-tool-call-request-id is logged only (gate showed it changes on retry) - Bounded replay window AMW_IDEMPOTENCY_WINDOW_SECONDS (default 600) - failed_unknown outcomes are never re-run - Ed25519-signed receipts for every decision - Fault injection lives only in tests/e2e (test-only launcher) --- integrations/goose-agent-middleware/LICENSE | 202 ++++++++++++++ integrations/goose-agent-middleware/README.md | 97 +++++++ .../plugin/amw-permit/hooks/hooks.json | 17 ++ .../goose-agent-middleware/pyproject.toml | 31 +++ .../src/goose_amw/__init__.py | 3 + .../src/goose_amw/canonical.py | 37 +++ .../src/goose_amw/hook.py | 60 +++++ .../src/goose_amw/ledger.py | 121 +++++++++ .../src/goose_amw/permits.py | 39 +++ .../src/goose_amw/proxy.py | 247 ++++++++++++++++++ .../src/goose_amw/receipts.py | 92 +++++++ .../tests/e2e/fault_proxy.py | 44 ++++ .../tests/e2e/verify_receipts.py | 28 ++ .../tests/fixtures/g1_gate_calls.jsonl | 3 + .../goose-agent-middleware/tests/test_core.py | 115 ++++++++ 15 files changed, 1136 insertions(+) create mode 100644 integrations/goose-agent-middleware/LICENSE create mode 100644 integrations/goose-agent-middleware/README.md create mode 100644 integrations/goose-agent-middleware/plugin/amw-permit/hooks/hooks.json create mode 100644 integrations/goose-agent-middleware/pyproject.toml create mode 100644 integrations/goose-agent-middleware/src/goose_amw/__init__.py create mode 100644 integrations/goose-agent-middleware/src/goose_amw/canonical.py create mode 100644 integrations/goose-agent-middleware/src/goose_amw/hook.py create mode 100644 integrations/goose-agent-middleware/src/goose_amw/ledger.py create mode 100644 integrations/goose-agent-middleware/src/goose_amw/permits.py create mode 100644 integrations/goose-agent-middleware/src/goose_amw/proxy.py create mode 100644 integrations/goose-agent-middleware/src/goose_amw/receipts.py create mode 100644 integrations/goose-agent-middleware/tests/e2e/fault_proxy.py create mode 100644 integrations/goose-agent-middleware/tests/e2e/verify_receipts.py create mode 100644 integrations/goose-agent-middleware/tests/fixtures/g1_gate_calls.jsonl create mode 100644 integrations/goose-agent-middleware/tests/test_core.py diff --git a/integrations/goose-agent-middleware/LICENSE b/integrations/goose-agent-middleware/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/integrations/goose-agent-middleware/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/integrations/goose-agent-middleware/README.md b/integrations/goose-agent-middleware/README.md new file mode 100644 index 000000000..5fda05706 --- /dev/null +++ b/integrations/goose-agent-middleware/README.md @@ -0,0 +1,97 @@ +# Goose + Agent Middleware + +Runs Agent Middleware (AMW) as a normal Goose **StreamableHttp MCP extension** +that proxies the official `@modelcontextprotocol/server-filesystem` server +(`read_text_file`, `write_file`), plus a Goose **PreToolUse deny hook**. + +Every proxied call goes through permit -> idempotency -> invoke -> receipt. + +## Pieces + +| Piece | What it does | +|---|---| +| `goose-amw-proxy` | StreamableHttp MCP server (protocol 2026-07-28 and older). Verifies the caller, enforces permits, dedupes writes, signs receipts. | +| `goose-amw-hook` | Goose `PreToolUse` hook. A call with no permit is blocked **before it runs**; Goose shows `Tool call denied by policy hook ...: AMW permit denied: `. | +| `plugin/amw-permit/hooks/hooks.json` | Template plugin that wires the hook to `amw__*` tools. | + +The proxy enforces the same permit rules server-side, so a client without the +hook is still refused. + +## Permit policy + +```json +{"rules": [ + {"id": "write-allowed", "tool": "write_file", "folder": "/path/to/allowed"}, + {"id": "read-sandbox", "tool": "read_text_file", "folder": "/path/to/sandbox"} +]} +``` + +A call is allowed only if a rule names the tool and the resolved `path` is +inside the rule's folder (`..` and symlinks are resolved first). Anything else +is denied with a reason. + +## Idempotency key + +AMW keys a write by **verified caller identity + tool name + canonical +argument hash + `agent-session-id`**. + +Goose (protocol 2026-07-28) sends `_meta["agent-tool-call-request-id"]`, but +that id is the model's tool-call id: when a call fails and the model retries, +Goose sends a **new** id (recorded in `tests/fixtures/g1_gate_calls.jsonl`). +AMW therefore logs it on receipts and in the ledger but never uses it as the +key. Older protocols without `_meta` use the same fallback key; a missing +session id is treated as the empty string. + +The caller is verified from the `Authorization: Bearer` header against +`AMW_CALLERS` (a JSON map of `sha256(token)` to caller id). Unverified calls +are refused. + +## Replay window + +`AMW_IDEMPOTENCY_WINDOW_SECONDS` (default **600**, must be > 0). + +* A completed write repeated with the same key **inside** the window is not + run again; AMW returns the stored result and issues a `replayed` receipt. +* The same write made **after** the window runs normally, so deliberate + identical writes later in a session are not swallowed. +* A write whose outcome is unknown (`failed_unknown`: the call was + dispatched and the response was lost, or AMW crashed mid-call) is **never + re-run automatically**, inside or outside the window. Retries are refused + with a reason until an operator resolves the entry. +* A definite upstream error (`failed`, no effect) may be retried. + +Choose a window longer than your client's retry horizon and shorter than the +interval at which you write identical content on purpose. + +## Receipts + +Each decision (allow, deny, replay, refuse) appends an Ed25519-signed receipt +to `$AMW_STATE_DIR/receipts.jsonl`: `tool`, `args_hash`, `decision`, +`outcome`, `issued_at`, plus caller, session, key and the logged request id. +The signature covers the canonical JSON of `body`; the public key is written +to `receipt_public_key.b64`. + +## Goose setup + +```yaml +extensions: + amw: + type: streamable_http + name: amw + uri: http://127.0.0.1:8791/mcp + headers: + Authorization: Bearer ${AMW_TOKEN} + timeout: 120 + enabled: true +``` + +Install `plugin/amw-permit` into `.agents/plugins/` (project) or the Goose +plugins directory, replacing the paths in its `hooks.json`. + +## Tests + +`pytest` needs no external data. `tests/fixtures/g1_gate_calls.jsonl` is the +real call log recorded by AMW during the G1 gate session. +`tests/e2e/fault_proxy.py` is a test-only launcher that injects one fault into +the shipped proxy to record the cut-stream and unknown-outcome sessions; it +is not part of the package. diff --git a/integrations/goose-agent-middleware/plugin/amw-permit/hooks/hooks.json b/integrations/goose-agent-middleware/plugin/amw-permit/hooks/hooks.json new file mode 100644 index 000000000..6ee293179 --- /dev/null +++ b/integrations/goose-agent-middleware/plugin/amw-permit/hooks/hooks.json @@ -0,0 +1,17 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "^amw__", + "hooks": [ + { + "type": "command", + "command": "goose-amw-hook --policy /path/to/policy.json --state-dir /path/to/state", + "on_failure": "block", + "timeout": 10 + } + ] + } + ] + } +} diff --git a/integrations/goose-agent-middleware/pyproject.toml b/integrations/goose-agent-middleware/pyproject.toml new file mode 100644 index 000000000..2a7aa957d --- /dev/null +++ b/integrations/goose-agent-middleware/pyproject.toml @@ -0,0 +1,31 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "goose-agent-middleware" +version = "0.1.0" +description = "Agent Middleware as a Goose StreamableHttp MCP extension: permits, PreToolUse deny hook, idempotent writes, signed receipts" +readme = "README.md" +license = "Apache-2.0" +requires-python = ">=3.11" +dependencies = [ + "mcp>=2.3.0,<3", + "cryptography>=50.0.0", +] + +[project.optional-dependencies] +dev = ["pytest", "ruff"] + +[project.scripts] +goose-amw-proxy = "goose_amw.proxy:main" +goose-amw-hook = "goose_amw.hook:main" + +[tool.hatch.build.targets.wheel] +packages = ["src/goose_amw"] + +[tool.ruff] +line-length = 100 + +[tool.pytest.ini_options] +pythonpath = ["src"] diff --git a/integrations/goose-agent-middleware/src/goose_amw/__init__.py b/integrations/goose-agent-middleware/src/goose_amw/__init__.py new file mode 100644 index 000000000..77f8e9e8c --- /dev/null +++ b/integrations/goose-agent-middleware/src/goose_amw/__init__.py @@ -0,0 +1,3 @@ +"""Agent Middleware for Goose: a governed StreamableHttp MCP proxy.""" + +__all__ = ["canonical", "ledger", "permits", "receipts"] diff --git a/integrations/goose-agent-middleware/src/goose_amw/canonical.py b/integrations/goose-agent-middleware/src/goose_amw/canonical.py new file mode 100644 index 000000000..4db4ef54a --- /dev/null +++ b/integrations/goose-agent-middleware/src/goose_amw/canonical.py @@ -0,0 +1,37 @@ +"""Canonical JSON and argument hashing.""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any + + +def canonical_json(payload: Any) -> str: + """Sorted keys, no insignificant whitespace, ASCII only (the AMW signing form).""" + return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + + +def sha256_hex(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def args_hash(arguments: dict[str, Any] | None) -> str: + return "sha256:" + sha256_hex(canonical_json(arguments or {})) + + +def idempotency_key( + *, caller: str, tool: str, arguments: dict[str, Any] | None, session_id: str +) -> str: + """Fallback key: verified caller + tool + canonical argument hash + agent-session-id. + + ``agent-tool-call-request-id`` is deliberately NOT an input: the G1 gate showed + Goose issues a new id when the model retries a failed call. + """ + material = { + "caller": caller, + "tool": tool, + "args_hash": args_hash(arguments), + "session_id": session_id, + } + return "amw-fb-" + sha256_hex(canonical_json(material)) diff --git a/integrations/goose-agent-middleware/src/goose_amw/hook.py b/integrations/goose-agent-middleware/src/goose_amw/hook.py new file mode 100644 index 000000000..fb5236504 --- /dev/null +++ b/integrations/goose-agent-middleware/src/goose_amw/hook.py @@ -0,0 +1,60 @@ +"""Goose PreToolUse hook: deny a tool call that has no AMW permit. + +Goose runs this before the tool call with the hook context JSON on stdin. +Printing ``{"decision":"block","reason":...}`` stops the call before it +reaches the MCP server; Goose shows the reason to the user and the model. + +Usage in ``hooks/hooks.json``:: + + goose-amw-hook --policy /path/policy.json --state-dir /path/state +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +from . import permits +from .canonical import args_hash +from .receipts import ReceiptSigner, load_or_create_key + + +def decide(payload: dict, policy: dict) -> dict: + tool = payload.get("tool_name") or payload.get("matcher_context") or "" + arguments = payload.get("tool_input") or {} + decision = permits.check(policy, tool, arguments) + if decision.allowed: + return {"decision": "allow"} + return {"decision": "block", "reason": f"AMW permit denied: {decision.reason}"} + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--policy", required=True) + ap.add_argument("--state-dir", required=True) + ns = ap.parse_args(argv) + payload = json.load(sys.stdin) + out = decide(payload, permits.load_policy(ns.policy)) + if out["decision"] == "block": + state = Path(ns.state_dir) + signer = ReceiptSigner( + load_or_create_key(state / "receipt_signing_key.pem"), state / "receipts.jsonl" + ) + signer.issue( + tool=payload.get("tool_name") or "", + args_hash=args_hash(payload.get("tool_input") or {}), + decision="deny", + outcome="not_run", + enforced_by="goose_pre_tool_use_hook", + reason=out["reason"], + session_id=payload.get("session_id"), + agent_tool_call_request_id=payload.get("tool_call_id"), + ) + print(json.dumps(out)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/integrations/goose-agent-middleware/src/goose_amw/ledger.py b/integrations/goose-agent-middleware/src/goose_amw/ledger.py new file mode 100644 index 000000000..7c13dedd1 --- /dev/null +++ b/integrations/goose-agent-middleware/src/goose_amw/ledger.py @@ -0,0 +1,121 @@ +"""SQLite idempotency ledger with a bounded replay window. + +States: ``in_flight`` -> ``completed`` | ``failed`` | ``failed_unknown``. + +* ``completed``: a retry inside the window replays the stored result; the tool + does not run again. +* ``failed``: the upstream answered with a definite error (no effect); a retry + may run again. +* ``failed_unknown``: the outcome is unclear (transport lost after dispatch). + It is never re-run automatically, inside or outside the window, until an + operator resolves it. +* A ``completed`` entry older than the window no longer dedupes, so an + identical write made on purpose much later runs normally. +""" + +from __future__ import annotations + +import sqlite3 +import threading +import time +from dataclasses import dataclass +from pathlib import Path + +DEFAULT_WINDOW_SECONDS = 600 + + +@dataclass(frozen=True) +class Claim: + """Result of trying to claim a key before running a tool.""" + + action: str # "run" | "replay" | "refuse" + result: str | None = None + status: str | None = None + + +class Ledger: + def __init__(self, path: str | Path, window_seconds: float = DEFAULT_WINDOW_SECONDS): + if window_seconds <= 0: + raise ValueError("window_seconds must be positive") + self.window_seconds = window_seconds + self._lock = threading.Lock() + self._db = sqlite3.connect(str(path), check_same_thread=False, isolation_level=None) + self._db.execute( + "CREATE TABLE IF NOT EXISTS calls (" + " key TEXT PRIMARY KEY, tool TEXT NOT NULL, args_hash TEXT NOT NULL," + " status TEXT NOT NULL, result TEXT, first_request_id TEXT," + " created_at REAL NOT NULL, updated_at REAL NOT NULL, executions INTEGER NOT NULL)" + ) + + def claim( + self, + key: str, + *, + tool: str, + args_hash: str, + request_id: str | None, + now: float | None = None, + ) -> Claim: + now = time.time() if now is None else now + with self._lock: + self._db.execute("BEGIN IMMEDIATE") + try: + row = self._db.execute( + "SELECT status, result, created_at FROM calls WHERE key = ?", (key,) + ).fetchone() + if row is not None: + status, result, created_at = row + if status == "failed_unknown": + self._db.execute("COMMIT") + return Claim("refuse", status=status) + if status == "in_flight": + self._db.execute("COMMIT") + return Claim("refuse", status=status) + if status == "completed" and now - created_at < self.window_seconds: + self._db.execute("COMMIT") + return Claim("replay", result=result, status=status) + # failed (no effect) or completed outside the window: run again. + self._db.execute( + "UPDATE calls SET status='in_flight', result=NULL, created_at=?," + " updated_at=?, executions=executions+1 WHERE key=?", + (now, now, key), + ) + else: + self._db.execute( + "INSERT INTO calls VALUES (?, ?, ?, 'in_flight', NULL, ?, ?, ?, 1)", + (key, tool, args_hash, request_id, now, now), + ) + self._db.execute("COMMIT") + return Claim("run") + except BaseException: + self._db.execute("ROLLBACK") + raise + + def finish(self, key: str, status: str, result: str | None = None) -> None: + if status not in ("completed", "failed", "failed_unknown"): + raise ValueError(status) + with self._lock: + self._db.execute( + "UPDATE calls SET status=?, result=?, updated_at=? WHERE key=?", + (status, result, time.time(), key), + ) + + def mark_stale_in_flight_unknown(self) -> int: + """At startup, an ``in_flight`` row means a crash mid-call: outcome unknown.""" + with self._lock: + cur = self._db.execute( + "UPDATE calls SET status='failed_unknown', updated_at=? WHERE status='in_flight'", + (time.time(),), + ) + return cur.rowcount + + def get(self, key: str) -> dict | None: + cur = self._db.execute( + "SELECT key, tool, status, result, executions, first_request_id FROM calls WHERE key=?", + (key,), + ) + row = cur.fetchone() + if row is None: + return None + names = ["key", "tool", "status", "result", "executions", "first_request_id"] + return dict(zip(names, row, strict=True)) diff --git a/integrations/goose-agent-middleware/src/goose_amw/permits.py b/integrations/goose-agent-middleware/src/goose_amw/permits.py new file mode 100644 index 000000000..a85529a5a --- /dev/null +++ b/integrations/goose-agent-middleware/src/goose_amw/permits.py @@ -0,0 +1,39 @@ +"""Path-scoped permit rules shared by the proxy and the Goose PreToolUse hook.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any + + +@dataclass(frozen=True) +class Decision: + allowed: bool + reason: str + + +def load_policy(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text()) + + +def _bare(tool: str) -> str: + # Goose prefixes extension tools as "__". + return tool.split("__", 1)[1] if "__" in tool else tool + + +def check(policy: dict[str, Any], tool: str, arguments: dict[str, Any] | None) -> Decision: + """Allow only when a rule grants ``tool`` on a path inside its folder.""" + name = _bare(tool) + raw = (arguments or {}).get("path") + if not isinstance(raw, str) or not raw: + return Decision(False, f"no permit: {name} call has no path argument") + target = Path(raw).expanduser().resolve() + for rule in policy.get("rules", []): + if rule.get("tool") != name: + continue + folder = Path(rule["folder"]).expanduser().resolve() + if target.is_relative_to(folder): + return Decision(True, f"permit {rule.get('id', name)} allows {name} in {folder}") + return Decision(False, f"no permit for {name} on {target}: outside every permitted folder") diff --git a/integrations/goose-agent-middleware/src/goose_amw/proxy.py b/integrations/goose-agent-middleware/src/goose_amw/proxy.py new file mode 100644 index 000000000..21f6edb1c --- /dev/null +++ b/integrations/goose-agent-middleware/src/goose_amw/proxy.py @@ -0,0 +1,247 @@ +"""AMW StreamableHttp MCP server for Goose. + +Proxies one read tool and one write tool to the official +``@modelcontextprotocol/server-filesystem`` server. Every call is checked +against the permit policy, keyed for idempotency with the fallback key +(verified caller + tool + canonical argument hash + agent-session-id), and +receives a signed receipt. ``agent-tool-call-request-id`` is logged only. + +Configuration (environment): + +* ``AMW_POLICY`` - permit policy JSON (see README) +* ``AMW_STATE_DIR`` - ledger, receipts and signing key +* ``AMW_CALLERS`` - JSON map of sha256(bearer token) -> caller id +* ``AMW_FS_ROOT`` - root directory handed to the filesystem server +* ``AMW_IDEMPOTENCY_WINDOW_SECONDS`` - replay window, default 600 +* ``AMW_HOST`` / ``AMW_PORT`` - bind address, default 127.0.0.1:8791 +""" + +from __future__ import annotations + +import hmac +import json +import logging +import os +from collections.abc import Awaitable, Callable, Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from mcp.server.mcpserver import Context, MCPServer +from mcp.server.mcpserver.exceptions import ToolError + +from . import permits +from .canonical import args_hash, idempotency_key, sha256_hex +from .ledger import DEFAULT_WINDOW_SECONDS, Ledger +from .receipts import ReceiptSigner, load_or_create_key + +log = logging.getLogger("goose_amw") + +REQUEST_ID_KEY = "agent-tool-call-request-id" +SESSION_ID_KEY = "agent-session-id" + + +class UpstreamError(Exception): + """The upstream answered with a definite error: the call had no effect.""" + + +class UpstreamUnknown(Exception): + """The call was dispatched but its outcome is unknown.""" + + +Upstream = Callable[[str, dict[str, Any]], Awaitable[str]] + + +def filesystem_upstream(fs_root: str) -> Upstream: + from mcp.client.session import ClientSession + from mcp.client.stdio import StdioServerParameters, stdio_client + + params = StdioServerParameters( + command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", fs_root] + ) + + async def call(tool: str, arguments: dict[str, Any]) -> str: + try: + ctx = stdio_client(params) + read, write = await ctx.__aenter__() + except Exception as exc: # never dispatched + raise UpstreamError(f"filesystem server unavailable: {exc}") from exc + try: + async with ClientSession(read, write) as session: + await session.initialize() + try: + res = await session.call_tool(tool, arguments) + except Exception as exc: + raise UpstreamUnknown(f"{type(exc).__name__}: {exc}") from exc + finally: + try: + await ctx.__aexit__(None, None, None) + except Exception: + log.warning("filesystem server shutdown error", exc_info=True) + text = "\n".join(getattr(c, "text", "") for c in res.content) + if res.is_error: + raise UpstreamError(text) + return text + + return call + + +@dataclass +class Config: + policy: dict[str, Any] + state_dir: Path + callers: dict[str, str] + fs_root: str + window_seconds: float = DEFAULT_WINDOW_SECONDS + + @classmethod + def from_env(cls) -> Config: + return cls( + policy=permits.load_policy(os.environ["AMW_POLICY"]), + state_dir=Path(os.environ["AMW_STATE_DIR"]), + callers=json.loads(Path(os.environ["AMW_CALLERS"]).read_text()), + fs_root=os.environ["AMW_FS_ROOT"], + window_seconds=float( + os.environ.get("AMW_IDEMPOTENCY_WINDOW_SECONDS", DEFAULT_WINDOW_SECONDS) + ), + ) + + +def verify_caller(headers: Mapping[str, str] | None, callers: dict[str, str]) -> str: + auth = (headers or {}).get("authorization", "") + if not auth.lower().startswith("bearer "): + raise ToolError("AMW refused: caller not verified (missing bearer token)") + digest = sha256_hex(auth[7:].strip()) + for known, caller in callers.items(): + if hmac.compare_digest(known, digest): + return caller + raise ToolError("AMW refused: caller not verified (unknown token)") + + +def _meta(ctx: Context) -> dict[str, Any]: + m = ctx.request_context.meta + if m is None: + return {} + return dict(m) if isinstance(m, dict) else m.model_dump(by_alias=True, exclude_none=True) + + +class Gateway: + """Permit -> idempotency -> invoke -> receipt for each proxied call.""" + + def __init__( + self, + config: Config, + upstream: Upstream | None = None, + after_commit: Callable[[str, str], Awaitable[None]] | None = None, + ): + config.state_dir.mkdir(parents=True, exist_ok=True) + self.config = config + self.ledger = Ledger(config.state_dir / "ledger.sqlite3", config.window_seconds) + stale = self.ledger.mark_stale_in_flight_unknown() + if stale: + log.warning("marked %d interrupted call(s) failed_unknown", stale) + self.signer = ReceiptSigner( + load_or_create_key(config.state_dir / "receipt_signing_key.pem"), + config.state_dir / "receipts.jsonl", + ) + (config.state_dir / "receipt_public_key.b64").write_text(self.signer.public_key_b64) + self.upstream = upstream or filesystem_upstream(config.fs_root) + # Test-only seam: tests inject faults here. Never set in production. + self.after_commit = after_commit + + async def handle(self, tool: str, arguments: dict[str, Any], ctx: Context, *, write: bool): + meta = _meta(ctx) + request_id = meta.get(REQUEST_ID_KEY) + session_id = meta.get(SESSION_ID_KEY) or "" + ahash = args_hash(arguments) + base = {"protocol": ctx.protocol_version, "agent_tool_call_request_id": request_id} + caller = verify_caller(ctx.headers, self.config.callers) + base.update(caller=caller, session_id=session_id) + + decision = permits.check(self.config.policy, tool, arguments) + if not decision.allowed: + self.signer.issue( + tool=tool, + args_hash=ahash, + decision="deny", + outcome="not_run", + reason=decision.reason, + **base, + ) + raise ToolError(f"AMW permit denied: {decision.reason}") + + key = idempotency_key(caller=caller, tool=tool, arguments=arguments, session_id=session_id) + base["idempotency_key"] = key + if not write: + return await self._run(tool, arguments, ahash, base, key=None) + + claim = self.ledger.claim(key, tool=tool, args_hash=ahash, request_id=request_id) + if claim.action == "replay": + self.signer.issue( + tool=tool, args_hash=ahash, decision="allow", outcome="replayed", **base + ) + return claim.result + if claim.action == "refuse": + self.signer.issue( + tool=tool, args_hash=ahash, decision="refuse", outcome=claim.status, **base + ) + raise ToolError( + f"AMW refused to re-run: an earlier identical {tool} call is {claim.status}; " + "its outcome is unknown, so it will not run again automatically" + ) + return await self._run(tool, arguments, ahash, base, key=key) + + async def _run(self, tool, arguments, ahash, base, *, key): + try: + result = await self.upstream(tool, arguments) + except UpstreamError as exc: + if key: + self.ledger.finish(key, "failed") + self.signer.issue( + tool=tool, args_hash=ahash, decision="allow", outcome="failed", **base + ) + raise ToolError(f"upstream error: {exc}") from exc + except BaseException: + if key: + self.ledger.finish(key, "failed_unknown") + self.signer.issue( + tool=tool, args_hash=ahash, decision="allow", outcome="failed_unknown", **base + ) + raise + if key: + self.ledger.finish(key, "completed", result) + self.signer.issue(tool=tool, args_hash=ahash, decision="allow", outcome="completed", **base) + if key and self.after_commit is not None: + await self.after_commit(tool, key) + return result + + +def build_server(gateway: Gateway) -> MCPServer: + mcp = MCPServer("amw") + + @mcp.tool() + async def read_text_file(path: str, ctx: Context) -> str: + """Read a UTF-8 text file through AMW (permit-checked, receipted).""" + return await gateway.handle("read_text_file", {"path": path}, ctx, write=False) + + @mcp.tool() + async def write_file(path: str, content: str, ctx: Context) -> str: + """Write a text file through AMW (permit-checked, idempotent, receipted).""" + args = {"path": path, "content": content} + return await gateway.handle("write_file", args, ctx, write=True) + + return mcp + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + server = build_server(Gateway(Config.from_env())) + server.run( + transport="streamable-http", + host=os.environ.get("AMW_HOST", "127.0.0.1"), + port=int(os.environ.get("AMW_PORT", "8791")), + ) + + +if __name__ == "__main__": + main() diff --git a/integrations/goose-agent-middleware/src/goose_amw/receipts.py b/integrations/goose-agent-middleware/src/goose_amw/receipts.py new file mode 100644 index 000000000..96ac674ec --- /dev/null +++ b/integrations/goose-agent-middleware/src/goose_amw/receipts.py @@ -0,0 +1,92 @@ +"""Ed25519-signed receipts, one JSON line per tool call decision.""" + +from __future__ import annotations + +import base64 +import json +import os +import time +import uuid +from pathlib import Path +from typing import Any + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import ( + Ed25519PrivateKey, + Ed25519PublicKey, +) + +from .canonical import canonical_json, sha256_hex + + +def load_or_create_key(path: str | Path) -> Ed25519PrivateKey: + p = Path(path) + if p.exists(): + key = serialization.load_pem_private_key(p.read_bytes(), password=None) + assert isinstance(key, Ed25519PrivateKey) + return key + key = Ed25519PrivateKey.generate() + p.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "wb") as f: + f.write( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + return key + + +def _raw_public(key: Ed25519PublicKey) -> bytes: + return key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) + + +class ReceiptSigner: + def __init__(self, key: Ed25519PrivateKey, log_path: str | Path): + self._key = key + self._log = Path(log_path) + pub = _raw_public(key.public_key()) + self.public_key_b64 = base64.b64encode(pub).decode() + self.kid = "amw-goose-" + sha256_hex(self.public_key_b64)[:16] + + def issue( + self, + *, + tool: str, + args_hash: str, + decision: str, + outcome: str, + **extra: Any, + ) -> dict[str, Any]: + body = { + "receipt_id": str(uuid.uuid4()), + "tool": tool, + "args_hash": args_hash, + "decision": decision, + "outcome": outcome, + "issued_at": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + "Z", + "alg": "Ed25519", + "kid": self.kid, + **{k: v for k, v in extra.items() if v is not None}, + } + sig = self._key.sign(canonical_json(body).encode()) + receipt = {"body": body, "signature": base64.b64encode(sig).decode()} + self._log.parent.mkdir(parents=True, exist_ok=True) + with self._log.open("a") as f: + f.write(json.dumps(receipt) + "\n") + return receipt + + +def verify(receipt: dict[str, Any], public_key_b64: str) -> bool: + pub = Ed25519PublicKey.from_public_bytes(base64.b64decode(public_key_b64)) + try: + pub.verify( + base64.b64decode(receipt["signature"]), + canonical_json(receipt["body"]).encode(), + ) + except (InvalidSignature, ValueError, KeyError): + return False + return True diff --git a/integrations/goose-agent-middleware/tests/e2e/fault_proxy.py b/integrations/goose-agent-middleware/tests/e2e/fault_proxy.py new file mode 100644 index 000000000..3f53c9341 --- /dev/null +++ b/integrations/goose-agent-middleware/tests/e2e/fault_proxy.py @@ -0,0 +1,44 @@ +"""TEST-ONLY launcher: the shipped proxy plus one injected fault. + +Not part of the package. Used to record the real Goose sessions in the PR: + +* ``AMW_TEST_FAULT=cut_after_commit`` - the first write runs and commits, then + its response stream is closed before the result reaches Goose. +* ``AMW_TEST_FAULT=lose_upstream_response`` - the first write is dispatched + to the filesystem server, then its response is dropped (outcome unknown). +""" + +import os + +from goose_amw.proxy import ( + Config, + Gateway, + UpstreamUnknown, + build_server, + filesystem_upstream, +) + +FAULT = os.environ["AMW_TEST_FAULT"] +cfg = Config.from_env() +real = filesystem_upstream(cfg.fs_root) +fired = [] + + +async def upstream(tool, args): + result = await real(tool, args) + if FAULT == "lose_upstream_response" and tool == "write_file" and not fired: + fired.append(tool) + raise UpstreamUnknown("test fault: upstream response dropped after dispatch") + return result + + +async def after_commit(tool, key): + if FAULT == "cut_after_commit" and not fired: + fired.append(key) + raise ConnectionAbortedError("test fault: response stream cut after commit") + + +gw = Gateway(cfg, upstream=upstream, after_commit=after_commit) +build_server(gw).run( + transport="streamable-http", host="127.0.0.1", port=int(os.environ["AMW_PORT"]) +) diff --git a/integrations/goose-agent-middleware/tests/e2e/verify_receipts.py b/integrations/goose-agent-middleware/tests/e2e/verify_receipts.py new file mode 100644 index 000000000..480657ae6 --- /dev/null +++ b/integrations/goose-agent-middleware/tests/e2e/verify_receipts.py @@ -0,0 +1,28 @@ +"""Verify every receipt in an AMW state dir and print a compact summary.""" + +import json +import sys +from pathlib import Path + +from goose_amw.receipts import verify + +state = Path(sys.argv[1]) +pub = (state / "receipt_public_key.b64").read_text().strip() +bad = 0 +for line in (state / "receipts.jsonl").read_text().splitlines(): + r = json.loads(line) + ok = verify(r, pub) + bad += not ok + b = r["body"] + print( + "OK " if ok else "BAD", + b["issued_at"], + b["tool"], + b["decision"], + b["outcome"], + b["args_hash"][:19], + b.get("enforced_by", "proxy"), + b.get("agent_tool_call_request_id") or "-", + b.get("protocol", "-"), + ) +sys.exit(1 if bad else 0) diff --git a/integrations/goose-agent-middleware/tests/fixtures/g1_gate_calls.jsonl b/integrations/goose-agent-middleware/tests/fixtures/g1_gate_calls.jsonl new file mode 100644 index 000000000..ab3fa361c --- /dev/null +++ b/integrations/goose-agent-middleware/tests/fixtures/g1_gate_calls.jsonl @@ -0,0 +1,3 @@ +{"tool": "write_file", "path": "/Users/sellers/scratch/g1-sandbox/allowed/gate.txt", "protocol": "2026-07-28", "meta": {"progress_token": 1, "agent-session-id": "20261024_4", "agent-working-dir": "/Users/sellers/scratch/g1-sandbox", "agent-tool-call-request-id": "tool_CpDpciFxHvt0zB4Vgyo0wXHe", "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": {"name": "goose-cli", "version": "1.56.0"}, "io.modelcontextprotocol/clientCapabilities": {"extensions": {}, "roots": {}, "elicitation": {}}}, "decision": "dropped_mid_stream", "ts": 1792826481.62643} +{"tool": "write_file", "path": "/Users/sellers/scratch/g1-sandbox/allowed/gate.txt", "protocol": "2026-07-28", "meta": {"progress_token": 2, "agent-session-id": "20261024_4", "agent-working-dir": "/Users/sellers/scratch/g1-sandbox", "agent-tool-call-request-id": "tool_Cn0pLB5b7j1weRQrhby6UOhB", "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": {"name": "goose-cli", "version": "1.56.0"}, "io.modelcontextprotocol/clientCapabilities": {"extensions": {}, "roots": {}, "elicitation": {}}}, "decision": "allow", "ts": 1792826485.893873} +{"tool": "read_text_file", "path": "/Users/sellers/scratch/g1-sandbox/allowed/gate.txt", "protocol": "2026-07-28", "meta": {"progress_token": 3, "agent-session-id": "20261024_4", "agent-working-dir": "/Users/sellers/scratch/g1-sandbox", "agent-tool-call-request-id": "tool_KAT1peagg5d6MBVBcMhucmZy", "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": {"name": "goose-cli", "version": "1.56.0"}, "io.modelcontextprotocol/clientCapabilities": {"extensions": {}, "roots": {}, "elicitation": {}}}, "ts": 1792826493.060245} diff --git a/integrations/goose-agent-middleware/tests/test_core.py b/integrations/goose-agent-middleware/tests/test_core.py new file mode 100644 index 000000000..9a2b23a3e --- /dev/null +++ b/integrations/goose-agent-middleware/tests/test_core.py @@ -0,0 +1,115 @@ +import json +from pathlib import Path + +import pytest + +from goose_amw import hook, permits +from goose_amw.canonical import args_hash, canonical_json, idempotency_key +from goose_amw.ledger import Ledger +from goose_amw.receipts import ReceiptSigner, load_or_create_key, verify + +FIXTURE = Path(__file__).parent / "fixtures" / "g1_gate_calls.jsonl" + + +def test_canonical_hash_ignores_key_order(): + assert canonical_json({"b": 1, "a": [2]}) == '{"a":[2],"b":1}' + assert args_hash({"path": "p", "content": "c"}) == args_hash({"content": "c", "path": "p"}) + + +def test_key_inputs(): + k = idempotency_key(caller="c", tool="write_file", arguments={"x": 1}, session_id="s") + assert k == idempotency_key(caller="c", tool="write_file", arguments={"x": 1}, session_id="s") + assert k != idempotency_key(caller="d", tool="write_file", arguments={"x": 1}, session_id="s") + assert k != idempotency_key( + caller="c", tool="read_text_file", arguments={"x": 1}, session_id="s" + ) + assert k != idempotency_key(caller="c", tool="write_file", arguments={"x": 2}, session_id="s") + assert k != idempotency_key(caller="c", tool="write_file", arguments={"x": 1}, session_id="t") + + +def test_recorded_gate_retry_maps_to_same_key_despite_new_request_id(): + """Real G1 gate evidence: Goose sent a new request id on the model's retry.""" + writes = [ + r for r in map(json.loads, FIXTURE.read_text().splitlines()) if r["tool"] == "write_file" + ] + assert len(writes) == 2 + ids = [w["meta"]["agent-tool-call-request-id"] for w in writes] + assert ids[0] != ids[1] + assert all(w["protocol"] == "2026-07-28" for w in writes) + args = {"path": writes[0]["path"], "content": "G1 gate"} + keys = { + idempotency_key( + caller="goose-local", + tool="write_file", + arguments=args, + session_id=w["meta"]["agent-session-id"], + ) + for w in writes + } + assert len(keys) == 1 + + +def test_ledger_replays_inside_window_and_reruns_after(tmp_path): + led = Ledger(tmp_path / "l.db", window_seconds=10) + assert led.claim("k", tool="t", args_hash="h", request_id="r1", now=100).action == "run" + led.finish("k", "completed", "ok") + c = led.claim("k", tool="t", args_hash="h", request_id="r2", now=105) + assert (c.action, c.result) == ("replay", "ok") + assert led.claim("k", tool="t", args_hash="h", request_id="r3", now=111).action == "run" + assert led.get("k")["executions"] == 2 + + +def test_failed_unknown_is_never_rerun(tmp_path): + led = Ledger(tmp_path / "l.db", window_seconds=10) + led.claim("k", tool="t", args_hash="h", request_id=None, now=0) + led.finish("k", "failed_unknown") + for now in (1, 10_000): + assert led.claim("k", tool="t", args_hash="h", request_id=None, now=now).action == "refuse" + assert led.get("k")["executions"] == 1 + + +def test_crash_in_flight_becomes_failed_unknown(tmp_path): + led = Ledger(tmp_path / "l.db") + led.claim("k", tool="t", args_hash="h", request_id=None) + assert Ledger(tmp_path / "l.db").mark_stale_in_flight_unknown() == 1 + assert led.get("k")["status"] == "failed_unknown" + + +def test_definite_failure_may_rerun(tmp_path): + led = Ledger(tmp_path / "l.db") + led.claim("k", tool="t", args_hash="h", request_id=None) + led.finish("k", "failed") + assert led.claim("k", tool="t", args_hash="h", request_id=None).action == "run" + + +def test_window_must_be_positive(tmp_path): + with pytest.raises(ValueError): + Ledger(tmp_path / "l.db", window_seconds=0) + + +POLICY = {"rules": [{"id": "w", "tool": "write_file", "folder": "/tmp/amw-allowed"}]} + + +def test_permits(): + assert permits.check(POLICY, "amw__write_file", {"path": "/tmp/amw-allowed/a"}).allowed + assert not permits.check(POLICY, "amw__write_file", {"path": "/tmp/amw-allowed/../x"}).allowed + assert not permits.check(POLICY, "amw__write_file", {"path": "/etc/x"}).allowed + assert not permits.check(POLICY, "amw__read_text_file", {"path": "/tmp/amw-allowed/a"}).allowed + assert not permits.check(POLICY, "write_file", {}).allowed + + +def test_hook_blocks_with_reason_and_allows(): + out = hook.decide({"tool_name": "amw__write_file", "tool_input": {"path": "/etc/x"}}, POLICY) + assert out["decision"] == "block" and "no permit" in out["reason"] + ok = {"tool_name": "amw__write_file", "tool_input": {"path": "/tmp/amw-allowed/a"}} + assert hook.decide(ok, POLICY) == {"decision": "allow"} + + +def test_receipts_are_signed_and_tamper_evident(tmp_path): + signer = ReceiptSigner(load_or_create_key(tmp_path / "k.pem"), tmp_path / "r.jsonl") + r = signer.issue(tool="write_file", args_hash="sha256:x", decision="allow", outcome="completed") + assert {"tool", "args_hash", "decision", "issued_at"} <= r["body"].keys() + assert verify(r, signer.public_key_b64) + r["body"]["decision"] = "deny" + assert not verify(r, signer.public_key_b64) + assert (tmp_path / "k.pem").stat().st_mode & 0o077 == 0 From 0392a061b646a8fcb71e765d096c7b50d3edeb58 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:47:20 -0700 Subject: [PATCH 02/12] fix(goose): depend on amw-sdk>=0.4.0 and reuse its canonical_json (onboarding contract) --- integrations/goose-agent-middleware/pyproject.toml | 6 +++++- .../goose-agent-middleware/src/goose_amw/canonical.py | 9 ++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/integrations/goose-agent-middleware/pyproject.toml b/integrations/goose-agent-middleware/pyproject.toml index 2a7aa957d..97f3c65d3 100644 --- a/integrations/goose-agent-middleware/pyproject.toml +++ b/integrations/goose-agent-middleware/pyproject.toml @@ -10,6 +10,7 @@ readme = "README.md" license = "Apache-2.0" requires-python = ">=3.11" dependencies = [ + "amw-sdk>=0.4.0", "mcp>=2.3.0,<3", "cryptography>=50.0.0", ] @@ -28,4 +29,7 @@ packages = ["src/goose_amw"] line-length = 100 [tool.pytest.ini_options] -pythonpath = ["src"] +pythonpath = ["src", "../../sdk/python/src"] + +[tool.uv.sources] +amw-sdk = { path = "../../sdk/python", editable = true } diff --git a/integrations/goose-agent-middleware/src/goose_amw/canonical.py b/integrations/goose-agent-middleware/src/goose_amw/canonical.py index 4db4ef54a..746d35652 100644 --- a/integrations/goose-agent-middleware/src/goose_amw/canonical.py +++ b/integrations/goose-agent-middleware/src/goose_amw/canonical.py @@ -3,13 +3,9 @@ from __future__ import annotations import hashlib -import json from typing import Any - -def canonical_json(payload: Any) -> str: - """Sorted keys, no insignificant whitespace, ASCII only (the AMW signing form).""" - return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True) +from b2a_sdk.receipt_verifier import canonical_json def sha256_hex(text: str) -> str: @@ -35,3 +31,6 @@ def idempotency_key( "session_id": session_id, } return "amw-fb-" + sha256_hex(canonical_json(material)) + + +__all__ = ["args_hash", "canonical_json", "idempotency_key", "sha256_hex"] From 360d864fad0544e1ccefd905461bdc2ce6655c33 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:01:19 -0700 Subject: [PATCH 03/12] fix(goose): real-data-only tests; refuse writes without agent-session-id (review 5637421971) --- integrations/goose-agent-middleware/README.md | 5 +- .../src/goose_amw/proxy.py | 22 +- .../goose-agent-middleware/tests/test_core.py | 200 +++++++++++++----- 3 files changed, 166 insertions(+), 61 deletions(-) diff --git a/integrations/goose-agent-middleware/README.md b/integrations/goose-agent-middleware/README.md index 5fda05706..63110bbd8 100644 --- a/integrations/goose-agent-middleware/README.md +++ b/integrations/goose-agent-middleware/README.md @@ -39,8 +39,9 @@ Goose (protocol 2026-07-28) sends `_meta["agent-tool-call-request-id"]`, but that id is the model's tool-call id: when a call fails and the model retries, Goose sends a **new** id (recorded in `tests/fixtures/g1_gate_calls.jsonl`). AMW therefore logs it on receipts and in the ledger but never uses it as the -key. Older protocols without `_meta` use the same fallback key; a missing -session id is treated as the empty string. +key. A **write without `agent-session-id`** (for example an older protocol with +no `_meta`) is refused with a clear reason and a `refuse` receipt, because it +cannot be deduplicated safely. Reads do not need a session id. The caller is verified from the `Authorization: Bearer` header against `AMW_CALLERS` (a JSON map of `sha256(token)` to caller id). Unverified calls diff --git a/integrations/goose-agent-middleware/src/goose_amw/proxy.py b/integrations/goose-agent-middleware/src/goose_amw/proxy.py index 21f6edb1c..074312446 100644 --- a/integrations/goose-agent-middleware/src/goose_amw/proxy.py +++ b/integrations/goose-agent-middleware/src/goose_amw/proxy.py @@ -152,7 +152,7 @@ def __init__( async def handle(self, tool: str, arguments: dict[str, Any], ctx: Context, *, write: bool): meta = _meta(ctx) request_id = meta.get(REQUEST_ID_KEY) - session_id = meta.get(SESSION_ID_KEY) or "" + session_id = meta.get(SESSION_ID_KEY) or None ahash = args_hash(arguments) base = {"protocol": ctx.protocol_version, "agent_tool_call_request_id": request_id} caller = verify_caller(ctx.headers, self.config.callers) @@ -170,11 +170,27 @@ async def handle(self, tool: str, arguments: dict[str, Any], ctx: Context, *, wr ) raise ToolError(f"AMW permit denied: {decision.reason}") - key = idempotency_key(caller=caller, tool=tool, arguments=arguments, session_id=session_id) - base["idempotency_key"] = key if not write: return await self._run(tool, arguments, ahash, base, key=None) + if not session_id: + reason = ( + f"{tool} needs _meta['{SESSION_ID_KEY}'] to be deduplicated safely; " + "the client sent none, so the write was not run" + ) + self.signer.issue( + tool=tool, + args_hash=ahash, + decision="refuse", + outcome="not_run", + reason=reason, + **base, + ) + raise ToolError(f"AMW refused: {reason}") + + key = idempotency_key(caller=caller, tool=tool, arguments=arguments, session_id=session_id) + base["idempotency_key"] = key + claim = self.ledger.claim(key, tool=tool, args_hash=ahash, request_id=request_id) if claim.action == "replay": self.signer.issue( diff --git a/integrations/goose-agent-middleware/tests/test_core.py b/integrations/goose-agent-middleware/tests/test_core.py index 9a2b23a3e..0f688b792 100644 --- a/integrations/goose-agent-middleware/tests/test_core.py +++ b/integrations/goose-agent-middleware/tests/test_core.py @@ -1,85 +1,132 @@ +"""Unit tests. Every value comes from the real G1 gate recording or is made at runtime.""" + +import asyncio import json +import secrets +import uuid from pathlib import Path +from types import SimpleNamespace import pytest +from mcp.server.mcpserver.exceptions import ToolError from goose_amw import hook, permits -from goose_amw.canonical import args_hash, canonical_json, idempotency_key -from goose_amw.ledger import Ledger +from goose_amw.canonical import args_hash, canonical_json, idempotency_key, sha256_hex +from goose_amw.ledger import DEFAULT_WINDOW_SECONDS, Ledger +from goose_amw.proxy import Config, Gateway from goose_amw.receipts import ReceiptSigner, load_or_create_key, verify FIXTURE = Path(__file__).parent / "fixtures" / "g1_gate_calls.jsonl" +RECORDS = [json.loads(line) for line in FIXTURE.read_text().splitlines()] +WRITES = [r for r in RECORDS if r["tool"] == "write_file"] +READ = next(r for r in RECORDS if r["tool"] != "write_file") +W = WRITES[0] +SESSION = W["meta"]["agent-session-id"] +ARGS = {"path": W["path"]} # the only argument field the recording holds -def test_canonical_hash_ignores_key_order(): - assert canonical_json({"b": 1, "a": [2]}) == '{"a":[2],"b":1}' - assert args_hash({"path": "p", "content": "c"}) == args_hash({"content": "c", "path": "p"}) +def rid(record): + return record["meta"]["agent-tool-call-request-id"] -def test_key_inputs(): - k = idempotency_key(caller="c", tool="write_file", arguments={"x": 1}, session_id="s") - assert k == idempotency_key(caller="c", tool="write_file", arguments={"x": 1}, session_id="s") - assert k != idempotency_key(caller="d", tool="write_file", arguments={"x": 1}, session_id="s") - assert k != idempotency_key( - caller="c", tool="read_text_file", arguments={"x": 1}, session_id="s" - ) - assert k != idempotency_key(caller="c", tool="write_file", arguments={"x": 2}, session_id="s") - assert k != idempotency_key(caller="c", tool="write_file", arguments={"x": 1}, session_id="t") +def fresh(): + return str(uuid.uuid4()) + + +def test_canonical_hash_ignores_key_order(): + meta = W["meta"] + reordered = dict(reversed(list(meta.items()))) + assert canonical_json(meta) == canonical_json(reordered) + assert args_hash(meta) == args_hash(reordered) + + +def test_key_changes_with_each_input_and_never_uses_request_id(tmp_path): + caller = fresh() + k = idempotency_key(caller=caller, tool=W["tool"], arguments=ARGS, session_id=SESSION) + assert rid(W) not in k + assert k == idempotency_key(caller=caller, tool=W["tool"], arguments=ARGS, session_id=SESSION) + for variant in ( + {"caller": fresh(), "tool": W["tool"], "arguments": ARGS, "session_id": SESSION}, + {"caller": caller, "tool": READ["tool"], "arguments": ARGS, "session_id": SESSION}, + { + "caller": caller, + "tool": W["tool"], + "arguments": {"path": str(tmp_path)}, + "session_id": SESSION, + }, + {"caller": caller, "tool": W["tool"], "arguments": ARGS, "session_id": fresh()}, + ): + assert idempotency_key(**variant) != k def test_recorded_gate_retry_maps_to_same_key_despite_new_request_id(): """Real G1 gate evidence: Goose sent a new request id on the model's retry.""" - writes = [ - r for r in map(json.loads, FIXTURE.read_text().splitlines()) if r["tool"] == "write_file" - ] - assert len(writes) == 2 - ids = [w["meta"]["agent-tool-call-request-id"] for w in writes] - assert ids[0] != ids[1] - assert all(w["protocol"] == "2026-07-28" for w in writes) - args = {"path": writes[0]["path"], "content": "G1 gate"} + assert len(WRITES) == 2 + assert rid(WRITES[0]) != rid(WRITES[1]) + assert all(w["protocol"] == "2026-07-28" for w in WRITES) + caller = fresh() keys = { idempotency_key( - caller="goose-local", - tool="write_file", - arguments=args, + caller=caller, + tool=w["tool"], + arguments={"path": w["path"]}, session_id=w["meta"]["agent-session-id"], ) - for w in writes + for w in WRITES } assert len(keys) == 1 +def _gate_key(): + return idempotency_key(caller=fresh(), tool=W["tool"], arguments=ARGS, session_id=SESSION) + + def test_ledger_replays_inside_window_and_reruns_after(tmp_path): - led = Ledger(tmp_path / "l.db", window_seconds=10) - assert led.claim("k", tool="t", args_hash="h", request_id="r1", now=100).action == "run" - led.finish("k", "completed", "ok") - c = led.claim("k", tool="t", args_hash="h", request_id="r2", now=105) - assert (c.action, c.result) == ("replay", "ok") - assert led.claim("k", tool="t", args_hash="h", request_id="r3", now=111).action == "run" - assert led.get("k")["executions"] == 2 + led = Ledger(tmp_path / "l.db") + key, ahash, t0 = _gate_key(), args_hash(ARGS), W["ts"] + result = fresh() + assert ( + led.claim(key, tool=W["tool"], args_hash=ahash, request_id=rid(W), now=t0).action == "run" + ) + led.finish(key, "completed", result) + retry = led.claim( + key, tool=W["tool"], args_hash=ahash, request_id=rid(WRITES[1]), now=WRITES[1]["ts"] + ) + assert (retry.action, retry.result) == ("replay", result) + later = t0 + DEFAULT_WINDOW_SECONDS + 1 + assert ( + led.claim(key, tool=W["tool"], args_hash=ahash, request_id=fresh(), now=later).action + == "run" + ) + assert led.get(key)["executions"] == 2 def test_failed_unknown_is_never_rerun(tmp_path): - led = Ledger(tmp_path / "l.db", window_seconds=10) - led.claim("k", tool="t", args_hash="h", request_id=None, now=0) - led.finish("k", "failed_unknown") - for now in (1, 10_000): - assert led.claim("k", tool="t", args_hash="h", request_id=None, now=now).action == "refuse" - assert led.get("k")["executions"] == 1 + led = Ledger(tmp_path / "l.db") + key, ahash, t0 = _gate_key(), args_hash(ARGS), W["ts"] + led.claim(key, tool=W["tool"], args_hash=ahash, request_id=rid(W), now=t0) + led.finish(key, "failed_unknown") + for now in (WRITES[1]["ts"], t0 + 10 * DEFAULT_WINDOW_SECONDS): + claim = led.claim(key, tool=W["tool"], args_hash=ahash, request_id=rid(WRITES[1]), now=now) + assert claim.action == "refuse" + assert led.get(key)["executions"] == 1 def test_crash_in_flight_becomes_failed_unknown(tmp_path): led = Ledger(tmp_path / "l.db") - led.claim("k", tool="t", args_hash="h", request_id=None) + key = _gate_key() + led.claim(key, tool=W["tool"], args_hash=args_hash(ARGS), request_id=rid(W)) assert Ledger(tmp_path / "l.db").mark_stale_in_flight_unknown() == 1 - assert led.get("k")["status"] == "failed_unknown" + assert led.get(key)["status"] == "failed_unknown" def test_definite_failure_may_rerun(tmp_path): led = Ledger(tmp_path / "l.db") - led.claim("k", tool="t", args_hash="h", request_id=None) - led.finish("k", "failed") - assert led.claim("k", tool="t", args_hash="h", request_id=None).action == "run" + key = _gate_key() + led.claim(key, tool=W["tool"], args_hash=args_hash(ARGS), request_id=rid(W)) + led.finish(key, "failed") + claim = led.claim(key, tool=W["tool"], args_hash=args_hash(ARGS), request_id=rid(WRITES[1])) + assert claim.action == "run" def test_window_must_be_positive(tmp_path): @@ -87,29 +134,70 @@ def test_window_must_be_positive(tmp_path): Ledger(tmp_path / "l.db", window_seconds=0) -POLICY = {"rules": [{"id": "w", "tool": "write_file", "folder": "/tmp/amw-allowed"}]} +def _policy(tmp_path): + allowed = tmp_path / fresh() + allowed.mkdir() + return allowed, {"rules": [{"id": fresh(), "tool": W["tool"], "folder": str(allowed)}]} -def test_permits(): - assert permits.check(POLICY, "amw__write_file", {"path": "/tmp/amw-allowed/a"}).allowed - assert not permits.check(POLICY, "amw__write_file", {"path": "/tmp/amw-allowed/../x"}).allowed - assert not permits.check(POLICY, "amw__write_file", {"path": "/etc/x"}).allowed - assert not permits.check(POLICY, "amw__read_text_file", {"path": "/tmp/amw-allowed/a"}).allowed - assert not permits.check(POLICY, "write_file", {}).allowed +def test_permits(tmp_path): + allowed, policy = _policy(tmp_path) + inside = str(allowed / fresh()) + prefixed = f"amw__{W['tool']}" + assert permits.check(policy, prefixed, {"path": inside}).allowed + assert not permits.check(policy, prefixed, {"path": f"{allowed}/../{fresh()}"}).allowed + assert not permits.check(policy, prefixed, {"path": str(tmp_path / fresh())}).allowed + assert not permits.check(policy, f"amw__{READ['tool']}", {"path": inside}).allowed + assert not permits.check(policy, W["tool"], {}).allowed -def test_hook_blocks_with_reason_and_allows(): - out = hook.decide({"tool_name": "amw__write_file", "tool_input": {"path": "/etc/x"}}, POLICY) +def test_hook_blocks_with_reason_and_allows(tmp_path): + allowed, policy = _policy(tmp_path) + name = f"amw__{W['tool']}" + out = hook.decide({"tool_name": name, "tool_input": {"path": str(tmp_path / fresh())}}, policy) assert out["decision"] == "block" and "no permit" in out["reason"] - ok = {"tool_name": "amw__write_file", "tool_input": {"path": "/tmp/amw-allowed/a"}} - assert hook.decide(ok, POLICY) == {"decision": "allow"} + ok = {"tool_name": name, "tool_input": {"path": str(allowed / fresh())}} + assert hook.decide(ok, policy) == {"decision": "allow"} def test_receipts_are_signed_and_tamper_evident(tmp_path): signer = ReceiptSigner(load_or_create_key(tmp_path / "k.pem"), tmp_path / "r.jsonl") - r = signer.issue(tool="write_file", args_hash="sha256:x", decision="allow", outcome="completed") + r = signer.issue( + tool=W["tool"], args_hash=args_hash(ARGS), decision="allow", outcome="completed" + ) assert {"tool", "args_hash", "decision", "issued_at"} <= r["body"].keys() assert verify(r, signer.public_key_b64) r["body"]["decision"] = "deny" assert not verify(r, signer.public_key_b64) assert (tmp_path / "k.pem").stat().st_mode & 0o077 == 0 + + +def test_write_without_session_id_is_refused_and_not_run(tmp_path): + allowed, policy = _policy(tmp_path) + token = secrets.token_hex(24) + cfg = Config( + policy=policy, + state_dir=tmp_path / "state", + callers={sha256_hex(token): fresh()}, + fs_root=str(tmp_path), + ) + calls = [] + + async def upstream(tool, arguments): + calls.append(tool) + return fresh() + + gw = Gateway(cfg, upstream=upstream) + ctx = SimpleNamespace( + request_context=SimpleNamespace(meta={}), + headers={"authorization": f"Bearer {token}"}, + protocol_version=None, + ) + args = {"path": str(allowed / fresh()), "content": fresh()} + with pytest.raises(ToolError, match="agent-session-id"): + asyncio.run(gw.handle(W["tool"], args, ctx, write=True)) + assert calls == [] + receipt = json.loads((cfg.state_dir / "receipts.jsonl").read_text().splitlines()[-1]) + assert receipt["body"]["decision"] == "refuse" + assert receipt["body"]["outcome"] == "not_run" + assert verify(receipt, gw.signer.public_key_b64) From ed3200321a4e511070ba206a9ac352b75b8b810c Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:03:16 -0700 Subject: [PATCH 04/12] feat(gateway): add input_required human approval gate for irreversible MCP calls Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/routers/approvals.py | 97 ++++++ gateway/app/services/approval_gate.py | 454 +++++++++++++++++++++++++ gateway/scripts/amw_approvals.py | 112 ++++++ gateway/tests/test_approval_gate.py | 220 ++++++++++++ gateway/tests/test_approvals_router.py | 109 ++++++ 5 files changed, 992 insertions(+) create mode 100644 gateway/app/routers/approvals.py create mode 100644 gateway/app/services/approval_gate.py create mode 100644 gateway/scripts/amw_approvals.py create mode 100644 gateway/tests/test_approval_gate.py create mode 100644 gateway/tests/test_approvals_router.py diff --git a/gateway/app/routers/approvals.py b/gateway/app/routers/approvals.py new file mode 100644 index 000000000..20204212c --- /dev/null +++ b/gateway/app/routers/approvals.py @@ -0,0 +1,97 @@ +"""Local-only human approval endpoints (AMW V2). + +A human on the gateway host approves or denies paused irreversible tool calls +here (or via ``gateway/scripts/amw_approvals.py``). Every endpoint rejects +non-loopback clients with 403. This router is intentionally not mounted in +``main.py`` yet; mounting lands with the ``mcp_standard.py`` hook in a later PR. +""" + +from __future__ import annotations + +import time + +from fastapi import APIRouter, Depends, HTTPException, Request +from pydantic import BaseModel + +from app.services.approval_gate import ApprovalStore, InMemoryApprovalStore + +router = APIRouter(prefix="/v1/approvals", tags=["Approvals"]) + +LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"}) + + +def require_loopback(request: Request) -> None: + """Allow only clients on the gateway host itself.""" + host = request.client.host if request.client else "" + if host not in LOOPBACK_HOSTS: + raise HTTPException(status_code=403, detail="approvals are local-only") + + +_store: ApprovalStore = InMemoryApprovalStore() + + +def get_approval_store() -> ApprovalStore: + return _store + + +def set_approval_store_for_tests(store: ApprovalStore) -> None: + global _store + _store = store + + +class PendingApproval(BaseModel): + nonce: str + tool: str + principal: str + args_hash: str + created_at: float + deadline: float + + +class PendingApprovalsResponse(BaseModel): + approvals: list[PendingApproval] + + +class DecisionResponse(BaseModel): + nonce: str + status: str + + +@router.get("/pending", response_model=PendingApprovalsResponse) +async def list_pending( + _local: None = Depends(require_loopback), +) -> PendingApprovalsResponse: + approvals = [ + PendingApproval( + nonce=record.nonce, + tool=record.tool, + principal=record.principal, + args_hash=record.args_hash, + created_at=record.created_at, + deadline=record.deadline, + ) + for record in get_approval_store().list_pending() + ] + return PendingApprovalsResponse(approvals=approvals) + + +@router.post("/{nonce}/approve", response_model=DecisionResponse) +async def approve( + nonce: str, + _local: None = Depends(require_loopback), +) -> DecisionResponse: + record = get_approval_store().decide(nonce, True, now=time.time()) + if record is None: + raise HTTPException(status_code=404, detail="approval_not_found") + return DecisionResponse(nonce=record.nonce, status=record.status) + + +@router.post("/{nonce}/deny", response_model=DecisionResponse) +async def deny( + nonce: str, + _local: None = Depends(require_loopback), +) -> DecisionResponse: + record = get_approval_store().decide(nonce, False, now=time.time()) + if record is None: + raise HTTPException(status_code=404, detail="approval_not_found") + return DecisionResponse(nonce=record.nonce, status=record.status) diff --git a/gateway/app/services/approval_gate.py b/gateway/app/services/approval_gate.py new file mode 100644 index 000000000..ac2869901 --- /dev/null +++ b/gateway/app/services/approval_gate.py @@ -0,0 +1,454 @@ +"""Human approval gate for irreversible MCP tool calls (AMW V2). + +SEP-2322 flow: the first ``tools/call`` for an irreversible tool PAUSEs with a +``resultType='input_required'`` result carrying an opaque ``requestState``. The +client retries the same ``tools/call`` with ``inputResponses`` plus the +``requestState``; this gate EXECUTEs only after a local human approved, else it +REJECTs. The hook in ``mcp_standard.py`` that calls :meth:`ApprovalGate.evaluate` +lands in a later PR. + +Fail-closed rules: + +- The idempotency key is the single G1 key from + ``goose_amw.canonical.idempotency_key`` (verified caller + tool + canonical + args hash + agent session id). The Goose request id is logged only. +- ``requestState`` is HMAC-SHA256 sealed; missing secret fails closed. +- Clients without ``input_required`` support are rejected. +- Deny, timeout, and tampering each emit a receipt via an injectable sink and + never execute. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import hmac +import json +import logging +import os +import secrets +import threading +import time +from dataclasses import dataclass, replace +from typing import Any, Callable, Literal + +logger = logging.getLogger(__name__) + +STATE_SECRET_ENV = "AMW_APPROVAL_STATE_SECRET" +TTL_ENV = "AMW_APPROVAL_TTL_SECONDS" +DEFAULT_TTL_SECONDS = 300 +MIN_TTL_SECONDS = 30 +MAX_TTL_SECONDS = 3600 +STATE_VERSION = 1 + +DecisionAction = Literal["PAUSE", "EXECUTE", "REJECT"] +RejectReason = Literal[ + "denied", + "timeout", + "tampered", + "unsupported_client", + "args_mismatch", + "principal_mismatch", + "replayed", +] +ApprovalStatus = Literal["pending", "approved", "denied", "expired"] + + +class ApprovalGateUnavailable(RuntimeError): + """The gate cannot operate safely (missing secret or missing key module).""" + + +class _StateTampered(ValueError): + """Internal: requestState failed authentication or parsing.""" + + +def _load_canonical() -> Any: + """Import goose_amw.canonical lazily; fail closed when absent.""" + try: + from goose_amw import canonical as canonical_module + except ImportError as exc: + raise ApprovalGateUnavailable( + "goose_amw is not importable; approval gate refuses to run " + "without the canonical idempotency key" + ) from exc + return canonical_module + + +def _ttl_from_env() -> int: + try: + return int(os.environ.get(TTL_ENV, str(DEFAULT_TTL_SECONDS))) + except ValueError: + return DEFAULT_TTL_SECONDS + + +def _clamp_ttl(value: int) -> int: + return max(MIN_TTL_SECONDS, min(MAX_TTL_SECONDS, value)) + + +def _b64encode(data: bytes) -> str: + return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") + + +def _b64decode(data: str) -> bytes: + try: + return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4)) + except (binascii.Error, ValueError) as exc: + raise _StateTampered("bad base64url") from exc + + +def _seal_state(secret: bytes, payload: dict[str, Any]) -> str: + body = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8") + signature = hmac.new(secret, body, hashlib.sha256).digest() + return f"{_b64encode(body)}.{_b64encode(signature)}" + + +def _unseal_state(secret: bytes, token: str) -> dict[str, Any]: + try: + encoded_body, encoded_sig = token.split(".", 1) + body = _b64decode(encoded_body) + signature = _b64decode(encoded_sig) + except ValueError as exc: + raise _StateTampered("malformed state") from exc + expected = hmac.new(secret, body, hashlib.sha256).digest() + if not hmac.compare_digest(signature, expected): + raise _StateTampered("bad signature") + try: + payload = json.loads(body.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise _StateTampered("bad payload") from exc + if not isinstance(payload, dict) or payload.get("v") != STATE_VERSION: + raise _StateTampered("unknown state version") + return payload + + +@dataclass +class ApprovalRecord: + """One pending human decision. Raw args are never stored, only their hash.""" + + nonce: str + idempotency_key: str + args_hash: str + principal: str + tool: str + session_id: str + status: ApprovalStatus = "pending" + created_at: float = 0.0 + deadline: float = 0.0 + decided_at: float | None = None + consumed: bool = False + + +class ApprovalStore: + """Interface for pending approvals so a DB-backed store can replace memory.""" + + def save(self, record: ApprovalRecord) -> None: + raise NotImplementedError + + def get(self, nonce: str) -> ApprovalRecord | None: + raise NotImplementedError + + def list_pending(self) -> list[ApprovalRecord]: + raise NotImplementedError + + def decide( + self, nonce: str, approved: bool, *, now: float + ) -> ApprovalRecord | None: + """Flip pending to approved/denied; None when missing or not pending.""" + raise NotImplementedError + + def consume(self, nonce: str) -> ApprovalRecord | None: + """Single-use: first call on approved marks consumed; later calls None.""" + raise NotImplementedError + + def mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: + """Flip pending to expired; None when missing.""" + raise NotImplementedError + + +class InMemoryApprovalStore(ApprovalStore): + """Thread-safe in-memory store. Process restart drops pending approvals.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._records: dict[str, ApprovalRecord] = {} + + def save(self, record: ApprovalRecord) -> None: + with self._lock: + self._records[record.nonce] = replace(record) + + def get(self, nonce: str) -> ApprovalRecord | None: + with self._lock: + record = self._records.get(nonce) + return replace(record) if record else None + + def list_pending(self) -> list[ApprovalRecord]: + with self._lock: + return [ + replace(record) + for record in self._records.values() + if record.status == "pending" + ] + + def decide( + self, nonce: str, approved: bool, *, now: float + ) -> ApprovalRecord | None: + with self._lock: + record = self._records.get(nonce) + if record is None or record.status != "pending": + return None + updated = replace( + record, + status="approved" if approved else "denied", + decided_at=now, + ) + self._records[nonce] = updated + return replace(updated) + + def consume(self, nonce: str) -> ApprovalRecord | None: + with self._lock: + record = self._records.get(nonce) + if record is None or record.status != "approved" or record.consumed: + return None + updated = replace(record, consumed=True) + self._records[nonce] = updated + return replace(updated) + + def mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: + with self._lock: + record = self._records.get(nonce) + if record is None: + return None + if record.status == "pending": + record = replace(record, status="expired", decided_at=now) + self._records[nonce] = record + return replace(record) + + +ReceiptSink = Callable[[str, dict[str, Any]], None] + + +def _log_receipt_sink(event: str, record: dict[str, Any]) -> None: + logger.info( + "approval_receipt event=%s record=%s", event, json.dumps(record, sort_keys=True) + ) + + +@dataclass(frozen=True) +class ApprovalDecision: + action: DecisionAction + payload: dict[str, Any] | None = None + idempotency_key: str | None = None + reason: RejectReason | None = None + nonce: str | None = None + + +class ApprovalGate: + """Entry point for the future mcp_standard.py hook.""" + + def __init__( + self, + *, + secret: str | None = None, + ttl_seconds: int | None = None, + store: ApprovalStore | None = None, + clock: Callable[[], float] = time.time, + receipt_sink: ReceiptSink | None = None, + ) -> None: + raw_secret = ( + secret if secret is not None else os.environ.get(STATE_SECRET_ENV, "") + ) + self._secret = raw_secret.encode("utf-8") if raw_secret else None + ttl = ttl_seconds if ttl_seconds is not None else _ttl_from_env() + self._ttl = _clamp_ttl(ttl) + self.store = store or InMemoryApprovalStore() + self.clock = clock + self.receipt_sink = receipt_sink or _log_receipt_sink + + def _require_secret(self) -> bytes: + if not self._secret: + raise ApprovalGateUnavailable( + f"{STATE_SECRET_ENV} is not set; approval gate refuses to run unsealed" + ) + return self._secret + + def _emit(self, event: str, **fields: Any) -> None: + self.receipt_sink(event, fields) + + def evaluate( + self, + caller: str, + tool: str, + arguments: dict[str, Any] | None, + session_id: str, + client_supports_input_required: bool, + request_state: str | None = None, + input_responses: list[Any] | dict[str, Any] | None = None, + request_id: str | None = None, + ) -> ApprovalDecision: + """Decide PAUSE, EXECUTE, or REJECT for one tools/call attempt.""" + canonical = _load_canonical() + if request_id is not None: + logger.debug("approval request_id=%s logged only, never keyed", request_id) + args_hash = canonical.args_hash(arguments) + idempotency_key = canonical.idempotency_key( + caller=caller, tool=tool, arguments=arguments, session_id=session_id + ) + if request_state is None: + return self._pause_new_call( + caller=caller, + tool=tool, + session_id=session_id, + args_hash=args_hash, + idempotency_key=idempotency_key, + client_supports_input_required=client_supports_input_required, + ) + return self._evaluate_retry( + caller=caller, + tool=tool, + session_id=session_id, + args_hash=args_hash, + idempotency_key=idempotency_key, + client_supports_input_required=client_supports_input_required, + request_state=request_state, + ) + + def _pause_new_call( + self, + *, + caller: str, + tool: str, + session_id: str, + args_hash: str, + idempotency_key: str, + client_supports_input_required: bool, + ) -> ApprovalDecision: + if not client_supports_input_required: + return ApprovalDecision(action="REJECT", reason="unsupported_client") + secret = self._require_secret() + now = self.clock() + nonce = secrets.token_urlsafe(16) + deadline = now + self._ttl + self.store.save( + ApprovalRecord( + nonce=nonce, + idempotency_key=idempotency_key, + args_hash=args_hash, + principal=caller, + tool=tool, + session_id=session_id, + created_at=now, + deadline=deadline, + ) + ) + state = _seal_state( + secret, + { + "v": STATE_VERSION, + "argsHash": args_hash, + "principal": caller, + "deadline": deadline, + "nonce": nonce, + }, + ) + return ApprovalDecision( + action="PAUSE", + nonce=nonce, + payload={ + "resultType": "input_required", + "inputRequests": [ + { + "requestId": nonce, + "prompt": f"Approve tool call: {tool}", + "schema": { + "type": "object", + "properties": {"approved": {"type": "boolean"}}, + "required": ["approved"], + }, + } + ], + "requestState": state, + }, + ) + + def _evaluate_retry( + self, + *, + caller: str, + tool: str, + session_id: str, + args_hash: str, + idempotency_key: str, + client_supports_input_required: bool, + request_state: str, + ) -> ApprovalDecision: + if not client_supports_input_required: + return ApprovalDecision(action="REJECT", reason="unsupported_client") + secret = self._require_secret() + try: + sealed = _unseal_state(secret, request_state) + except _StateTampered: + self._emit( + "tampered", + nonce=None, + tool=tool, + principal=caller, + session_id=session_id, + ) + return ApprovalDecision(action="REJECT", reason="tampered") + nonce = sealed.get("nonce") + if sealed.get("principal") != caller: + self._emit("principal_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="principal_mismatch", nonce=nonce + ) + if sealed.get("argsHash") != args_hash: + self._emit("args_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="args_mismatch", nonce=nonce + ) + record = self.store.get(nonce) if isinstance(nonce, str) else None + if record is None: + self._emit("tampered", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="tampered", nonce=nonce) + now = self.clock() + sealed_deadline = sealed.get("deadline") + if ( + not isinstance(sealed_deadline, (int, float)) + or now > sealed_deadline + or now > record.deadline + or record.status == "expired" + ): + self.store.mark_expired(nonce, now=now) + self._emit("timeout", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="timeout", nonce=nonce) + if record.status == "denied": + self._emit("denied", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="denied", nonce=nonce) + if record.status == "pending": + return ApprovalDecision( + action="PAUSE", + nonce=nonce, + payload={ + "resultType": "input_required", + "inputRequests": [ + { + "requestId": nonce, + "prompt": f"Approve tool call: {tool}", + "schema": { + "type": "object", + "properties": {"approved": {"type": "boolean"}}, + "required": ["approved"], + }, + } + ], + "requestState": request_state, + }, + ) + consumed = self.store.consume(nonce) + if consumed is None: + self._emit("replayed", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="replayed", nonce=nonce) + return ApprovalDecision( + action="EXECUTE", idempotency_key=idempotency_key, nonce=nonce + ) diff --git a/gateway/scripts/amw_approvals.py b/gateway/scripts/amw_approvals.py new file mode 100644 index 000000000..d22288236 --- /dev/null +++ b/gateway/scripts/amw_approvals.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Local approve/deny CLI for AMW V2 pending approvals. + +Talks to the gateway's local-only endpoints over loopback; run on the gateway +host. In-process callers can use the approval store directly instead. + +Usage: + python gateway/scripts/amw_approvals.py list + python gateway/scripts/amw_approvals.py approve + python gateway/scripts/amw_approvals.py deny +""" + +from __future__ import annotations + +import argparse +import os +import sys +from datetime import datetime, timezone + +import httpx + +DEFAULT_BASE_URL = "http://127.0.0.1:8000" +BASE_URL_ENV = "AMW_GATEWAY_URL" + + +def _client(base_url: str) -> httpx.Client: + return httpx.Client(base_url=base_url, timeout=10.0) + + +def _format_time(value: float) -> str: + return datetime.fromtimestamp(value, tz=timezone.utc).strftime( + "%Y-%m-%d %H:%M:%S UTC" + ) + + +def cmd_list(args: argparse.Namespace) -> int: + try: + response = _client(args.base_url).get("/v1/approvals/pending") + response.raise_for_status() + except httpx.HTTPError as exc: + print( + f"error: gateway not reachable at {args.base_url}: {exc}", file=sys.stderr + ) + return 1 + approvals = response.json().get("approvals", []) + if not approvals: + print("no pending approvals") + return 0 + for item in approvals: + print( + f"{item['nonce']} tool={item['tool']} principal={item['principal']} " + f"deadline={_format_time(item['deadline'])}" + ) + return 0 + + +def _decide(args: argparse.Namespace, action: str) -> int: + try: + response = _client(args.base_url).post(f"/v1/approvals/{args.nonce}/{action}") + except httpx.HTTPError as exc: + print( + f"error: gateway not reachable at {args.base_url}: {exc}", file=sys.stderr + ) + return 1 + if response.status_code == 404: + print( + f"error: unknown or already decided approval: {args.nonce}", file=sys.stderr + ) + return 1 + if response.status_code == 403: + print( + "error: approvals are local-only; run on the gateway host", file=sys.stderr + ) + return 1 + try: + response.raise_for_status() + except httpx.HTTPError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"{args.nonce}: {response.json().get('status')}") + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Approve or deny pending AMW tool calls." + ) + parser.add_argument( + "--base-url", + default=os.environ.get(BASE_URL_ENV, DEFAULT_BASE_URL), + help=f"gateway base URL (env {BASE_URL_ENV})", + ) + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("list", help="list pending approvals") + approve = sub.add_parser("approve", help="approve a pending tool call") + approve.add_argument("nonce", help="approval nonce from list") + deny = sub.add_parser("deny", help="deny a pending tool call") + deny.add_argument("nonce", help="approval nonce from list") + return parser + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + if args.command == "list": + return cmd_list(args) + if args.command in ("approve", "deny"): + return _decide(args, args.command) + raise AssertionError(f"unknown command: {args.command}") + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gateway/tests/test_approval_gate.py b/gateway/tests/test_approval_gate.py new file mode 100644 index 000000000..41835c1c9 --- /dev/null +++ b/gateway/tests/test_approval_gate.py @@ -0,0 +1,220 @@ +"""Data-free tests for the AMW V2 approval gate state machine.""" + +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +for _path in ( + REPO_ROOT / "integrations" / "goose-agent-middleware" / "src", + REPO_ROOT / "sdk" / "python" / "src", +): + if str(_path) not in sys.path: + sys.path.insert(0, str(_path)) + +from typing import Any # noqa: E402 + +import pytest # noqa: E402 +from goose_amw import canonical as goose_canonical # noqa: E402 + +from app.services.approval_gate import ( # noqa: E402 + ApprovalGate, + ApprovalGateUnavailable, + InMemoryApprovalStore, +) + +SECRET = "test-state-secret" +CALLER = "caller-a" +TOOL = "tool-x" +SESSION = "session-1" +ARGS: dict[str, Any] = {} + + +class _Clock: + def __init__(self, now: float = 1_000_000.0) -> None: + self.now = now + + def __call__(self) -> float: + return self.now + + +@pytest.fixture +def receipts() -> list[tuple[str, dict[str, Any]]]: + return [] + + +@pytest.fixture +def clock() -> _Clock: + return _Clock() + + +@pytest.fixture +def gate(receipts: list[tuple[str, dict[str, Any]]], clock: _Clock) -> ApprovalGate: + return ApprovalGate( + secret=SECRET, + store=InMemoryApprovalStore(), + clock=clock, + receipt_sink=lambda event, record: receipts.append((event, record)), + ) + + +def _pause(gate: ApprovalGate) -> Any: + decision = gate.evaluate(CALLER, TOOL, ARGS, SESSION, True) + assert decision.action == "PAUSE" + assert decision.payload is not None + return decision + + +def _retry(gate: ApprovalGate, state: str, **kwargs: Any) -> Any: + params: dict[str, Any] = { + "caller": CALLER, + "tool": TOOL, + "arguments": ARGS, + "session_id": SESSION, + "client_supports_input_required": True, + "request_state": state, + "input_responses": [{"requestId": "r1", "approved": True}], + } + params.update(kwargs) + return gate.evaluate( + params.pop("caller"), + params.pop("tool"), + params.pop("arguments"), + params.pop("session_id"), + params.pop("client_supports_input_required"), + **params, + ) + + +def test_first_call_pauses_with_input_required_payload(gate: ApprovalGate) -> None: + decision = _pause(gate) + assert decision.payload is not None + assert decision.payload["resultType"] == "input_required" + assert isinstance(decision.payload["inputRequests"], list) + assert decision.payload["inputRequests"] + assert isinstance(decision.payload["requestState"], str) + assert decision.payload["requestState"] + + +def test_key_equals_goose_idempotency_key(gate: ApprovalGate) -> None: + expected = goose_canonical.idempotency_key( + caller=CALLER, tool=TOOL, arguments=ARGS, session_id=SESSION + ) + decision = _pause(gate) + assert decision.nonce is not None + gate.store.decide(decision.nonce, True, now=gate.clock()) + executed = _retry(gate, decision.payload["requestState"]) + assert executed.action == "EXECUTE" + assert executed.idempotency_key == expected + + +def test_approved_retry_executes_exactly_once( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: + decision = _pause(gate) + assert decision.nonce is not None + gate.store.decide(decision.nonce, True, now=gate.clock()) + first = _retry(gate, decision.payload["requestState"]) + assert first.action == "EXECUTE" + second = _retry(gate, decision.payload["requestState"]) + assert second.action == "REJECT" + assert second.reason == "replayed" + assert [event for event, _ in receipts] == ["replayed"] + + +def test_pending_retry_repauses(gate: ApprovalGate) -> None: + decision = _pause(gate) + again = _retry(gate, decision.payload["requestState"]) + assert again.action == "PAUSE" + assert again.payload is not None + assert again.payload["resultType"] == "input_required" + + +def test_deny_rejects_and_receipts( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: + decision = _pause(gate) + assert decision.nonce is not None + gate.store.decide(decision.nonce, False, now=gate.clock()) + rejected = _retry(gate, decision.payload["requestState"]) + assert rejected.action == "REJECT" + assert rejected.reason == "denied" + assert [event for event, _ in receipts] == ["denied"] + + +def test_expired_rejects_timeout_and_marks_expired( + gate: ApprovalGate, clock: _Clock, receipts: list[tuple[str, dict[str, Any]]] +) -> None: + decision = _pause(gate) + clock.now += 3600 + 1 + rejected = _retry(gate, decision.payload["requestState"]) + assert rejected.action == "REJECT" + assert rejected.reason == "timeout" + assert decision.nonce is not None + assert gate.store.get(decision.nonce) is not None + assert gate.store.get(decision.nonce).status == "expired" # type: ignore[union-attr] + assert [event for event, _ in receipts] == ["timeout"] + + +def test_tampered_state_rejects( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: + decision = _pause(gate) + state: str = decision.payload["requestState"] + tampered = ("A" if state[0] != "A" else "B") + state[1:] + rejected = _retry(gate, tampered) + assert rejected.action == "REJECT" + assert rejected.reason == "tampered" + assert [event for event, _ in receipts] == ["tampered"] + + +def test_unknown_nonce_rejects_tampered( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]], clock: _Clock +) -> None: + decision = _pause(gate) + fresh = ApprovalGate( + secret=SECRET, + store=InMemoryApprovalStore(), + clock=clock, + receipt_sink=lambda event, record: receipts.append((event, record)), + ) + rejected = _retry(fresh, decision.payload["requestState"]) + assert rejected.action == "REJECT" + assert rejected.reason == "tampered" + + +def test_unsupported_client_rejects_without_record(gate: ApprovalGate) -> None: + decision = gate.evaluate(CALLER, TOOL, ARGS, SESSION, False) + assert decision.action == "REJECT" + assert decision.reason == "unsupported_client" + assert gate.store.list_pending() == [] + + +def test_args_mismatch_rejects(gate: ApprovalGate) -> None: + decision = _pause(gate) + rejected = _retry(gate, decision.payload["requestState"], arguments={"k": "v"}) + assert rejected.action == "REJECT" + assert rejected.reason == "args_mismatch" + + +def test_principal_mismatch_rejects(gate: ApprovalGate) -> None: + decision = _pause(gate) + rejected = _retry(gate, decision.payload["requestState"], caller="caller-b") + assert rejected.action == "REJECT" + assert rejected.reason == "principal_mismatch" + + +def test_missing_secret_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("AMW_APPROVAL_STATE_SECRET", raising=False) + gate = ApprovalGate(store=InMemoryApprovalStore()) + with pytest.raises(ApprovalGateUnavailable): + gate.evaluate(CALLER, TOOL, ARGS, SESSION, True) + + +def test_request_id_is_logged_not_keyed(gate: ApprovalGate) -> None: + first = gate.evaluate(CALLER, TOOL, ARGS, SESSION, True, request_id="req-1") + second = gate.evaluate(CALLER, TOOL, ARGS, SESSION, True, request_id="req-2") + assert first.action == "PAUSE" + assert second.action == "PAUSE" + assert gate.store.list_pending() + keys = {record.idempotency_key for record in gate.store.list_pending()} + assert len(keys) == 1 diff --git a/gateway/tests/test_approvals_router.py b/gateway/tests/test_approvals_router.py new file mode 100644 index 000000000..4aea54fb7 --- /dev/null +++ b/gateway/tests/test_approvals_router.py @@ -0,0 +1,109 @@ +"""Data-free tests for the local-only approvals router.""" + +import time + +import pytest +from fastapi import FastAPI, HTTPException, Request +from starlette.testclient import TestClient + +from app.routers.approvals import ( + get_approval_store, + require_loopback, + router, + set_approval_store_for_tests, +) +from app.services.approval_gate import ApprovalRecord, InMemoryApprovalStore + + +@pytest.fixture +def app() -> FastAPI: + set_approval_store_for_tests(InMemoryApprovalStore()) + application = FastAPI() + application.include_router(router) + application.dependency_overrides[require_loopback] = lambda: None + return application + + +@pytest.fixture +def client(app: FastAPI) -> TestClient: + return TestClient(app) + + +def _seed(nonce: str = "nonce-1") -> ApprovalRecord: + record = ApprovalRecord( + nonce=nonce, + idempotency_key="key-1", + args_hash="sha256:abc", + principal="caller-a", + tool="tool-x", + session_id="session-1", + created_at=time.time(), + deadline=time.time() + 300, + ) + get_approval_store().save(record) + return record + + +def test_pending_lists_seeded_record(client: TestClient) -> None: + _seed() + response = client.get("/v1/approvals/pending") + assert response.status_code == 200 + approvals = response.json()["approvals"] + assert [item["nonce"] for item in approvals] == ["nonce-1"] + assert approvals[0]["tool"] == "tool-x" + + +def test_approve_flips_pending_to_approved(client: TestClient) -> None: + _seed() + response = client.post("/v1/approvals/nonce-1/approve") + assert response.status_code == 200 + assert response.json() == {"nonce": "nonce-1", "status": "approved"} + assert client.get("/v1/approvals/pending").json() == {"approvals": []} + + +def test_deny_flips_pending_to_denied(client: TestClient) -> None: + _seed() + response = client.post("/v1/approvals/nonce-1/deny") + assert response.status_code == 200 + assert response.json() == {"nonce": "nonce-1", "status": "denied"} + + +def test_second_decision_is_404(client: TestClient) -> None: + _seed() + assert client.post("/v1/approvals/nonce-1/approve").status_code == 200 + assert client.post("/v1/approvals/nonce-1/deny").status_code == 404 + + +def test_unknown_nonce_is_404(client: TestClient) -> None: + assert client.post("/v1/approvals/nope/approve").status_code == 404 + assert client.post("/v1/approvals/nope/deny").status_code == 404 + + +def test_non_loopback_client_gets_403() -> None: + set_approval_store_for_tests(InMemoryApprovalStore()) + application = FastAPI() + application.include_router(router) + client = TestClient(application) + assert client.get("/v1/approvals/pending").status_code == 403 + assert client.post("/v1/approvals/nonce-1/approve").status_code == 403 + assert client.post("/v1/approvals/nonce-1/deny").status_code == 403 + + +@pytest.mark.parametrize("host", ["127.0.0.1", "::1", "localhost"]) +def test_require_loopback_allows_loopback(host: str) -> None: + request = Request({"type": "http", "client": (host, 1234), "headers": []}) + assert require_loopback(request) is None + + +@pytest.mark.parametrize( + "host", ["10.0.0.1", "192.168.1.2", "example.com", "testclient", ""] +) +def test_require_loopback_rejects_remote(host: str) -> None: + scope = {"type": "http", "headers": []} + if host: + scope["client"] = (host, 1234) + else: + scope["client"] = None + with pytest.raises(HTTPException) as exc_info: + require_loopback(Request(scope)) + assert exc_info.value.status_code == 403 From 4e4e0c951619f618b33ac386a815f319ab2eb1e8 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:16:23 -0700 Subject: [PATCH 05/12] fix(gateway): persist approval gate state, seal tool/session/key, receipt unsupported clients (review 5637441231) Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/db/approval_gate_models.py | 57 ++++ gateway/app/routers/approvals.py | 4 +- gateway/app/services/approval_gate.py | 303 +++++++++++++++++- gateway/docs/schema-045-rollout.md | 27 ++ .../versions/045_approval_gate_approvals.py | 50 +++ gateway/tests/test_approval_gate.py | 225 ++++++++++++- gateway/tests/test_approvals_router.py | 154 +++++++-- 7 files changed, 764 insertions(+), 56 deletions(-) create mode 100644 gateway/app/db/approval_gate_models.py create mode 100644 gateway/docs/schema-045-rollout.md create mode 100644 gateway/migrations/versions/045_approval_gate_approvals.py diff --git a/gateway/app/db/approval_gate_models.py b/gateway/app/db/approval_gate_models.py new file mode 100644 index 000000000..057281d5c --- /dev/null +++ b/gateway/app/db/approval_gate_models.py @@ -0,0 +1,57 @@ +"""Durable rows for the AMW V2 human approval gate (SEP-2322). + +One row per paused irreversible MCP tool call. The sealed ``requestState`` the +client retries with is authenticated by HMAC, but the decision and the +single-use consumption must survive a gateway restart, so they live here +instead of only in memory. See ``app/services/approval_gate.py`` and +migration ``045_approval_gate_approvals``. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Optional + +from sqlalchemy import CheckConstraint +from sqlmodel import Field, SQLModel + +from app.core.time import utc_now +from app.db.types import NaiveUTCDateTime + +APPROVAL_GATE_STATUS_PENDING = "pending" +APPROVAL_GATE_STATUS_APPROVED = "approved" +APPROVAL_GATE_STATUS_DENIED = "denied" +APPROVAL_GATE_STATUS_EXPIRED = "expired" + + +class ApprovalGateModel(SQLModel, table=True): + """One paused tool call awaiting (or holding) a human decision. + + ``nonce`` is the primary key, so it is unique by definition: one row per + pause, and the atomic consume (``UPDATE ... WHERE status='approved' AND + consumed_at IS NULL``, rowcount checked) makes the approval single-use + even across a restart or concurrent retries. Raw arguments are never + stored, only their canonical hash. + """ + + __tablename__ = "approval_gate_approvals" + __table_args__ = ( + CheckConstraint( + "status IN ('pending', 'approved', 'denied', 'expired')", + name="ck_approval_gate_approvals_status", + ), + ) + + nonce: str = Field(primary_key=True, max_length=64) + idempotency_key: str = Field(max_length=128, index=True) + args_hash: str = Field(max_length=128) + principal: str = Field(max_length=255) + tool: str = Field(max_length=128) + session_id: str = Field(max_length=128) + status: str = Field(default="pending", max_length=16, index=True) + created_at: datetime = Field(sa_type=NaiveUTCDateTime, default_factory=utc_now) + deadline: datetime = Field(sa_type=NaiveUTCDateTime) + decided_at: Optional[datetime] = Field(sa_type=NaiveUTCDateTime, default=None) + consumed_at: Optional[datetime] = Field(sa_type=NaiveUTCDateTime, default=None) + + model_config = {"arbitrary_types_allowed": True} diff --git a/gateway/app/routers/approvals.py b/gateway/app/routers/approvals.py index 20204212c..c3391c717 100644 --- a/gateway/app/routers/approvals.py +++ b/gateway/app/routers/approvals.py @@ -13,7 +13,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import BaseModel -from app.services.approval_gate import ApprovalStore, InMemoryApprovalStore +from app.services.approval_gate import ApprovalStore, DbApprovalStore router = APIRouter(prefix="/v1/approvals", tags=["Approvals"]) @@ -27,7 +27,7 @@ def require_loopback(request: Request) -> None: raise HTTPException(status_code=403, detail="approvals are local-only") -_store: ApprovalStore = InMemoryApprovalStore() +_store: ApprovalStore = DbApprovalStore() def get_approval_store() -> ApprovalStore: diff --git a/gateway/app/services/approval_gate.py b/gateway/app/services/approval_gate.py index ac2869901..ffcb9706e 100644 --- a/gateway/app/services/approval_gate.py +++ b/gateway/app/services/approval_gate.py @@ -13,15 +13,19 @@ ``goose_amw.canonical.idempotency_key`` (verified caller + tool + canonical args hash + agent session id). The Goose request id is logged only. - ``requestState`` is HMAC-SHA256 sealed; missing secret fails closed. -- Clients without ``input_required`` support are rejected. -- Deny, timeout, and tampering each emit a receipt via an injectable sink and - never execute. +- Clients without ``input_required`` support are rejected, with a receipt. +- Deny, timeout, tampering, and every retry mismatch each emit a receipt via + an injectable sink and never execute. +- Pending approvals, decisions, and consumption live in the database + (``DbApprovalStore``), so a restart cannot replay an approval. """ from __future__ import annotations +import asyncio import base64 import binascii +import concurrent.futures import hashlib import hmac import json @@ -30,8 +34,18 @@ import secrets import threading import time +from collections.abc import Coroutine from dataclasses import dataclass, replace -from typing import Any, Callable, Literal +from datetime import datetime, timezone +from typing import Any, Callable, Literal, TypeVar, cast + +from sqlalchemy import select, update +from sqlalchemy.sql.elements import ColumnElement +from sqlmodel import col + +from app.core.time import to_naive_utc, utc_now +from app.db.approval_gate_models import ApprovalGateModel +from app.db.database import get_session_factory logger = logging.getLogger(__name__) @@ -48,6 +62,9 @@ "timeout", "tampered", "unsupported_client", + "tool_mismatch", + "session_mismatch", + "key_mismatch", "args_mismatch", "principal_mismatch", "replayed", @@ -66,7 +83,7 @@ class _StateTampered(ValueError): def _load_canonical() -> Any: """Import goose_amw.canonical lazily; fail closed when absent.""" try: - from goose_amw import canonical as canonical_module + from goose_amw import canonical as canonical_module # type: ignore[import-not-found] except ImportError as exc: raise ApprovalGateUnavailable( "goose_amw is not importable; approval gate refuses to run " @@ -225,6 +242,236 @@ def mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: return replace(record) +_T = TypeVar("_T") + + +def _run_sync(coro: Coroutine[Any, Any, _T]) -> _T: + """Drive one DB coroutine from the store's synchronous interface. + + The gate evaluates inline in a sync ``tools/call`` path, while the + gateway's persistence is async. With no running loop this is a plain + ``asyncio.run``; from inside a running loop (the async approvals router) + the coroutine runs on a helper thread with its own loop instead. + """ + try: + asyncio.get_running_loop() + except RuntimeError: + return asyncio.run(coro) + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: + return pool.submit(asyncio.run, coro).result() + + +def _to_db_time(value: float) -> datetime: + """Epoch seconds to the naive-UTC form used for persistence.""" + return to_naive_utc(datetime.fromtimestamp(value, tz=timezone.utc)) + + +def _from_db_time(value: datetime) -> float: + """Naive-UTC database timestamp back to epoch seconds.""" + return value.replace(tzinfo=timezone.utc).timestamp() + + +def _model_from_record(record: ApprovalRecord) -> ApprovalGateModel: + return ApprovalGateModel( + nonce=record.nonce, + idempotency_key=record.idempotency_key, + args_hash=record.args_hash, + principal=record.principal, + tool=record.tool, + session_id=record.session_id, + status=record.status, + created_at=_to_db_time(record.created_at), + deadline=_to_db_time(record.deadline), + decided_at=( + _to_db_time(record.decided_at) if record.decided_at is not None else None + ), + consumed_at=utc_now() if record.consumed else None, + ) + + +def _record_from_model(model: ApprovalGateModel) -> ApprovalRecord: + # The table check constraint admits only the four ApprovalStatus values. + status = cast(ApprovalStatus, model.status) + return ApprovalRecord( + nonce=model.nonce, + idempotency_key=model.idempotency_key, + args_hash=model.args_hash, + principal=model.principal, + tool=model.tool, + session_id=model.session_id, + status=status, + created_at=_from_db_time(model.created_at), + deadline=_from_db_time(model.deadline), + decided_at=( + _from_db_time(model.decided_at) if model.decided_at is not None else None + ), + consumed=model.consumed_at is not None, + ) + + +class DbApprovalStore(ApprovalStore): + """Durable store on the gateway database via the shared session factory. + + Decisions and consumption survive a restart: a consumed nonce stays + consumed because consume is a conditional ``UPDATE ... WHERE + status='approved' AND consumed_at IS NULL`` whose rowcount admits exactly + one winner, so neither a restart nor concurrent retries can replay it. + """ + + def save(self, record: ApprovalRecord) -> None: + _run_sync(self._save(record)) + + async def _save(self, record: ApprovalRecord) -> None: + factory = get_session_factory() + async with factory() as session: + await session.merge(_model_from_record(record)) + await session.commit() + + def get(self, nonce: str) -> ApprovalRecord | None: + return _run_sync(self._get(nonce)) + + async def _get(self, nonce: str) -> ApprovalRecord | None: + factory = get_session_factory() + async with factory() as session: + result = await session.execute( + select(ApprovalGateModel).where( + cast(ColumnElement[bool], ApprovalGateModel.nonce == nonce) + ) + ) + model = result.scalar_one_or_none() + return _record_from_model(model) if model is not None else None + + def list_pending(self) -> list[ApprovalRecord]: + return _run_sync(self._list_pending()) + + async def _list_pending(self) -> list[ApprovalRecord]: + factory = get_session_factory() + async with factory() as session: + result = await session.execute( + select(ApprovalGateModel) + .where( + cast( + ColumnElement[bool], + ApprovalGateModel.status == "pending", + ) + ) + .order_by( + col(ApprovalGateModel.created_at).asc(), + col(ApprovalGateModel.nonce).asc(), + ) + ) + return [_record_from_model(model) for model in result.scalars().all()] + + def decide( + self, nonce: str, approved: bool, *, now: float + ) -> ApprovalRecord | None: + return _run_sync(self._decide(nonce, approved, now=now)) + + async def _decide( + self, nonce: str, approved: bool, *, now: float + ) -> ApprovalRecord | None: + factory = get_session_factory() + async with factory() as session: + result = await session.execute( + select(ApprovalGateModel).where( + cast(ColumnElement[bool], ApprovalGateModel.nonce == nonce) + ) + ) + model = result.scalar_one_or_none() + if model is None or model.status != "pending": + return None + updated = await session.execute( + update(ApprovalGateModel) + .where( + cast(ColumnElement[bool], ApprovalGateModel.nonce == nonce), + cast( + ColumnElement[bool], + ApprovalGateModel.status == "pending", + ), + ) + .values( + status="approved" if approved else "denied", + decided_at=_to_db_time(now), + ) + ) + await session.commit() + if cast(Any, updated).rowcount != 1: + return None + await session.refresh(model) + return _record_from_model(model) + + def consume(self, nonce: str) -> ApprovalRecord | None: + return _run_sync(self._consume(nonce)) + + async def _consume(self, nonce: str) -> ApprovalRecord | None: + """Atomically spend an approved, unconsumed approval — single use. + + The ``WHERE status='approved' AND consumed_at IS NULL`` clause is the + single serialization point: exactly one caller (one retry, one + transport) wins, and a restart cannot resurrect a spent approval. + """ + factory = get_session_factory() + async with factory() as session: + updated = await session.execute( + update(ApprovalGateModel) + .where( + cast(ColumnElement[bool], ApprovalGateModel.nonce == nonce), + cast( + ColumnElement[bool], + ApprovalGateModel.status == "approved", + ), + cast( + ColumnElement[bool], + cast(Any, ApprovalGateModel.consumed_at).is_(None), + ), + ) + .values(consumed_at=utc_now()) + ) + await session.commit() + if cast(Any, updated).rowcount != 1: + return None + result = await session.execute( + select(ApprovalGateModel).where( + cast(ColumnElement[bool], ApprovalGateModel.nonce == nonce) + ) + ) + model = result.scalar_one_or_none() + return _record_from_model(model) if model is not None else None + + def mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: + return _run_sync(self._mark_expired(nonce, now=now)) + + async def _mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: + factory = get_session_factory() + async with factory() as session: + result = await session.execute( + select(ApprovalGateModel).where( + cast(ColumnElement[bool], ApprovalGateModel.nonce == nonce) + ) + ) + model = result.scalar_one_or_none() + if model is None: + return None + if model.status == "pending": + await session.execute( + update(ApprovalGateModel) + .where( + cast( + ColumnElement[bool], + ApprovalGateModel.nonce == nonce, + ), + cast( + ColumnElement[bool], + ApprovalGateModel.status == "pending", + ), + ) + .values(status="expired", decided_at=_to_db_time(now)) + ) + await session.commit() + await session.refresh(model) + return _record_from_model(model) + + ReceiptSink = Callable[[str, dict[str, Any]], None] @@ -261,7 +508,7 @@ def __init__( self._secret = raw_secret.encode("utf-8") if raw_secret else None ttl = ttl_seconds if ttl_seconds is not None else _ttl_from_env() self._ttl = _clamp_ttl(ttl) - self.store = store or InMemoryApprovalStore() + self.store = store or DbApprovalStore() self.clock = clock self.receipt_sink = receipt_sink or _log_receipt_sink @@ -324,6 +571,13 @@ def _pause_new_call( client_supports_input_required: bool, ) -> ApprovalDecision: if not client_supports_input_required: + self._emit( + "unsupported_client", + nonce=None, + tool=tool, + principal=caller, + session_id=session_id, + ) return ApprovalDecision(action="REJECT", reason="unsupported_client") secret = self._require_secret() now = self.clock() @@ -347,6 +601,9 @@ def _pause_new_call( "v": STATE_VERSION, "argsHash": args_hash, "principal": caller, + "tool": tool, + "sessionId": session_id, + "idempotencyKey": idempotency_key, "deadline": deadline, "nonce": nonce, }, @@ -383,6 +640,13 @@ def _evaluate_retry( request_state: str, ) -> ApprovalDecision: if not client_supports_input_required: + self._emit( + "unsupported_client", + nonce=None, + tool=tool, + principal=caller, + session_id=session_id, + ) return ApprovalDecision(action="REJECT", reason="unsupported_client") secret = self._require_secret() try: @@ -397,6 +661,25 @@ def _evaluate_retry( ) return ApprovalDecision(action="REJECT", reason="tampered") nonce = sealed.get("nonce") + if not isinstance(nonce, str) or not nonce: + self._emit( + "tampered", + nonce=None, + tool=tool, + principal=caller, + session_id=session_id, + ) + return ApprovalDecision(action="REJECT", reason="tampered") + if sealed.get("tool") != tool: + self._emit("tool_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="tool_mismatch", nonce=nonce + ) + if sealed.get("sessionId") != session_id: + self._emit("session_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="session_mismatch", nonce=nonce + ) if sealed.get("principal") != caller: self._emit("principal_mismatch", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision( @@ -407,7 +690,13 @@ def _evaluate_retry( return ApprovalDecision( action="REJECT", reason="args_mismatch", nonce=nonce ) - record = self.store.get(nonce) if isinstance(nonce, str) else None + # Last: the key is derived from caller, tool, args, and session, so a + # mismatch here with all inputs matching means the key derivation + # itself drifted between pause and retry. + if sealed.get("idempotencyKey") != idempotency_key: + self._emit("key_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="key_mismatch", nonce=nonce) + record = self.store.get(nonce) if record is None: self._emit("tampered", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision(action="REJECT", reason="tampered", nonce=nonce) diff --git a/gateway/docs/schema-045-rollout.md b/gateway/docs/schema-045-rollout.md new file mode 100644 index 000000000..26dbfe51a --- /dev/null +++ b/gateway/docs/schema-045-rollout.md @@ -0,0 +1,27 @@ +# Schema 045: approval-gate rows and rollback boundary + +Migration `045_approval_gate_approvals` revises `044_receipt_resolutions`. It adds the +`approval_gate_approvals` table for the AMW V2 human approval gate (SEP-2322) without +changing existing tables. The gate is not mounted yet, so no serving path writes this +table; the rows become load-bearing only when the `mcp_standard.py` hook lands. + +## Compatibility release before migration + +This is a release plan, not evidence of a deployment. Before applying 045, confirm the +database is at `044_receipt_resolutions` and qualify an immutable 045-capable +compatibility image as the recovery target. Rehearse the upgrade and recovery on +disposable PostgreSQL, including existing approval-adjacent reads. Keep new approval +writes stopped until the migration has completed, schema parity is verified, and every +serving worker is 045-capable. Record the exact image, database revision, and +verification results before enabling writes. An image packaged with head 044 cannot +restart against a database upgraded to 045. + +## Rollback after activation + +Stop new approval writes and recover with the qualified 045-capable image, leaving the +database at 045. Pending rows are operational pause state, not signed evidence: denial, +timeout, tamper, and replay receipts are emitted through the gate's receipt sink, so +abandoning paused rows on recovery only forces those clients to start a new paused call. +The `downgrade()` drops the new table and its indexes; run it only after confirming no +serving worker still writes approvals, and never as a substitute for the qualified +recovery image above. diff --git a/gateway/migrations/versions/045_approval_gate_approvals.py b/gateway/migrations/versions/045_approval_gate_approvals.py new file mode 100644 index 000000000..95db4c4f9 --- /dev/null +++ b/gateway/migrations/versions/045_approval_gate_approvals.py @@ -0,0 +1,50 @@ +"""Add durable rows for the AMW V2 human approval gate. + +Revision ID: 045_approval_gate_approvals +Revises: 044_receipt_resolutions +""" + +from alembic import op +import sqlalchemy as sa + +revision: str = "045_approval_gate_approvals" +down_revision: str = "044_receipt_resolutions" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "approval_gate_approvals", + sa.Column("nonce", sa.String(length=64), primary_key=True), + sa.Column("idempotency_key", sa.String(length=128), nullable=False), + sa.Column("args_hash", sa.String(length=128), nullable=False), + sa.Column("principal", sa.String(length=255), nullable=False), + sa.Column("tool", sa.String(length=128), nullable=False), + sa.Column("session_id", sa.String(length=128), nullable=False), + sa.Column("status", sa.String(length=16), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("deadline", sa.DateTime(), nullable=False), + sa.Column("decided_at", sa.DateTime(), nullable=True), + sa.Column("consumed_at", sa.DateTime(), nullable=True), + sa.CheckConstraint( + "status IN ('pending', 'approved', 'denied', 'expired')", + name="ck_approval_gate_approvals_status", + ), + ) + for column in ("idempotency_key", "status"): + op.create_index( + f"ix_approval_gate_approvals_{column}", + "approval_gate_approvals", + [column], + unique=False, + ) + + +def downgrade() -> None: + for column in ("idempotency_key", "status"): + op.drop_index( + f"ix_approval_gate_approvals_{column}", + table_name="approval_gate_approvals", + ) + op.drop_table("approval_gate_approvals") diff --git a/gateway/tests/test_approval_gate.py b/gateway/tests/test_approval_gate.py index 41835c1c9..85176f9c2 100644 --- a/gateway/tests/test_approval_gate.py +++ b/gateway/tests/test_approval_gate.py @@ -1,6 +1,14 @@ -"""Data-free tests for the AMW V2 approval gate state machine.""" +"""Tests for the AMW V2 approval gate state machine. +Every value comes from the real G1 gate recording +(integrations/goose-agent-middleware/tests/fixtures/g1_gate_calls.jsonl) or is +made at runtime (secrets.token_hex / uuid.uuid4). Nothing here is hand-invented. +""" + +import json +import secrets import sys +import uuid from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[2] @@ -15,18 +23,40 @@ import pytest # noqa: E402 from goose_amw import canonical as goose_canonical # noqa: E402 +from sqlalchemy import delete # noqa: E402 +import app.services.approval_gate as gate_module # noqa: E402 +from app.db.approval_gate_models import ApprovalGateModel # noqa: E402 +from app.db.database import get_session_factory # noqa: E402 from app.services.approval_gate import ( # noqa: E402 ApprovalGate, ApprovalGateUnavailable, + DbApprovalStore, InMemoryApprovalStore, ) -SECRET = "test-state-secret" -CALLER = "caller-a" -TOOL = "tool-x" -SESSION = "session-1" -ARGS: dict[str, Any] = {} +FIXTURE = ( + REPO_ROOT + / "integrations" + / "goose-agent-middleware" + / "tests" + / "fixtures" + / "g1_gate_calls.jsonl" +) +RECORDS = [json.loads(line) for line in FIXTURE.read_text().splitlines()] +WRITES = [record for record in RECORDS if record["tool"] == "write_file"] +W = WRITES[0] +TOOL = W["tool"] +SESSION = W["meta"]["agent-session-id"] +ARGS = {"path": W["path"]} # the only argument field the recording holds +REQUEST_IDS = [w["meta"]["agent-tool-call-request-id"] for w in WRITES] + +SECRET = secrets.token_hex(32) +CALLER = str(uuid.uuid4()) + + +def _fresh_id() -> str: + return str(uuid.uuid4()) class _Clock: @@ -57,6 +87,30 @@ def gate(receipts: list[tuple[str, dict[str, Any]]], clock: _Clock) -> ApprovalG ) +@pytest.fixture +def db_gate(receipts: list[tuple[str, dict[str, Any]]], clock: _Clock) -> ApprovalGate: + return ApprovalGate( + secret=SECRET, + store=DbApprovalStore(), + clock=clock, + receipt_sink=lambda event, record: receipts.append((event, record)), + ) + + +async def _purge_approval_gate_table() -> None: + factory = get_session_factory() + async with factory() as session: + await session.execute(delete(ApprovalGateModel)) + await session.commit() + + +@pytest.fixture +async def purge_approval_gate_table() -> Any: + await _purge_approval_gate_table() + yield + await _purge_approval_gate_table() + + def _pause(gate: ApprovalGate) -> Any: decision = gate.evaluate(CALLER, TOOL, ARGS, SESSION, True) assert decision.action == "PAUSE" @@ -72,7 +126,7 @@ def _retry(gate: ApprovalGate, state: str, **kwargs: Any) -> Any: "session_id": SESSION, "client_supports_input_required": True, "request_state": state, - "input_responses": [{"requestId": "r1", "approved": True}], + "input_responses": [{"requestId": _fresh_id(), "approved": True}], } params.update(kwargs) return gate.evaluate( @@ -182,25 +236,95 @@ def test_unknown_nonce_rejects_tampered( assert rejected.reason == "tampered" -def test_unsupported_client_rejects_without_record(gate: ApprovalGate) -> None: +def test_unsupported_client_rejects_without_record( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: decision = gate.evaluate(CALLER, TOOL, ARGS, SESSION, False) assert decision.action == "REJECT" assert decision.reason == "unsupported_client" assert gate.store.list_pending() == [] + assert [event for event, _ in receipts] == ["unsupported_client"] + assert receipts[0][1]["tool"] == TOOL + assert receipts[0][1]["principal"] == CALLER -def test_args_mismatch_rejects(gate: ApprovalGate) -> None: +def test_unsupported_client_retry_rejects_with_receipt( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: + decision = _pause(gate) + rejected = _retry( + gate, decision.payload["requestState"], client_supports_input_required=False + ) + assert rejected.action == "REJECT" + assert rejected.reason == "unsupported_client" + assert [event for event, _ in receipts] == ["unsupported_client"] + + +def test_args_mismatch_rejects( + gate: ApprovalGate, + receipts: list[tuple[str, dict[str, Any]]], + tmp_path: Path, +) -> None: decision = _pause(gate) - rejected = _retry(gate, decision.payload["requestState"], arguments={"k": "v"}) + rejected = _retry( + gate, decision.payload["requestState"], arguments={"path": str(tmp_path)} + ) assert rejected.action == "REJECT" assert rejected.reason == "args_mismatch" + assert [event for event, _ in receipts] == ["args_mismatch"] -def test_principal_mismatch_rejects(gate: ApprovalGate) -> None: +def test_principal_mismatch_rejects( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: decision = _pause(gate) - rejected = _retry(gate, decision.payload["requestState"], caller="caller-b") + rejected = _retry(gate, decision.payload["requestState"], caller=_fresh_id()) assert rejected.action == "REJECT" assert rejected.reason == "principal_mismatch" + assert [event for event, _ in receipts] == ["principal_mismatch"] + + +def test_tool_mismatch_rejects( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: + decision = _pause(gate) + rejected = _retry(gate, decision.payload["requestState"], tool=_fresh_id()) + assert rejected.action == "REJECT" + assert rejected.reason == "tool_mismatch" + assert [event for event, _ in receipts] == ["tool_mismatch"] + + +def test_session_mismatch_rejects( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: + decision = _pause(gate) + rejected = _retry(gate, decision.payload["requestState"], session_id=_fresh_id()) + assert rejected.action == "REJECT" + assert rejected.reason == "session_mismatch" + assert [event for event, _ in receipts] == ["session_mismatch"] + + +def test_key_mismatch_rejects( + gate: ApprovalGate, + receipts: list[tuple[str, dict[str, Any]]], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A drifted key derivation cannot ride the sealed approval.""" + decision = _pause(gate) + real = goose_canonical + + class _DriftedCanonical: + args_hash = staticmethod(real.args_hash) + + @staticmethod + def idempotency_key(**kwargs: Any) -> str: + return secrets.token_hex(32) + + monkeypatch.setattr(gate_module, "_load_canonical", lambda: _DriftedCanonical) + rejected = _retry(gate, decision.payload["requestState"]) + assert rejected.action == "REJECT" + assert rejected.reason == "key_mismatch" + assert [event for event, _ in receipts] == ["key_mismatch"] def test_missing_secret_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None: @@ -211,10 +335,83 @@ def test_missing_secret_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None: def test_request_id_is_logged_not_keyed(gate: ApprovalGate) -> None: - first = gate.evaluate(CALLER, TOOL, ARGS, SESSION, True, request_id="req-1") - second = gate.evaluate(CALLER, TOOL, ARGS, SESSION, True, request_id="req-2") + assert len(REQUEST_IDS) >= 2 + first = gate.evaluate(CALLER, TOOL, ARGS, SESSION, True, request_id=REQUEST_IDS[0]) + second = gate.evaluate(CALLER, TOOL, ARGS, SESSION, True, request_id=REQUEST_IDS[1]) assert first.action == "PAUSE" assert second.action == "PAUSE" assert gate.store.list_pending() keys = {record.idempotency_key for record in gate.store.list_pending()} assert len(keys) == 1 + + +def test_default_store_is_db_backed() -> None: + assert isinstance(ApprovalGate(secret=SECRET).store, DbApprovalStore) + + +async def test_db_consumed_nonce_stays_consumed_across_restart( + db_gate: ApprovalGate, + clock: _Clock, + receipts: list[tuple[str, dict[str, Any]]], + clean_database: Any, + purge_approval_gate_table: Any, +) -> None: + decision = _pause(db_gate) + assert decision.nonce is not None + state: str = decision.payload["requestState"] + + # Simulated restart: a new store instance sees the same pending row. + restarted = DbApprovalStore() + record = restarted.get(decision.nonce) + assert record is not None + assert record.status == "pending" + assert record.tool == TOOL + assert record.session_id == SESSION + assert record.principal == CALLER + assert record.args_hash == goose_canonical.args_hash(ARGS) + assert record.idempotency_key == goose_canonical.idempotency_key( + caller=CALLER, tool=TOOL, arguments=ARGS, session_id=SESSION + ) + assert record.deadline == clock.now + 300 + assert [pending.nonce for pending in restarted.list_pending()] == [decision.nonce] + + restarted.decide(decision.nonce, True, now=clock()) + executed = _retry(db_gate, state) + assert executed.action == "EXECUTE" + + # Second restart: the nonce stays consumed; the retry cannot replay. + restarted_again = DbApprovalStore() + consumed = restarted_again.get(decision.nonce) + assert consumed is not None + assert consumed.consumed is True + assert restarted_again.consume(decision.nonce) is None + replayed = _retry(db_gate, state) + assert replayed.action == "REJECT" + assert replayed.reason == "replayed" + assert [event for event, _ in receipts] == ["replayed"] + + +async def test_db_denied_decision_visible_across_instances( + db_gate: ApprovalGate, + clock: _Clock, + receipts: list[tuple[str, dict[str, Any]]], + clean_database: Any, + purge_approval_gate_table: Any, +) -> None: + decision = _pause(db_gate) + assert decision.nonce is not None + decider = DbApprovalStore() + denied = decider.decide(decision.nonce, False, now=clock()) + assert denied is not None + assert denied.status == "denied" + + observer = DbApprovalStore() + assert observer.get(decision.nonce) is not None + assert observer.get(decision.nonce).status == "denied" # type: ignore[union-attr] + assert observer.list_pending() == [] + assert observer.decide(decision.nonce, True, now=clock()) is None + + rejected = _retry(db_gate, decision.payload["requestState"]) + assert rejected.action == "REJECT" + assert rejected.reason == "denied" + assert [event for event, _ in receipts] == ["denied"] diff --git a/gateway/tests/test_approvals_router.py b/gateway/tests/test_approvals_router.py index 4aea54fb7..f78588910 100644 --- a/gateway/tests/test_approvals_router.py +++ b/gateway/tests/test_approvals_router.py @@ -1,18 +1,65 @@ -"""Data-free tests for the local-only approvals router.""" +"""Tests for the local-only approvals router. -import time - -import pytest -from fastapi import FastAPI, HTTPException, Request -from starlette.testclient import TestClient +Every value comes from the real G1 gate recording +(integrations/goose-agent-middleware/tests/fixtures/g1_gate_calls.jsonl) or is +made at runtime (secrets.token_hex / uuid.uuid4). Nothing here is hand-invented. +""" -from app.routers.approvals import ( +import json +import secrets +import sys +import time +import uuid +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +for _path in ( + REPO_ROOT / "integrations" / "goose-agent-middleware" / "src", + REPO_ROOT / "sdk" / "python" / "src", +): + if str(_path) not in sys.path: + sys.path.insert(0, str(_path)) + +from typing import Any # noqa: E402 + +import pytest # noqa: E402 +from fastapi import FastAPI, HTTPException, Request # noqa: E402 +from goose_amw import canonical as goose_canonical # noqa: E402 +from sqlalchemy import delete # noqa: E402 +from starlette.testclient import TestClient # noqa: E402 + +import app.routers.approvals as approvals_module # noqa: E402 +from app.db.approval_gate_models import ApprovalGateModel # noqa: E402 +from app.db.database import get_session_factory # noqa: E402 +from app.routers.approvals import ( # noqa: E402 get_approval_store, require_loopback, router, set_approval_store_for_tests, ) -from app.services.approval_gate import ApprovalRecord, InMemoryApprovalStore +from app.services.approval_gate import ( # noqa: E402 + ApprovalRecord, + DbApprovalStore, + InMemoryApprovalStore, +) + +FIXTURE = ( + REPO_ROOT + / "integrations" + / "goose-agent-middleware" + / "tests" + / "fixtures" + / "g1_gate_calls.jsonl" +) +RECORDS = [json.loads(line) for line in FIXTURE.read_text().splitlines()] +W = next(record for record in RECORDS if record["tool"] == "write_file") +TOOL = W["tool"] +SESSION = W["meta"]["agent-session-id"] +ARGS = {"path": W["path"]} # the only argument field the recording holds + + +def _fresh_id() -> str: + return str(uuid.uuid4()) @pytest.fixture @@ -29,54 +76,70 @@ def client(app: FastAPI) -> TestClient: return TestClient(app) -def _seed(nonce: str = "nonce-1") -> ApprovalRecord: +@pytest.fixture +async def purge_approval_gate_table() -> Any: + factory = get_session_factory() + async with factory() as session: + await session.execute(delete(ApprovalGateModel)) + await session.commit() + yield + async with factory() as session: + await session.execute(delete(ApprovalGateModel)) + await session.commit() + + +def _seed() -> ApprovalRecord: + now = time.time() record = ApprovalRecord( - nonce=nonce, - idempotency_key="key-1", - args_hash="sha256:abc", - principal="caller-a", - tool="tool-x", - session_id="session-1", - created_at=time.time(), - deadline=time.time() + 300, + nonce=secrets.token_urlsafe(16), + idempotency_key=f"amw-fb-{secrets.token_hex(32)}", + args_hash=goose_canonical.args_hash(ARGS), + principal=_fresh_id(), + tool=TOOL, + session_id=SESSION, + created_at=now, + deadline=now + 300, ) get_approval_store().save(record) return record def test_pending_lists_seeded_record(client: TestClient) -> None: - _seed() + record = _seed() response = client.get("/v1/approvals/pending") assert response.status_code == 200 approvals = response.json()["approvals"] - assert [item["nonce"] for item in approvals] == ["nonce-1"] - assert approvals[0]["tool"] == "tool-x" + assert [item["nonce"] for item in approvals] == [record.nonce] + assert approvals[0]["tool"] == TOOL + assert approvals[0]["principal"] == record.principal + assert approvals[0]["args_hash"] == goose_canonical.args_hash(ARGS) def test_approve_flips_pending_to_approved(client: TestClient) -> None: - _seed() - response = client.post("/v1/approvals/nonce-1/approve") + record = _seed() + response = client.post(f"/v1/approvals/{record.nonce}/approve") assert response.status_code == 200 - assert response.json() == {"nonce": "nonce-1", "status": "approved"} + assert response.json() == {"nonce": record.nonce, "status": "approved"} assert client.get("/v1/approvals/pending").json() == {"approvals": []} def test_deny_flips_pending_to_denied(client: TestClient) -> None: - _seed() - response = client.post("/v1/approvals/nonce-1/deny") + record = _seed() + response = client.post(f"/v1/approvals/{record.nonce}/deny") assert response.status_code == 200 - assert response.json() == {"nonce": "nonce-1", "status": "denied"} + assert response.json() == {"nonce": record.nonce, "status": "denied"} def test_second_decision_is_404(client: TestClient) -> None: - _seed() - assert client.post("/v1/approvals/nonce-1/approve").status_code == 200 - assert client.post("/v1/approvals/nonce-1/deny").status_code == 404 + record = _seed() + assert client.post(f"/v1/approvals/{record.nonce}/approve").status_code == 200 + assert client.post(f"/v1/approvals/{record.nonce}/deny").status_code == 404 def test_unknown_nonce_is_404(client: TestClient) -> None: - assert client.post("/v1/approvals/nope/approve").status_code == 404 - assert client.post("/v1/approvals/nope/deny").status_code == 404 + unknown = _fresh_id() + assert client.post(f"/v1/approvals/{unknown}/approve").status_code == 404 + assert client.post(f"/v1/approvals/{unknown}/deny").status_code == 404 def test_non_loopback_client_gets_403() -> None: @@ -84,9 +147,34 @@ def test_non_loopback_client_gets_403() -> None: application = FastAPI() application.include_router(router) client = TestClient(application) + unknown = _fresh_id() assert client.get("/v1/approvals/pending").status_code == 403 - assert client.post("/v1/approvals/nonce-1/approve").status_code == 403 - assert client.post("/v1/approvals/nonce-1/deny").status_code == 403 + assert client.post(f"/v1/approvals/{unknown}/approve").status_code == 403 + assert client.post(f"/v1/approvals/{unknown}/deny").status_code == 403 + + +def test_default_store_is_db_backed() -> None: + import importlib + + try: + importlib.reload(approvals_module) + assert isinstance(approvals_module.get_approval_store(), DbApprovalStore) + finally: + approvals_module.set_approval_store_for_tests(InMemoryApprovalStore()) + + +async def test_approve_through_http_decides_db_row( + client: TestClient, clean_database: None, purge_approval_gate_table: None +) -> None: + set_approval_store_for_tests(DbApprovalStore()) + record = _seed() + response = client.post(f"/v1/approvals/{record.nonce}/approve") + assert response.status_code == 200 + assert response.json() == {"nonce": record.nonce, "status": "approved"} + assert client.get("/v1/approvals/pending").json() == {"approvals": []} + stored = DbApprovalStore().get(record.nonce) + assert stored is not None + assert stored.status == "approved" @pytest.mark.parametrize("host", ["127.0.0.1", "::1", "localhost"]) From 48e9263e8e16a75f4ec09115246631945926cf08 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:19:11 -0700 Subject: [PATCH 06/12] fix(tests): clean approval_gate_approvals between tests Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/tests/conftest.py | 1 + 1 file changed, 1 insertion(+) diff --git a/gateway/tests/conftest.py b/gateway/tests/conftest.py index ef855168e..8c7bc5e76 100644 --- a/gateway/tests/conftest.py +++ b/gateway/tests/conftest.py @@ -423,6 +423,7 @@ async def setup_database(): #: tests/test_clean_database_coverage.py's exemption set fails that test, so a #: new trust-plane table cannot silently escape per-test cleanup. CLEAN_DATABASE_TABLES = ( + "approval_gate_approvals", "receipt_resolutions", "resolution_chain_heads", "receipts", From cc0da45f15550f9596bd1a30a8fe8cc9e301ee8e Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:23:21 -0700 Subject: [PATCH 07/12] fix(gateway): check stored approval binding on retry; runtime-generated test hosts and recorded clock (review 5637503614) Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/services/approval_gate.py | 13 +++++++ gateway/tests/test_approval_gate.py | 51 +++++++++++++++++++++++++- gateway/tests/test_approvals_router.py | 35 ++++++++++++++++-- 3 files changed, 94 insertions(+), 5 deletions(-) diff --git a/gateway/app/services/approval_gate.py b/gateway/app/services/approval_gate.py index ffcb9706e..49e084aeb 100644 --- a/gateway/app/services/approval_gate.py +++ b/gateway/app/services/approval_gate.py @@ -700,6 +700,19 @@ def _evaluate_retry( if record is None: self._emit("tampered", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision(action="REJECT", reason="tampered", nonce=nonce) + if record.tool != tool: + self._emit("tool_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="tool_mismatch", nonce=nonce + ) + if record.session_id != session_id: + self._emit("session_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="session_mismatch", nonce=nonce + ) + if record.idempotency_key != idempotency_key: + self._emit("key_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="key_mismatch", nonce=nonce) now = self.clock() sealed_deadline = sealed.get("deadline") if ( diff --git a/gateway/tests/test_approval_gate.py b/gateway/tests/test_approval_gate.py index 85176f9c2..692391946 100644 --- a/gateway/tests/test_approval_gate.py +++ b/gateway/tests/test_approval_gate.py @@ -9,6 +9,8 @@ import secrets import sys import uuid +from dataclasses import replace +from datetime import datetime from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[2] @@ -59,8 +61,20 @@ def _fresh_id() -> str: return str(uuid.uuid4()) +def _fixture_epoch(value: Any) -> float: + if isinstance(value, (int, float)): + return float(value) + text = str(value) + if text.endswith("Z"): + text = text[:-1] + "+00:00" + return datetime.fromisoformat(text).timestamp() + + +FIXTURE_EPOCH = _fixture_epoch(W["ts"]) + + class _Clock: - def __init__(self, now: float = 1_000_000.0) -> None: + def __init__(self, now: float = FIXTURE_EPOCH) -> None: self.now = now def __call__(self) -> float: @@ -327,6 +341,41 @@ def idempotency_key(**kwargs: Any) -> str: assert [event for event, _ in receipts] == ["key_mismatch"] +@pytest.mark.parametrize( + ("field", "reason"), + [ + ("tool", "tool_mismatch"), + ("session_id", "session_mismatch"), + ("idempotency_key", "key_mismatch"), + ], +) +def test_stored_record_mismatch_rejects( + gate: ApprovalGate, + receipts: list[tuple[str, dict[str, Any]]], + field: str, + reason: str, +) -> None: + """A stored record that drifts from the sealed state cannot execute.""" + decision = _pause(gate) + assert decision.nonce is not None + assert decision.payload is not None + record = gate.store.get(decision.nonce) + assert record is not None + if field == "idempotency_key": + tampered = f"amw-fb-{secrets.token_hex(32)}" + while tampered == record.idempotency_key: + tampered = f"amw-fb-{secrets.token_hex(32)}" + else: + tampered = _fresh_id() + while tampered == getattr(record, field): + tampered = _fresh_id() + gate.store.save(replace(record, **{field: tampered})) + rejected = _retry(gate, decision.payload["requestState"]) + assert rejected.action == "REJECT" + assert rejected.reason == reason + assert [event for event, _ in receipts] == [reason] + + def test_missing_secret_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv("AMW_APPROVAL_STATE_SECRET", raising=False) gate = ApprovalGate(store=InMemoryApprovalStore()) diff --git a/gateway/tests/test_approvals_router.py b/gateway/tests/test_approvals_router.py index f78588910..f66c0d54c 100644 --- a/gateway/tests/test_approvals_router.py +++ b/gateway/tests/test_approvals_router.py @@ -62,6 +62,25 @@ def _fresh_id() -> str: return str(uuid.uuid4()) +def _random_port() -> int: + return 1024 + secrets.randbelow(65535 - 1024 + 1) + + +def _random_10_host() -> str: + return ( + f"10.{secrets.randbelow(256)}.{secrets.randbelow(256)}" + f".{1 + secrets.randbelow(254)}" + ) + + +def _random_192_168_host() -> str: + return f"192.168.{secrets.randbelow(256)}.{1 + secrets.randbelow(254)}" + + +def _random_invalid_host() -> str: + return f"{uuid.uuid4().hex}.invalid" + + @pytest.fixture def app() -> FastAPI: set_approval_store_for_tests(InMemoryApprovalStore()) @@ -177,19 +196,27 @@ async def test_approve_through_http_decides_db_row( assert stored.status == "approved" +# Protocol constants (loopback): the only client identities allowed through. @pytest.mark.parametrize("host", ["127.0.0.1", "::1", "localhost"]) def test_require_loopback_allows_loopback(host: str) -> None: - request = Request({"type": "http", "client": (host, 1234), "headers": []}) + request = Request({"type": "http", "client": (host, _random_port()), "headers": []}) assert require_loopback(request) is None @pytest.mark.parametrize( - "host", ["10.0.0.1", "192.168.1.2", "example.com", "testclient", ""] + "host", + [ + _random_10_host(), + _random_192_168_host(), + _random_invalid_host(), + "testclient", + "", + ], ) def test_require_loopback_rejects_remote(host: str) -> None: - scope = {"type": "http", "headers": []} + scope: dict[str, Any] = {"type": "http", "headers": []} if host: - scope["client"] = (host, 1234) + scope["client"] = (host, _random_port()) else: scope["client"] = None with pytest.raises(HTTPException) as exc_info: From ae49ba4225f5ea0ee0de4ef7385673e3a718d8cd Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:35:58 -0700 Subject: [PATCH 08/12] fix(tests): stable xdist ids, register approval gate table, plain doc field names Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/services/approval_gate.py | 2 +- gateway/tests/conftest.py | 1 + gateway/tests/test_approvals_router.py | 26 ++++++++++++++++++++------ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/gateway/app/services/approval_gate.py b/gateway/app/services/approval_gate.py index 49e084aeb..ef28b1bdd 100644 --- a/gateway/app/services/approval_gate.py +++ b/gateway/app/services/approval_gate.py @@ -2,7 +2,7 @@ SEP-2322 flow: the first ``tools/call`` for an irreversible tool PAUSEs with a ``resultType='input_required'`` result carrying an opaque ``requestState``. The -client retries the same ``tools/call`` with ``inputResponses`` plus the +client retries the same ``tools/call`` with "inputResponses" plus the ``requestState``; this gate EXECUTEs only after a local human approved, else it REJECTs. The hook in ``mcp_standard.py`` that calls :meth:`ApprovalGate.evaluate` lands in a later PR. diff --git a/gateway/tests/conftest.py b/gateway/tests/conftest.py index 8c7bc5e76..fc921a447 100644 --- a/gateway/tests/conftest.py +++ b/gateway/tests/conftest.py @@ -386,6 +386,7 @@ def mount_dormant_surfaces_for_marked_tests(request): async def setup_database(): """Set up database tables before any tests run.""" require_disposable_test_database() + import app.db.approval_gate_models # noqa: F401 -- registers table on SQLModel.metadata from app.core.durable_state import close_durable_state from app.db.database import init_db, close_db diff --git a/gateway/tests/test_approvals_router.py b/gateway/tests/test_approvals_router.py index f66c0d54c..ca5f16fa2 100644 --- a/gateway/tests/test_approvals_router.py +++ b/gateway/tests/test_approvals_router.py @@ -204,16 +204,30 @@ def test_require_loopback_allows_loopback(host: str) -> None: @pytest.mark.parametrize( - "host", + "case", [ - _random_10_host(), - _random_192_168_host(), - _random_invalid_host(), + "rfc1918-10", + "rfc1918-192-168", + "uuid-invalid-host", "testclient", - "", + "missing", ], ) -def test_require_loopback_rejects_remote(host: str) -> None: +def test_require_loopback_rejects_remote(case: str) -> None: + # Hosts stay runtime-generated, but collection must be deterministic: + # xdist workers collect independently, so a random value baked into the + # parametrize list yields different test ids per worker. Parametrize over + # stable labels and generate the random host inside the test body. + if case == "rfc1918-10": + host = _random_10_host() + elif case == "rfc1918-192-168": + host = _random_192_168_host() + elif case == "uuid-invalid-host": + host = _random_invalid_host() + elif case == "testclient": + host = "testclient" + else: + host = "" scope: dict[str, Any] = {"type": "http", "headers": []} if host: scope["client"] = (host, _random_port()) From b57a203fb6e4a37344f40b09868af81fc6578b26 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:54:45 -0700 Subject: [PATCH 09/12] fix(gateway): address approval gate review findings SEP-2322 inputRequests map, loop-safe async store, deadline guard on consume, admin auth on approvals router. Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/routers/approvals.py | 18 +- gateway/app/services/approval_gate.py | 558 ++++++++++++++++++++----- gateway/tests/test_approval_gate.py | 224 ++++++++-- gateway/tests/test_approvals_router.py | 49 ++- 4 files changed, 695 insertions(+), 154 deletions(-) diff --git a/gateway/app/routers/approvals.py b/gateway/app/routers/approvals.py index c3391c717..a9c1265ac 100644 --- a/gateway/app/routers/approvals.py +++ b/gateway/app/routers/approvals.py @@ -2,8 +2,9 @@ A human on the gateway host approves or denies paused irreversible tool calls here (or via ``gateway/scripts/amw_approvals.py``). Every endpoint rejects -non-loopback clients with 403. This router is intentionally not mounted in -``main.py`` yet; mounting lands with the ``mcp_standard.py`` hook in a later PR. +non-loopback clients with 403 and requires a bootstrap admin (operator) API +key. This router is intentionally not mounted in ``main.py`` yet; mounting +lands with the ``mcp_standard.py`` hook in a later PR. """ from __future__ import annotations @@ -13,6 +14,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import BaseModel +from app.core.auth import AuthContext, get_auth_context from app.services.approval_gate import ApprovalStore, DbApprovalStore router = APIRouter(prefix="/v1/approvals", tags=["Approvals"]) @@ -60,7 +62,9 @@ class DecisionResponse(BaseModel): @router.get("/pending", response_model=PendingApprovalsResponse) async def list_pending( _local: None = Depends(require_loopback), + auth: AuthContext = Depends(get_auth_context), ) -> PendingApprovalsResponse: + auth.require_bootstrap_admin() approvals = [ PendingApproval( nonce=record.nonce, @@ -70,7 +74,7 @@ async def list_pending( created_at=record.created_at, deadline=record.deadline, ) - for record in get_approval_store().list_pending() + for record in await get_approval_store().alist_pending() ] return PendingApprovalsResponse(approvals=approvals) @@ -79,8 +83,10 @@ async def list_pending( async def approve( nonce: str, _local: None = Depends(require_loopback), + auth: AuthContext = Depends(get_auth_context), ) -> DecisionResponse: - record = get_approval_store().decide(nonce, True, now=time.time()) + auth.require_bootstrap_admin() + record = await get_approval_store().adecide(nonce, True, now=time.time()) if record is None: raise HTTPException(status_code=404, detail="approval_not_found") return DecisionResponse(nonce=record.nonce, status=record.status) @@ -90,8 +96,10 @@ async def approve( async def deny( nonce: str, _local: None = Depends(require_loopback), + auth: AuthContext = Depends(get_auth_context), ) -> DecisionResponse: - record = get_approval_store().decide(nonce, False, now=time.time()) + auth.require_bootstrap_admin() + record = await get_approval_store().adecide(nonce, False, now=time.time()) if record is None: raise HTTPException(status_code=404, detail="approval_not_found") return DecisionResponse(nonce=record.nonce, status=record.status) diff --git a/gateway/app/services/approval_gate.py b/gateway/app/services/approval_gate.py index ef28b1bdd..4b228ccb9 100644 --- a/gateway/app/services/approval_gate.py +++ b/gateway/app/services/approval_gate.py @@ -1,11 +1,13 @@ """Human approval gate for irreversible MCP tool calls (AMW V2). SEP-2322 flow: the first ``tools/call`` for an irreversible tool PAUSEs with a -``resultType='input_required'`` result carrying an opaque ``requestState``. The -client retries the same ``tools/call`` with "inputResponses" plus the -``requestState``; this gate EXECUTEs only after a local human approved, else it -REJECTs. The hook in ``mcp_standard.py`` that calls :meth:`ApprovalGate.evaluate` -lands in a later PR. +``resultType='input_required'`` result carrying an ``inputRequests`` map (keyed +by request id, each value an ``elicitation/create`` client request) plus an +opaque ``requestState``. The client retries the same ``tools/call`` with an +"inputResponses" map keyed by the same id plus the ``requestState``; this gate +EXECUTEs only after a local human approved, else it REJECTs. The hook in +``mcp_standard.py`` that calls :meth:`ApprovalGate.evaluate` lands in a later +PR. Fail-closed rules: @@ -25,7 +27,6 @@ import asyncio import base64 import binascii -import concurrent.futures import hashlib import hmac import json @@ -67,6 +68,7 @@ "key_mismatch", "args_mismatch", "principal_mismatch", + "response_mismatch", "replayed", ] ApprovalStatus = Literal["pending", "approved", "denied", "expired"] @@ -174,14 +176,43 @@ def decide( """Flip pending to approved/denied; None when missing or not pending.""" raise NotImplementedError - def consume(self, nonce: str) -> ApprovalRecord | None: - """Single-use: first call on approved marks consumed; later calls None.""" + def consume(self, nonce: str, *, now: float) -> ApprovalRecord | None: + """Single-use: first call on approved marks consumed; later calls None. + + Expired approvals (``deadline`` past ``now``) never consume. + """ raise NotImplementedError def mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: """Flip pending to expired; None when missing.""" raise NotImplementedError + async def asave(self, record: ApprovalRecord) -> None: + """Async ``save`` for handlers already on the app event loop.""" + raise NotImplementedError + + async def aget(self, nonce: str) -> ApprovalRecord | None: + """Async ``get`` for handlers already on the app event loop.""" + raise NotImplementedError + + async def alist_pending(self) -> list[ApprovalRecord]: + """Async ``list_pending`` for handlers already on the app event loop.""" + raise NotImplementedError + + async def adecide( + self, nonce: str, approved: bool, *, now: float + ) -> ApprovalRecord | None: + """Async ``decide`` for handlers already on the app event loop.""" + raise NotImplementedError + + async def aconsume(self, nonce: str, *, now: float) -> ApprovalRecord | None: + """Async ``consume`` for handlers already on the app event loop.""" + raise NotImplementedError + + async def amark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: + """Async ``mark_expired`` for handlers already on the app event loop.""" + raise NotImplementedError + class InMemoryApprovalStore(ApprovalStore): """Thread-safe in-memory store. Process restart drops pending approvals.""" @@ -222,11 +253,13 @@ def decide( self._records[nonce] = updated return replace(updated) - def consume(self, nonce: str) -> ApprovalRecord | None: + def consume(self, nonce: str, *, now: float) -> ApprovalRecord | None: with self._lock: record = self._records.get(nonce) if record is None or record.status != "approved" or record.consumed: return None + if record.deadline <= now: + return None updated = replace(record, consumed=True) self._records[nonce] = updated return replace(updated) @@ -241,6 +274,26 @@ def mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: self._records[nonce] = record return replace(record) + async def asave(self, record: ApprovalRecord) -> None: + self.save(record) + + async def aget(self, nonce: str) -> ApprovalRecord | None: + return self.get(nonce) + + async def alist_pending(self) -> list[ApprovalRecord]: + return self.list_pending() + + async def adecide( + self, nonce: str, approved: bool, *, now: float + ) -> ApprovalRecord | None: + return self.decide(nonce, approved, now=now) + + async def aconsume(self, nonce: str, *, now: float) -> ApprovalRecord | None: + return self.consume(nonce, now=now) + + async def amark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: + return self.mark_expired(nonce, now=now) + _T = TypeVar("_T") @@ -248,17 +301,22 @@ def mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: def _run_sync(coro: Coroutine[Any, Any, _T]) -> _T: """Drive one DB coroutine from the store's synchronous interface. - The gate evaluates inline in a sync ``tools/call`` path, while the - gateway's persistence is async. With no running loop this is a plain - ``asyncio.run``; from inside a running loop (the async approvals router) - the coroutine runs on a helper thread with its own loop instead. + Sync callers (scripts, the sync ``tools/call`` path) run only when no + event loop is running, via a plain ``asyncio.run``. From inside a + running loop this refuses instead of hopping threads: the shared + ``AsyncEngine`` is loop-bound (asyncpg), so touching it from another + loop corrupts pooled connections. Async callers must await the + store's ``a*`` methods directly on the app loop. """ try: asyncio.get_running_loop() except RuntimeError: return asyncio.run(coro) - with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: - return pool.submit(asyncio.run, coro).result() + coro.close() + raise RuntimeError( + "DbApprovalStore sync methods cannot run inside a running event " + "loop; await the async (a*) methods on the app loop instead" + ) def _to_db_time(value: float) -> datetime: @@ -314,23 +372,24 @@ class DbApprovalStore(ApprovalStore): Decisions and consumption survive a restart: a consumed nonce stays consumed because consume is a conditional ``UPDATE ... WHERE - status='approved' AND consumed_at IS NULL`` whose rowcount admits exactly - one winner, so neither a restart nor concurrent retries can replay it. + status='approved' AND consumed_at IS NULL AND deadline > now`` whose + rowcount admits exactly one winner, so neither a restart nor concurrent + retries can replay it, and an expired approval can never spend. """ def save(self, record: ApprovalRecord) -> None: - _run_sync(self._save(record)) + _run_sync(self.asave(record)) - async def _save(self, record: ApprovalRecord) -> None: + async def asave(self, record: ApprovalRecord) -> None: factory = get_session_factory() async with factory() as session: await session.merge(_model_from_record(record)) await session.commit() def get(self, nonce: str) -> ApprovalRecord | None: - return _run_sync(self._get(nonce)) + return _run_sync(self.aget(nonce)) - async def _get(self, nonce: str) -> ApprovalRecord | None: + async def aget(self, nonce: str) -> ApprovalRecord | None: factory = get_session_factory() async with factory() as session: result = await session.execute( @@ -342,9 +401,9 @@ async def _get(self, nonce: str) -> ApprovalRecord | None: return _record_from_model(model) if model is not None else None def list_pending(self) -> list[ApprovalRecord]: - return _run_sync(self._list_pending()) + return _run_sync(self.alist_pending()) - async def _list_pending(self) -> list[ApprovalRecord]: + async def alist_pending(self) -> list[ApprovalRecord]: factory = get_session_factory() async with factory() as session: result = await session.execute( @@ -365,9 +424,9 @@ async def _list_pending(self) -> list[ApprovalRecord]: def decide( self, nonce: str, approved: bool, *, now: float ) -> ApprovalRecord | None: - return _run_sync(self._decide(nonce, approved, now=now)) + return _run_sync(self.adecide(nonce, approved, now=now)) - async def _decide( + async def adecide( self, nonce: str, approved: bool, *, now: float ) -> ApprovalRecord | None: factory = get_session_factory() @@ -400,15 +459,17 @@ async def _decide( await session.refresh(model) return _record_from_model(model) - def consume(self, nonce: str) -> ApprovalRecord | None: - return _run_sync(self._consume(nonce)) + def consume(self, nonce: str, *, now: float) -> ApprovalRecord | None: + return _run_sync(self.aconsume(nonce, now=now)) - async def _consume(self, nonce: str) -> ApprovalRecord | None: - """Atomically spend an approved, unconsumed approval — single use. + async def aconsume(self, nonce: str, *, now: float) -> ApprovalRecord | None: + """Atomically spend an approved, unconsumed, unexpired approval. - The ``WHERE status='approved' AND consumed_at IS NULL`` clause is the - single serialization point: exactly one caller (one retry, one - transport) wins, and a restart cannot resurrect a spent approval. + The ``WHERE status='approved' AND consumed_at IS NULL AND + deadline > now`` clause is the single serialization point: exactly + one caller (one retry, one transport) wins, a restart cannot + resurrect a spent approval, and an approval whose deadline passed + between the gate's expiry check and this UPDATE still cannot spend. """ factory = get_session_factory() async with factory() as session: @@ -424,6 +485,10 @@ async def _consume(self, nonce: str) -> ApprovalRecord | None: ColumnElement[bool], cast(Any, ApprovalGateModel.consumed_at).is_(None), ), + cast( + ColumnElement[bool], + ApprovalGateModel.deadline > _to_db_time(now), + ), ) .values(consumed_at=utc_now()) ) @@ -439,9 +504,9 @@ async def _consume(self, nonce: str) -> ApprovalRecord | None: return _record_from_model(model) if model is not None else None def mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: - return _run_sync(self._mark_expired(nonce, now=now)) + return _run_sync(self.amark_expired(nonce, now=now)) - async def _mark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: + async def amark_expired(self, nonce: str, *, now: float) -> ApprovalRecord | None: factory = get_session_factory() async with factory() as session: result = await session.execute( @@ -490,6 +555,33 @@ class ApprovalDecision: nonce: str | None = None +def _pause_payload(tool: str, nonce: str, request_state: str) -> dict[str, Any]: + """Build the SEP-2322 ``input_required`` pause payload. + + ``inputRequests`` is a map keyed by request id; each value is the client + request the server wants answered, here an ``elicitation/create`` asking + a human to approve the paused tool call. The client answers with an + ``inputResponses`` map keyed by the same id. + """ + return { + "resultType": "input_required", + "inputRequests": { + nonce: { + "method": "elicitation/create", + "params": { + "message": f"Approve tool call: {tool}", + "requestedSchema": { + "type": "object", + "properties": {"approved": {"type": "boolean"}}, + "required": ["approved"], + }, + }, + } + }, + "requestState": request_state, + } + + class ApprovalGate: """Entry point for the future mcp_standard.py hook.""" @@ -530,10 +622,16 @@ def evaluate( session_id: str, client_supports_input_required: bool, request_state: str | None = None, - input_responses: list[Any] | dict[str, Any] | None = None, + input_responses: dict[str, Any] | None = None, request_id: str | None = None, ) -> ApprovalDecision: - """Decide PAUSE, EXECUTE, or REJECT for one tools/call attempt.""" + """Decide PAUSE, EXECUTE, or REJECT for one tools/call attempt. + + Sync path for callers with no running event loop. Async callers + (FastAPI handlers, the async MCP hook) must use :meth:`aevaluate`, + which awaits the store on the app loop instead of crossing loops + with the shared engine. + """ canonical = _load_canonical() if request_id is not None: logger.debug("approval request_id=%s logged only, never keyed", request_id) @@ -558,6 +656,146 @@ def evaluate( idempotency_key=idempotency_key, client_supports_input_required=client_supports_input_required, request_state=request_state, + input_responses=input_responses, + ) + + async def aevaluate( + self, + caller: str, + tool: str, + arguments: dict[str, Any] | None, + session_id: str, + client_supports_input_required: bool, + request_state: str | None = None, + input_responses: dict[str, Any] | None = None, + request_id: str | None = None, + ) -> ApprovalDecision: + """Async mirror of :meth:`evaluate` for callers on the app loop. + + Awaits the store directly on the running loop; never crosses loops + with the shared engine. + """ + canonical = _load_canonical() + if request_id is not None: + logger.debug("approval request_id=%s logged only, never keyed", request_id) + args_hash = canonical.args_hash(arguments) + idempotency_key = canonical.idempotency_key( + caller=caller, tool=tool, arguments=arguments, session_id=session_id + ) + if request_state is None: + return await self._apause_new_call( + caller=caller, + tool=tool, + session_id=session_id, + args_hash=args_hash, + idempotency_key=idempotency_key, + client_supports_input_required=client_supports_input_required, + ) + return await self._aevaluate_retry( + caller=caller, + tool=tool, + session_id=session_id, + args_hash=args_hash, + idempotency_key=idempotency_key, + client_supports_input_required=client_supports_input_required, + request_state=request_state, + input_responses=input_responses, + ) + + def _check_sealed_fields( + self, + sealed: dict[str, Any], + *, + caller: str, + tool: str, + session_id: str, + args_hash: str, + idempotency_key: str, + nonce: str, + ) -> ApprovalDecision | None: + """Reject when the retry inputs drift from the sealed state.""" + if sealed.get("tool") != tool: + self._emit("tool_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="tool_mismatch", nonce=nonce + ) + if sealed.get("sessionId") != session_id: + self._emit("session_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="session_mismatch", nonce=nonce + ) + if sealed.get("principal") != caller: + self._emit("principal_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="principal_mismatch", nonce=nonce + ) + if sealed.get("argsHash") != args_hash: + self._emit("args_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="args_mismatch", nonce=nonce + ) + # Last: the key is derived from caller, tool, args, and session, so a + # mismatch here with all inputs matching means the key derivation + # itself drifted between pause and retry. + if sealed.get("idempotencyKey") != idempotency_key: + self._emit("key_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="key_mismatch", nonce=nonce) + return None + + def _check_input_responses( + self, + input_responses: dict[str, Any] | None, + *, + nonce: str, + tool: str, + caller: str, + ) -> ApprovalDecision | None: + """Reject when the retry answers no input request for this pause. + + SEP-2322 keys ``inputResponses`` by the same request id the pause + carried in ``inputRequests``. The response content itself is ignored: + only the local human decision in the store can approve. + """ + if not isinstance(input_responses, dict) or nonce not in input_responses: + self._emit("response_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="response_mismatch", nonce=nonce + ) + return None + + def _check_record( + self, + record: ApprovalRecord, + *, + tool: str, + session_id: str, + idempotency_key: str, + caller: str, + ) -> ApprovalDecision | None: + """Reject when the stored record drifts from the retry inputs.""" + nonce = record.nonce + if record.tool != tool: + self._emit("tool_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="tool_mismatch", nonce=nonce + ) + if record.session_id != session_id: + self._emit("session_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision( + action="REJECT", reason="session_mismatch", nonce=nonce + ) + if record.idempotency_key != idempotency_key: + self._emit("key_mismatch", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="key_mismatch", nonce=nonce) + return None + + @staticmethod + def _is_expired(now: float, sealed_deadline: Any, record: ApprovalRecord) -> bool: + return ( + not isinstance(sealed_deadline, (int, float)) + or now > sealed_deadline + or now > record.deadline + or record.status == "expired" ) def _pause_new_call( @@ -611,22 +849,62 @@ def _pause_new_call( return ApprovalDecision( action="PAUSE", nonce=nonce, - payload={ - "resultType": "input_required", - "inputRequests": [ - { - "requestId": nonce, - "prompt": f"Approve tool call: {tool}", - "schema": { - "type": "object", - "properties": {"approved": {"type": "boolean"}}, - "required": ["approved"], - }, - } - ], - "requestState": state, + payload=_pause_payload(tool, nonce, state), + ) + + async def _apause_new_call( + self, + *, + caller: str, + tool: str, + session_id: str, + args_hash: str, + idempotency_key: str, + client_supports_input_required: bool, + ) -> ApprovalDecision: + if not client_supports_input_required: + self._emit( + "unsupported_client", + nonce=None, + tool=tool, + principal=caller, + session_id=session_id, + ) + return ApprovalDecision(action="REJECT", reason="unsupported_client") + secret = self._require_secret() + now = self.clock() + nonce = secrets.token_urlsafe(16) + deadline = now + self._ttl + await self.store.asave( + ApprovalRecord( + nonce=nonce, + idempotency_key=idempotency_key, + args_hash=args_hash, + principal=caller, + tool=tool, + session_id=session_id, + created_at=now, + deadline=deadline, + ) + ) + state = _seal_state( + secret, + { + "v": STATE_VERSION, + "argsHash": args_hash, + "principal": caller, + "tool": tool, + "sessionId": session_id, + "idempotencyKey": idempotency_key, + "deadline": deadline, + "nonce": nonce, }, ) + return ApprovalDecision( + action="PAUSE", + nonce=nonce, + payload=_pause_payload(tool, nonce, state), + ) def _evaluate_retry( self, @@ -638,6 +916,7 @@ def _evaluate_retry( idempotency_key: str, client_supports_input_required: bool, request_state: str, + input_responses: dict[str, Any] | None, ) -> ApprovalDecision: if not client_supports_input_required: self._emit( @@ -670,58 +949,133 @@ def _evaluate_retry( session_id=session_id, ) return ApprovalDecision(action="REJECT", reason="tampered") - if sealed.get("tool") != tool: - self._emit("tool_mismatch", nonce=nonce, tool=tool, principal=caller) + rejected = self._check_sealed_fields( + sealed, + caller=caller, + tool=tool, + session_id=session_id, + args_hash=args_hash, + idempotency_key=idempotency_key, + nonce=nonce, + ) + if rejected is not None: + return rejected + rejected = self._check_input_responses( + input_responses, nonce=nonce, tool=tool, caller=caller + ) + if rejected is not None: + return rejected + record = self.store.get(nonce) + if record is None: + self._emit("tampered", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="tampered", nonce=nonce) + rejected = self._check_record( + record, + tool=tool, + session_id=session_id, + idempotency_key=idempotency_key, + caller=caller, + ) + if rejected is not None: + return rejected + now = self.clock() + if self._is_expired(now, sealed.get("deadline"), record): + self.store.mark_expired(nonce, now=now) + self._emit("timeout", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="timeout", nonce=nonce) + if record.status == "denied": + self._emit("denied", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="denied", nonce=nonce) + if record.status == "pending": return ApprovalDecision( - action="REJECT", reason="tool_mismatch", nonce=nonce + action="PAUSE", + nonce=nonce, + payload=_pause_payload(tool, nonce, request_state), ) - if sealed.get("sessionId") != session_id: - self._emit("session_mismatch", nonce=nonce, tool=tool, principal=caller) - return ApprovalDecision( - action="REJECT", reason="session_mismatch", nonce=nonce + consumed = self.store.consume(nonce, now=now) + if consumed is None: + self._emit("replayed", nonce=nonce, tool=tool, principal=caller) + return ApprovalDecision(action="REJECT", reason="replayed", nonce=nonce) + return ApprovalDecision( + action="EXECUTE", idempotency_key=idempotency_key, nonce=nonce + ) + + async def _aevaluate_retry( + self, + *, + caller: str, + tool: str, + session_id: str, + args_hash: str, + idempotency_key: str, + client_supports_input_required: bool, + request_state: str, + input_responses: dict[str, Any] | None, + ) -> ApprovalDecision: + """Async mirror of :meth:`_evaluate_retry` on the app loop.""" + if not client_supports_input_required: + self._emit( + "unsupported_client", + nonce=None, + tool=tool, + principal=caller, + session_id=session_id, ) - if sealed.get("principal") != caller: - self._emit("principal_mismatch", nonce=nonce, tool=tool, principal=caller) - return ApprovalDecision( - action="REJECT", reason="principal_mismatch", nonce=nonce + return ApprovalDecision(action="REJECT", reason="unsupported_client") + secret = self._require_secret() + try: + sealed = _unseal_state(secret, request_state) + except _StateTampered: + self._emit( + "tampered", + nonce=None, + tool=tool, + principal=caller, + session_id=session_id, ) - if sealed.get("argsHash") != args_hash: - self._emit("args_mismatch", nonce=nonce, tool=tool, principal=caller) - return ApprovalDecision( - action="REJECT", reason="args_mismatch", nonce=nonce + return ApprovalDecision(action="REJECT", reason="tampered") + nonce = sealed.get("nonce") + if not isinstance(nonce, str) or not nonce: + self._emit( + "tampered", + nonce=None, + tool=tool, + principal=caller, + session_id=session_id, ) - # Last: the key is derived from caller, tool, args, and session, so a - # mismatch here with all inputs matching means the key derivation - # itself drifted between pause and retry. - if sealed.get("idempotencyKey") != idempotency_key: - self._emit("key_mismatch", nonce=nonce, tool=tool, principal=caller) - return ApprovalDecision(action="REJECT", reason="key_mismatch", nonce=nonce) - record = self.store.get(nonce) + return ApprovalDecision(action="REJECT", reason="tampered") + rejected = self._check_sealed_fields( + sealed, + caller=caller, + tool=tool, + session_id=session_id, + args_hash=args_hash, + idempotency_key=idempotency_key, + nonce=nonce, + ) + if rejected is not None: + return rejected + rejected = self._check_input_responses( + input_responses, nonce=nonce, tool=tool, caller=caller + ) + if rejected is not None: + return rejected + record = await self.store.aget(nonce) if record is None: self._emit("tampered", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision(action="REJECT", reason="tampered", nonce=nonce) - if record.tool != tool: - self._emit("tool_mismatch", nonce=nonce, tool=tool, principal=caller) - return ApprovalDecision( - action="REJECT", reason="tool_mismatch", nonce=nonce - ) - if record.session_id != session_id: - self._emit("session_mismatch", nonce=nonce, tool=tool, principal=caller) - return ApprovalDecision( - action="REJECT", reason="session_mismatch", nonce=nonce - ) - if record.idempotency_key != idempotency_key: - self._emit("key_mismatch", nonce=nonce, tool=tool, principal=caller) - return ApprovalDecision(action="REJECT", reason="key_mismatch", nonce=nonce) + rejected = self._check_record( + record, + tool=tool, + session_id=session_id, + idempotency_key=idempotency_key, + caller=caller, + ) + if rejected is not None: + return rejected now = self.clock() - sealed_deadline = sealed.get("deadline") - if ( - not isinstance(sealed_deadline, (int, float)) - or now > sealed_deadline - or now > record.deadline - or record.status == "expired" - ): - self.store.mark_expired(nonce, now=now) + if self._is_expired(now, sealed.get("deadline"), record): + await self.store.amark_expired(nonce, now=now) self._emit("timeout", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision(action="REJECT", reason="timeout", nonce=nonce) if record.status == "denied": @@ -731,23 +1085,9 @@ def _evaluate_retry( return ApprovalDecision( action="PAUSE", nonce=nonce, - payload={ - "resultType": "input_required", - "inputRequests": [ - { - "requestId": nonce, - "prompt": f"Approve tool call: {tool}", - "schema": { - "type": "object", - "properties": {"approved": {"type": "boolean"}}, - "required": ["approved"], - }, - } - ], - "requestState": request_state, - }, + payload=_pause_payload(tool, nonce, request_state), ) - consumed = self.store.consume(nonce) + consumed = await self.store.aconsume(nonce, now=now) if consumed is None: self._emit("replayed", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision(action="REJECT", reason="replayed", nonce=nonce) diff --git a/gateway/tests/test_approval_gate.py b/gateway/tests/test_approval_gate.py index 692391946..43568d9db 100644 --- a/gateway/tests/test_approval_gate.py +++ b/gateway/tests/test_approval_gate.py @@ -21,7 +21,7 @@ if str(_path) not in sys.path: sys.path.insert(0, str(_path)) -from typing import Any # noqa: E402 +from typing import Any, cast # noqa: E402 import pytest # noqa: E402 from goose_amw import canonical as goose_canonical # noqa: E402 @@ -132,7 +132,19 @@ def _pause(gate: ApprovalGate) -> Any: return decision -def _retry(gate: ApprovalGate, state: str, **kwargs: Any) -> Any: +async def _apause(gate: ApprovalGate) -> Any: + decision = await gate.aevaluate(CALLER, TOOL, ARGS, SESSION, True) + assert decision.action == "PAUSE" + assert decision.payload is not None + return decision + + +def _responses(nonce: str) -> dict[str, Any]: + """SEP-2322 retry answers, keyed by the pause's request id.""" + return {nonce: {"approved": True}} + + +def _retry(gate: ApprovalGate, state: str, nonce: str, **kwargs: Any) -> Any: params: dict[str, Any] = { "caller": CALLER, "tool": TOOL, @@ -140,7 +152,7 @@ def _retry(gate: ApprovalGate, state: str, **kwargs: Any) -> Any: "session_id": SESSION, "client_supports_input_required": True, "request_state": state, - "input_responses": [{"requestId": _fresh_id(), "approved": True}], + "input_responses": _responses(nonce), } params.update(kwargs) return gate.evaluate( @@ -153,12 +165,43 @@ def _retry(gate: ApprovalGate, state: str, **kwargs: Any) -> Any: ) +async def _aretry(gate: ApprovalGate, state: str, nonce: str, **kwargs: Any) -> Any: + params: dict[str, Any] = { + "caller": CALLER, + "tool": TOOL, + "arguments": ARGS, + "session_id": SESSION, + "client_supports_input_required": True, + "request_state": state, + "input_responses": _responses(nonce), + } + params.update(kwargs) + return await gate.aevaluate( + params.pop("caller"), + params.pop("tool"), + params.pop("arguments"), + params.pop("session_id"), + params.pop("client_supports_input_required"), + **params, + ) + + def test_first_call_pauses_with_input_required_payload(gate: ApprovalGate) -> None: decision = _pause(gate) assert decision.payload is not None assert decision.payload["resultType"] == "input_required" - assert isinstance(decision.payload["inputRequests"], list) - assert decision.payload["inputRequests"] + requests = decision.payload["inputRequests"] + assert isinstance(requests, dict) + assert decision.nonce is not None + assert set(requests) == {decision.nonce} + entry = requests[decision.nonce] + assert entry["method"] == "elicitation/create" + assert entry["params"]["message"] == f"Approve tool call: {TOOL}" + assert entry["params"]["requestedSchema"] == { + "type": "object", + "properties": {"approved": {"type": "boolean"}}, + "required": ["approved"], + } assert isinstance(decision.payload["requestState"], str) assert decision.payload["requestState"] @@ -170,7 +213,7 @@ def test_key_equals_goose_idempotency_key(gate: ApprovalGate) -> None: decision = _pause(gate) assert decision.nonce is not None gate.store.decide(decision.nonce, True, now=gate.clock()) - executed = _retry(gate, decision.payload["requestState"]) + executed = _retry(gate, decision.payload["requestState"], decision.nonce) assert executed.action == "EXECUTE" assert executed.idempotency_key == expected @@ -181,9 +224,9 @@ def test_approved_retry_executes_exactly_once( decision = _pause(gate) assert decision.nonce is not None gate.store.decide(decision.nonce, True, now=gate.clock()) - first = _retry(gate, decision.payload["requestState"]) + first = _retry(gate, decision.payload["requestState"], decision.nonce) assert first.action == "EXECUTE" - second = _retry(gate, decision.payload["requestState"]) + second = _retry(gate, decision.payload["requestState"], decision.nonce) assert second.action == "REJECT" assert second.reason == "replayed" assert [event for event, _ in receipts] == ["replayed"] @@ -191,10 +234,13 @@ def test_approved_retry_executes_exactly_once( def test_pending_retry_repauses(gate: ApprovalGate) -> None: decision = _pause(gate) - again = _retry(gate, decision.payload["requestState"]) + assert decision.nonce is not None + again = _retry(gate, decision.payload["requestState"], decision.nonce) assert again.action == "PAUSE" assert again.payload is not None assert again.payload["resultType"] == "input_required" + assert set(again.payload["inputRequests"]) == {decision.nonce} + assert again.payload["requestState"] == decision.payload["requestState"] def test_deny_rejects_and_receipts( @@ -203,7 +249,7 @@ def test_deny_rejects_and_receipts( decision = _pause(gate) assert decision.nonce is not None gate.store.decide(decision.nonce, False, now=gate.clock()) - rejected = _retry(gate, decision.payload["requestState"]) + rejected = _retry(gate, decision.payload["requestState"], decision.nonce) assert rejected.action == "REJECT" assert rejected.reason == "denied" assert [event for event, _ in receipts] == ["denied"] @@ -213,8 +259,9 @@ def test_expired_rejects_timeout_and_marks_expired( gate: ApprovalGate, clock: _Clock, receipts: list[tuple[str, dict[str, Any]]] ) -> None: decision = _pause(gate) + assert decision.nonce is not None clock.now += 3600 + 1 - rejected = _retry(gate, decision.payload["requestState"]) + rejected = _retry(gate, decision.payload["requestState"], decision.nonce) assert rejected.action == "REJECT" assert rejected.reason == "timeout" assert decision.nonce is not None @@ -229,7 +276,8 @@ def test_tampered_state_rejects( decision = _pause(gate) state: str = decision.payload["requestState"] tampered = ("A" if state[0] != "A" else "B") + state[1:] - rejected = _retry(gate, tampered) + # The seal fails before the responses are read, so any key shape works. + rejected = _retry(gate, tampered, _fresh_id()) assert rejected.action == "REJECT" assert rejected.reason == "tampered" assert [event for event, _ in receipts] == ["tampered"] @@ -239,13 +287,14 @@ def test_unknown_nonce_rejects_tampered( gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]], clock: _Clock ) -> None: decision = _pause(gate) + assert decision.nonce is not None fresh = ApprovalGate( secret=SECRET, store=InMemoryApprovalStore(), clock=clock, receipt_sink=lambda event, record: receipts.append((event, record)), ) - rejected = _retry(fresh, decision.payload["requestState"]) + rejected = _retry(fresh, decision.payload["requestState"], decision.nonce) assert rejected.action == "REJECT" assert rejected.reason == "tampered" @@ -266,8 +315,12 @@ def test_unsupported_client_retry_rejects_with_receipt( gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] ) -> None: decision = _pause(gate) + assert decision.nonce is not None rejected = _retry( - gate, decision.payload["requestState"], client_supports_input_required=False + gate, + decision.payload["requestState"], + decision.nonce, + client_supports_input_required=False, ) assert rejected.action == "REJECT" assert rejected.reason == "unsupported_client" @@ -280,8 +333,12 @@ def test_args_mismatch_rejects( tmp_path: Path, ) -> None: decision = _pause(gate) + assert decision.nonce is not None rejected = _retry( - gate, decision.payload["requestState"], arguments={"path": str(tmp_path)} + gate, + decision.payload["requestState"], + decision.nonce, + arguments={"path": str(tmp_path)}, ) assert rejected.action == "REJECT" assert rejected.reason == "args_mismatch" @@ -292,7 +349,10 @@ def test_principal_mismatch_rejects( gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] ) -> None: decision = _pause(gate) - rejected = _retry(gate, decision.payload["requestState"], caller=_fresh_id()) + assert decision.nonce is not None + rejected = _retry( + gate, decision.payload["requestState"], decision.nonce, caller=_fresh_id() + ) assert rejected.action == "REJECT" assert rejected.reason == "principal_mismatch" assert [event for event, _ in receipts] == ["principal_mismatch"] @@ -302,7 +362,10 @@ def test_tool_mismatch_rejects( gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] ) -> None: decision = _pause(gate) - rejected = _retry(gate, decision.payload["requestState"], tool=_fresh_id()) + assert decision.nonce is not None + rejected = _retry( + gate, decision.payload["requestState"], decision.nonce, tool=_fresh_id() + ) assert rejected.action == "REJECT" assert rejected.reason == "tool_mismatch" assert [event for event, _ in receipts] == ["tool_mismatch"] @@ -312,7 +375,10 @@ def test_session_mismatch_rejects( gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] ) -> None: decision = _pause(gate) - rejected = _retry(gate, decision.payload["requestState"], session_id=_fresh_id()) + assert decision.nonce is not None + rejected = _retry( + gate, decision.payload["requestState"], decision.nonce, session_id=_fresh_id() + ) assert rejected.action == "REJECT" assert rejected.reason == "session_mismatch" assert [event for event, _ in receipts] == ["session_mismatch"] @@ -335,7 +401,8 @@ def idempotency_key(**kwargs: Any) -> str: return secrets.token_hex(32) monkeypatch.setattr(gate_module, "_load_canonical", lambda: _DriftedCanonical) - rejected = _retry(gate, decision.payload["requestState"]) + assert decision.nonce is not None + rejected = _retry(gate, decision.payload["requestState"], decision.nonce) assert rejected.action == "REJECT" assert rejected.reason == "key_mismatch" assert [event for event, _ in receipts] == ["key_mismatch"] @@ -370,12 +437,68 @@ def test_stored_record_mismatch_rejects( while tampered == getattr(record, field): tampered = _fresh_id() gate.store.save(replace(record, **{field: tampered})) - rejected = _retry(gate, decision.payload["requestState"]) + rejected = _retry(gate, decision.payload["requestState"], decision.nonce) assert rejected.action == "REJECT" assert rejected.reason == reason assert [event for event, _ in receipts] == [reason] +@pytest.mark.parametrize("case", ["missing", "empty", "wrong_id", "legacy_list"]) +def test_retry_without_matching_input_response_rejects( + gate: ApprovalGate, + receipts: list[tuple[str, dict[str, Any]]], + case: str, +) -> None: + """The retry must answer the pause's request id; anything else rejects.""" + decision = _pause(gate) + assert decision.nonce is not None + if case == "missing": + responses = None + elif case == "empty": + responses = {} + elif case == "wrong_id": + responses = _responses(_fresh_id()) + else: + responses = cast(Any, [{"requestId": decision.nonce, "approved": True}]) + rejected = _retry( + gate, + decision.payload["requestState"], + decision.nonce, + input_responses=responses, + ) + assert rejected.action == "REJECT" + assert rejected.reason == "response_mismatch" + assert [event for event, _ in receipts] == ["response_mismatch"] + + +def test_consume_rejects_expired_approval(gate: ApprovalGate, clock: _Clock) -> None: + decision = _pause(gate) + assert decision.nonce is not None + gate.store.decide(decision.nonce, True, now=gate.clock()) + clock.now += 3600 + 1 + assert gate.store.consume(decision.nonce, now=clock()) is None + record = gate.store.get(decision.nonce) + assert record is not None + assert record.consumed is False + + +async def test_async_evaluate_executes_after_approval( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: + decision = await gate.aevaluate(CALLER, TOOL, ARGS, SESSION, True) + assert decision.action == "PAUSE" + assert decision.payload is not None + assert decision.nonce is not None + assert set(decision.payload["inputRequests"]) == {decision.nonce} + await gate.store.adecide(decision.nonce, True, now=gate.clock()) + executed = await _aretry(gate, decision.payload["requestState"], decision.nonce) + assert executed.action == "EXECUTE" + replayed = await _aretry(gate, decision.payload["requestState"], decision.nonce) + assert replayed.action == "REJECT" + assert replayed.reason == "replayed" + assert [event for event, _ in receipts] == ["replayed"] + + def test_missing_secret_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv("AMW_APPROVAL_STATE_SECRET", raising=False) gate = ApprovalGate(store=InMemoryApprovalStore()) @@ -405,13 +528,13 @@ async def test_db_consumed_nonce_stays_consumed_across_restart( clean_database: Any, purge_approval_gate_table: Any, ) -> None: - decision = _pause(db_gate) + decision = await _apause(db_gate) assert decision.nonce is not None state: str = decision.payload["requestState"] # Simulated restart: a new store instance sees the same pending row. restarted = DbApprovalStore() - record = restarted.get(decision.nonce) + record = await restarted.aget(decision.nonce) assert record is not None assert record.status == "pending" assert record.tool == TOOL @@ -422,19 +545,20 @@ async def test_db_consumed_nonce_stays_consumed_across_restart( caller=CALLER, tool=TOOL, arguments=ARGS, session_id=SESSION ) assert record.deadline == clock.now + 300 - assert [pending.nonce for pending in restarted.list_pending()] == [decision.nonce] + pending = await restarted.alist_pending() + assert [item.nonce for item in pending] == [decision.nonce] - restarted.decide(decision.nonce, True, now=clock()) - executed = _retry(db_gate, state) + await restarted.adecide(decision.nonce, True, now=clock()) + executed = await _aretry(db_gate, state, decision.nonce) assert executed.action == "EXECUTE" # Second restart: the nonce stays consumed; the retry cannot replay. restarted_again = DbApprovalStore() - consumed = restarted_again.get(decision.nonce) + consumed = await restarted_again.aget(decision.nonce) assert consumed is not None assert consumed.consumed is True - assert restarted_again.consume(decision.nonce) is None - replayed = _retry(db_gate, state) + assert await restarted_again.aconsume(decision.nonce, now=clock()) is None + replayed = await _aretry(db_gate, state, decision.nonce) assert replayed.action == "REJECT" assert replayed.reason == "replayed" assert [event for event, _ in receipts] == ["replayed"] @@ -447,20 +571,48 @@ async def test_db_denied_decision_visible_across_instances( clean_database: Any, purge_approval_gate_table: Any, ) -> None: - decision = _pause(db_gate) + decision = await _apause(db_gate) assert decision.nonce is not None decider = DbApprovalStore() - denied = decider.decide(decision.nonce, False, now=clock()) + denied = await decider.adecide(decision.nonce, False, now=clock()) assert denied is not None assert denied.status == "denied" observer = DbApprovalStore() - assert observer.get(decision.nonce) is not None - assert observer.get(decision.nonce).status == "denied" # type: ignore[union-attr] - assert observer.list_pending() == [] - assert observer.decide(decision.nonce, True, now=clock()) is None - - rejected = _retry(db_gate, decision.payload["requestState"]) + assert await observer.aget(decision.nonce) is not None + observed = await observer.aget(decision.nonce) + assert observed is not None + assert observed.status == "denied" + assert await observer.alist_pending() == [] + assert await observer.adecide(decision.nonce, True, now=clock()) is None + + rejected = await _aretry(db_gate, decision.payload["requestState"], decision.nonce) assert rejected.action == "REJECT" assert rejected.reason == "denied" assert [event for event, _ in receipts] == ["denied"] + + +async def test_db_consume_rejects_expired_approval( + db_gate: ApprovalGate, + clock: _Clock, + clean_database: Any, + purge_approval_gate_table: Any, +) -> None: + """The atomic consume UPDATE refuses an approval past its deadline.""" + decision = await _apause(db_gate) + assert decision.nonce is not None + store = DbApprovalStore() + approved = await store.adecide(decision.nonce, True, now=clock()) + assert approved is not None + clock.now += 3600 + 1 + assert await store.aconsume(decision.nonce, now=clock()) is None + record = await store.aget(decision.nonce) + assert record is not None + assert record.consumed is False + + +async def test_db_sync_store_refuses_running_loop() -> None: + """Sync DB calls inside a loop refuse instead of crossing engine loops.""" + store = DbApprovalStore() + with pytest.raises(RuntimeError, match="running event loop"): + store.get(_fresh_id()) diff --git a/gateway/tests/test_approvals_router.py b/gateway/tests/test_approvals_router.py index ca5f16fa2..c84f8a533 100644 --- a/gateway/tests/test_approvals_router.py +++ b/gateway/tests/test_approvals_router.py @@ -29,6 +29,7 @@ from starlette.testclient import TestClient # noqa: E402 import app.routers.approvals as approvals_module # noqa: E402 +from app.core.auth import AuthContext, get_auth_context # noqa: E402 from app.db.approval_gate_models import ApprovalGateModel # noqa: E402 from app.db.database import get_session_factory # noqa: E402 from app.routers.approvals import ( # noqa: E402 @@ -81,12 +82,17 @@ def _random_invalid_host() -> str: return f"{uuid.uuid4().hex}.invalid" +def _admin_auth() -> AuthContext: + return AuthContext(source="env", raw_key="synthetic", is_bootstrap_admin=True) + + @pytest.fixture def app() -> FastAPI: set_approval_store_for_tests(InMemoryApprovalStore()) application = FastAPI() application.include_router(router) application.dependency_overrides[require_loopback] = lambda: None + application.dependency_overrides[get_auth_context] = _admin_auth return application @@ -107,9 +113,9 @@ async def purge_approval_gate_table() -> Any: await session.commit() -def _seed() -> ApprovalRecord: +def _make_record() -> ApprovalRecord: now = time.time() - record = ApprovalRecord( + return ApprovalRecord( nonce=secrets.token_urlsafe(16), idempotency_key=f"amw-fb-{secrets.token_hex(32)}", args_hash=goose_canonical.args_hash(ARGS), @@ -119,6 +125,10 @@ def _seed() -> ApprovalRecord: created_at=now, deadline=now + 300, ) + + +def _seed() -> ApprovalRecord: + record = _make_record() get_approval_store().save(record) return record @@ -172,6 +182,36 @@ def test_non_loopback_client_gets_403() -> None: assert client.post(f"/v1/approvals/{unknown}/deny").status_code == 403 +def test_unauthenticated_client_gets_401() -> None: + set_approval_store_for_tests(InMemoryApprovalStore()) + application = FastAPI() + application.include_router(router) + application.dependency_overrides[require_loopback] = lambda: None + client = TestClient(application) + unknown = _fresh_id() + assert client.get("/v1/approvals/pending").status_code == 401 + assert client.post(f"/v1/approvals/{unknown}/approve").status_code == 401 + assert client.post(f"/v1/approvals/{unknown}/deny").status_code == 401 + + +def test_non_admin_key_gets_403() -> None: + set_approval_store_for_tests(InMemoryApprovalStore()) + application = FastAPI() + application.include_router(router) + application.dependency_overrides[require_loopback] = lambda: None + application.dependency_overrides[get_auth_context] = lambda: AuthContext( + source="db", + raw_key="synthetic", + wallet_id=_fresh_id(), + key_id=_fresh_id(), + ) + client = TestClient(application) + unknown = _fresh_id() + assert client.get("/v1/approvals/pending").status_code == 403 + assert client.post(f"/v1/approvals/{unknown}/approve").status_code == 403 + assert client.post(f"/v1/approvals/{unknown}/deny").status_code == 403 + + def test_default_store_is_db_backed() -> None: import importlib @@ -186,12 +226,13 @@ async def test_approve_through_http_decides_db_row( client: TestClient, clean_database: None, purge_approval_gate_table: None ) -> None: set_approval_store_for_tests(DbApprovalStore()) - record = _seed() + record = _make_record() + await DbApprovalStore().asave(record) response = client.post(f"/v1/approvals/{record.nonce}/approve") assert response.status_code == 200 assert response.json() == {"nonce": record.nonce, "status": "approved"} assert client.get("/v1/approvals/pending").json() == {"approvals": []} - stored = DbApprovalStore().get(record.nonce) + stored = await DbApprovalStore().aget(record.nonce) assert stored is not None assert stored.status == "approved" From 9a3a4776b0fd5e9935b6d84bd6fe6084598a61ed Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:02:53 -0700 Subject: [PATCH 10/12] docs(gateway): drop symbol-style inputResponses references Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/services/approval_gate.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gateway/app/services/approval_gate.py b/gateway/app/services/approval_gate.py index 4b228ccb9..41cfdfa6f 100644 --- a/gateway/app/services/approval_gate.py +++ b/gateway/app/services/approval_gate.py @@ -561,7 +561,7 @@ def _pause_payload(tool: str, nonce: str, request_state: str) -> dict[str, Any]: ``inputRequests`` is a map keyed by request id; each value is the client request the server wants answered, here an ``elicitation/create`` asking a human to approve the paused tool call. The client answers with an - ``inputResponses`` map keyed by the same id. + MCP inputResponses map keyed by the same id. """ return { "resultType": "input_required", @@ -752,7 +752,7 @@ def _check_input_responses( ) -> ApprovalDecision | None: """Reject when the retry answers no input request for this pause. - SEP-2322 keys ``inputResponses`` by the same request id the pause + SEP-2322 keys MCP inputResponses by the same request id the pause carried in ``inputRequests``. The response content itself is ignored: only the local human decision in the store can approve. """ From 7d4d0ea83772cef16023d2242b5c63000373f7aa Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:15:10 -0700 Subject: [PATCH 11/12] fix(gateway): enforce approval deadlines, emit consumed receipt, authenticate CLI Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/routers/approvals.py | 2 +- gateway/app/services/approval_gate.py | 57 +++++++---- gateway/scripts/amw_approvals.py | 36 ++++++- gateway/tests/test_amw_approvals_cli.py | 118 +++++++++++++++++++++++ gateway/tests/test_approval_gate.py | 121 +++++++++++++++++++++++- gateway/tests/test_approvals_router.py | 24 +++++ 6 files changed, 334 insertions(+), 24 deletions(-) create mode 100644 gateway/tests/test_amw_approvals_cli.py diff --git a/gateway/app/routers/approvals.py b/gateway/app/routers/approvals.py index a9c1265ac..b69a1d440 100644 --- a/gateway/app/routers/approvals.py +++ b/gateway/app/routers/approvals.py @@ -74,7 +74,7 @@ async def list_pending( created_at=record.created_at, deadline=record.deadline, ) - for record in await get_approval_store().alist_pending() + for record in await get_approval_store().alist_pending(now=time.time()) ] return PendingApprovalsResponse(approvals=approvals) diff --git a/gateway/app/services/approval_gate.py b/gateway/app/services/approval_gate.py index 41cfdfa6f..9a122e008 100644 --- a/gateway/app/services/approval_gate.py +++ b/gateway/app/services/approval_gate.py @@ -17,7 +17,8 @@ - ``requestState`` is HMAC-SHA256 sealed; missing secret fails closed. - Clients without ``input_required`` support are rejected, with a receipt. - Deny, timeout, tampering, and every retry mismatch each emit a receipt via - an injectable sink and never execute. + an injectable sink and never execute. A successful consume emits a + consumed receipt through the same sink. - Pending approvals, decisions, and consumption live in the database (``DbApprovalStore``), so a restart cannot replay an approval. """ @@ -167,13 +168,17 @@ def save(self, record: ApprovalRecord) -> None: def get(self, nonce: str) -> ApprovalRecord | None: raise NotImplementedError - def list_pending(self) -> list[ApprovalRecord]: + def list_pending(self, *, now: float | None = None) -> list[ApprovalRecord]: + """Pending records, excluding ones past deadline when now is given.""" raise NotImplementedError def decide( self, nonce: str, approved: bool, *, now: float ) -> ApprovalRecord | None: - """Flip pending to approved/denied; None when missing or not pending.""" + """Flip pending to approved/denied. + + None when missing, not pending, or past its deadline. + """ raise NotImplementedError def consume(self, nonce: str, *, now: float) -> ApprovalRecord | None: @@ -195,7 +200,7 @@ async def aget(self, nonce: str) -> ApprovalRecord | None: """Async ``get`` for handlers already on the app event loop.""" raise NotImplementedError - async def alist_pending(self) -> list[ApprovalRecord]: + async def alist_pending(self, *, now: float | None = None) -> list[ApprovalRecord]: """Async ``list_pending`` for handlers already on the app event loop.""" raise NotImplementedError @@ -230,12 +235,12 @@ def get(self, nonce: str) -> ApprovalRecord | None: record = self._records.get(nonce) return replace(record) if record else None - def list_pending(self) -> list[ApprovalRecord]: + def list_pending(self, *, now: float | None = None) -> list[ApprovalRecord]: with self._lock: return [ replace(record) for record in self._records.values() - if record.status == "pending" + if record.status == "pending" and (now is None or record.deadline > now) ] def decide( @@ -245,6 +250,8 @@ def decide( record = self._records.get(nonce) if record is None or record.status != "pending": return None + if record.deadline <= now: + return None updated = replace( record, status="approved" if approved else "denied", @@ -280,8 +287,8 @@ async def asave(self, record: ApprovalRecord) -> None: async def aget(self, nonce: str) -> ApprovalRecord | None: return self.get(nonce) - async def alist_pending(self) -> list[ApprovalRecord]: - return self.list_pending() + async def alist_pending(self, *, now: float | None = None) -> list[ApprovalRecord]: + return self.list_pending(now=now) async def adecide( self, nonce: str, approved: bool, *, now: float @@ -400,21 +407,27 @@ async def aget(self, nonce: str) -> ApprovalRecord | None: model = result.scalar_one_or_none() return _record_from_model(model) if model is not None else None - def list_pending(self) -> list[ApprovalRecord]: - return _run_sync(self.alist_pending()) + def list_pending(self, *, now: float | None = None) -> list[ApprovalRecord]: + return _run_sync(self.alist_pending(now=now)) - async def alist_pending(self) -> list[ApprovalRecord]: + async def alist_pending(self, *, now: float | None = None) -> list[ApprovalRecord]: factory = get_session_factory() async with factory() as session: - result = await session.execute( - select(ApprovalGateModel) - .where( + stmt = select(ApprovalGateModel).where( + cast( + ColumnElement[bool], + ApprovalGateModel.status == "pending", + ) + ) + if now is not None: + stmt = stmt.where( cast( ColumnElement[bool], - ApprovalGateModel.status == "pending", + ApprovalGateModel.deadline > _to_db_time(now), ) ) - .order_by( + result = await session.execute( + stmt.order_by( col(ApprovalGateModel.created_at).asc(), col(ApprovalGateModel.nonce).asc(), ) @@ -429,6 +442,12 @@ def decide( async def adecide( self, nonce: str, approved: bool, *, now: float ) -> ApprovalRecord | None: + """Atomically decide a pending, unexpired approval. + + The UPDATE condition carries deadline > now alongside the pending + status check, so an approval whose deadline passed between any read + and this write is refused instead of decided. + """ factory = get_session_factory() async with factory() as session: result = await session.execute( @@ -447,6 +466,10 @@ async def adecide( ColumnElement[bool], ApprovalGateModel.status == "pending", ), + cast( + ColumnElement[bool], + ApprovalGateModel.deadline > _to_db_time(now), + ), ) .values( status="approved" if approved else "denied", @@ -996,6 +1019,7 @@ def _evaluate_retry( if consumed is None: self._emit("replayed", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision(action="REJECT", reason="replayed", nonce=nonce) + self._emit("consumed", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision( action="EXECUTE", idempotency_key=idempotency_key, nonce=nonce ) @@ -1091,6 +1115,7 @@ async def _aevaluate_retry( if consumed is None: self._emit("replayed", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision(action="REJECT", reason="replayed", nonce=nonce) + self._emit("consumed", nonce=nonce, tool=tool, principal=caller) return ApprovalDecision( action="EXECUTE", idempotency_key=idempotency_key, nonce=nonce ) diff --git a/gateway/scripts/amw_approvals.py b/gateway/scripts/amw_approvals.py index d22288236..d9bf76b04 100644 --- a/gateway/scripts/amw_approvals.py +++ b/gateway/scripts/amw_approvals.py @@ -3,6 +3,8 @@ Talks to the gateway's local-only endpoints over loopback; run on the gateway host. In-process callers can use the approval store directly instead. +Export VALID_API_KEYS with the gateway bootstrap admin key first; every +request sends it. The key is never printed. Usage: python gateway/scripts/amw_approvals.py list @@ -21,10 +23,25 @@ DEFAULT_BASE_URL = "http://127.0.0.1:8000" BASE_URL_ENV = "AMW_GATEWAY_URL" +# Same setting the gateway reads for its bootstrap admin keys +# (app/core/config.py VALID_API_KEYS, comma-separated) and the same header +# the auth dependency reads (app/core/auth.py, default X-API-Key). +API_KEY_ENV = "VALID_API_KEYS" +API_KEY_HEADER = "X-API-Key" -def _client(base_url: str) -> httpx.Client: - return httpx.Client(base_url=base_url, timeout=10.0) +def _read_api_key() -> str: + """First key from API_KEY_ENV; empty when unset or blank.""" + for entry in os.environ.get(API_KEY_ENV, "").split(","): + if entry.strip(): + return entry.strip() + return "" + + +def _client(base_url: str, api_key: str) -> httpx.Client: + return httpx.Client( + base_url=base_url, timeout=10.0, headers={API_KEY_HEADER: api_key} + ) def _format_time(value: float) -> str: @@ -35,7 +52,7 @@ def _format_time(value: float) -> str: def cmd_list(args: argparse.Namespace) -> int: try: - response = _client(args.base_url).get("/v1/approvals/pending") + response = _client(args.base_url, args.api_key).get("/v1/approvals/pending") response.raise_for_status() except httpx.HTTPError as exc: print( @@ -56,7 +73,9 @@ def cmd_list(args: argparse.Namespace) -> int: def _decide(args: argparse.Namespace, action: str) -> int: try: - response = _client(args.base_url).post(f"/v1/approvals/{args.nonce}/{action}") + response = _client(args.base_url, args.api_key).post( + f"/v1/approvals/{args.nonce}/{action}" + ) except httpx.HTTPError as exc: print( f"error: gateway not reachable at {args.base_url}: {exc}", file=sys.stderr @@ -101,6 +120,15 @@ def build_parser() -> argparse.ArgumentParser: def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) + api_key = _read_api_key() + if not api_key: + print( + f"error: {API_KEY_ENV} is not set; export the gateway " + "bootstrap admin key first", + file=sys.stderr, + ) + return 1 + args.api_key = api_key if args.command == "list": return cmd_list(args) if args.command in ("approve", "deny"): diff --git a/gateway/tests/test_amw_approvals_cli.py b/gateway/tests/test_amw_approvals_cli.py new file mode 100644 index 000000000..a8e908da2 --- /dev/null +++ b/gateway/tests/test_amw_approvals_cli.py @@ -0,0 +1,118 @@ +"""Tests for the local approve/deny CLI. + +The placeholder key below follows the synthetic style used by the other +auth-adjacent tests; it is never a real credential. +""" + +from __future__ import annotations + +import importlib.util +import secrets +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +_SPEC = importlib.util.spec_from_file_location( + "amw_approvals", ROOT / "scripts" / "amw_approvals.py" +) +assert _SPEC and _SPEC.loader +amw_approvals = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(amw_approvals) + +PLACEHOLDER_KEY = f"synthetic-{secrets.token_hex(8)}" + + +def test_key_env_and_header_match_gateway_auth() -> None: + from app.core.config import get_settings + + settings = get_settings() + assert amw_approvals.API_KEY_ENV == "VALID_API_KEYS" + assert "VALID_API_KEYS" in type(settings).model_fields + assert amw_approvals.API_KEY_HEADER == settings.API_KEY_HEADER + + +def test_missing_key_exits_naming_env_var( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.delenv("VALID_API_KEYS", raising=False) + assert amw_approvals.main(["list"]) == 1 + assert "VALID_API_KEYS" in capsys.readouterr().err + + +def test_blank_key_exits( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("VALID_API_KEYS", " , ") + assert amw_approvals.main(["approve", "nonce"]) == 1 + assert "VALID_API_KEYS" in capsys.readouterr().err + + +def test_first_comma_separated_entry_wins( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("VALID_API_KEYS", f" , {PLACEHOLDER_KEY} , second") + assert amw_approvals._read_api_key() == PLACEHOLDER_KEY + + +def test_client_attaches_key_header(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("VALID_API_KEYS", PLACEHOLDER_KEY) + client = amw_approvals._client("http://127.0.0.1:9", amw_approvals._read_api_key()) + assert client.headers["X-API-Key"] == PLACEHOLDER_KEY + + +class _StubResponse: + def __init__(self, payload: dict[str, object]) -> None: + self._payload = payload + self.status_code = 200 + + def json(self) -> dict[str, object]: + return self._payload + + def raise_for_status(self) -> None: + return None + + +def test_every_command_sends_key_and_never_prints_it( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + sent: list[tuple[str, str, dict[str, str]]] = [] + + class _RecordingClient: + def __init__( + self, + base_url: str = "", + timeout: float | None = None, + headers: dict[str, str] | None = None, + ) -> None: + self._headers = dict(headers or {}) + + def get(self, path: str) -> _StubResponse: + sent.append(("GET", path, dict(self._headers))) + return _StubResponse({"approvals": []}) + + def post(self, path: str) -> _StubResponse: + sent.append(("POST", path, dict(self._headers))) + return _StubResponse({"status": "approved"}) + + monkeypatch.setattr(amw_approvals.httpx, "Client", _RecordingClient) + monkeypatch.setenv("VALID_API_KEYS", PLACEHOLDER_KEY) + assert amw_approvals.main(["list"]) == 0 + assert amw_approvals.main(["approve", "nonce-a"]) == 0 + assert amw_approvals.main(["deny", "nonce-b"]) == 0 + assert [method for method, _, _ in sent] == ["GET", "POST", "POST"] + for _, _, headers in sent: + assert headers == {"X-API-Key": PLACEHOLDER_KEY} + out = capsys.readouterr() + assert PLACEHOLDER_KEY not in out.out + assert PLACEHOLDER_KEY not in out.err + + +def test_unreachable_gateway_error_hides_key( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("VALID_API_KEYS", PLACEHOLDER_KEY) + assert amw_approvals.main(["--base-url", "http://127.0.0.1:9", "list"]) == 1 + out = capsys.readouterr() + assert PLACEHOLDER_KEY not in out.out + assert PLACEHOLDER_KEY not in out.err diff --git a/gateway/tests/test_approval_gate.py b/gateway/tests/test_approval_gate.py index 43568d9db..7a45b9909 100644 --- a/gateway/tests/test_approval_gate.py +++ b/gateway/tests/test_approval_gate.py @@ -5,6 +5,7 @@ made at runtime (secrets.token_hex / uuid.uuid4). Nothing here is hand-invented. """ +import asyncio import json import secrets import sys @@ -229,7 +230,21 @@ def test_approved_retry_executes_exactly_once( second = _retry(gate, decision.payload["requestState"], decision.nonce) assert second.action == "REJECT" assert second.reason == "replayed" - assert [event for event, _ in receipts] == ["replayed"] + assert [event for event, _ in receipts] == ["consumed", "replayed"] + + +def test_execute_emits_consumed_receipt( + gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] +) -> None: + decision = _pause(gate) + assert decision.nonce is not None + gate.store.decide(decision.nonce, True, now=gate.clock()) + executed = _retry(gate, decision.payload["requestState"], decision.nonce) + assert executed.action == "EXECUTE" + assert [event for event, _ in receipts] == ["consumed"] + assert receipts[0][1]["nonce"] == decision.nonce + assert receipts[0][1]["tool"] == TOOL + assert receipts[0][1]["principal"] == CALLER def test_pending_retry_repauses(gate: ApprovalGate) -> None: @@ -482,6 +497,51 @@ def test_consume_rejects_expired_approval(gate: ApprovalGate, clock: _Clock) -> assert record.consumed is False +def test_decide_refuses_expired_approval(gate: ApprovalGate, clock: _Clock) -> None: + decision = _pause(gate) + assert decision.nonce is not None + clock.now += 3600 + 1 + assert gate.store.decide(decision.nonce, True, now=clock()) is None + assert gate.store.decide(decision.nonce, False, now=clock()) is None + record = gate.store.get(decision.nonce) + assert record is not None + assert record.status == "pending" + + +async def test_adecide_refuses_expired_approval( + gate: ApprovalGate, clock: _Clock +) -> None: + decision = _pause(gate) + assert decision.nonce is not None + clock.now += 3600 + 1 + assert await gate.store.adecide(decision.nonce, True, now=clock()) is None + record = await gate.store.aget(decision.nonce) + assert record is not None + assert record.status == "pending" + + +def test_list_pending_excludes_expired(gate: ApprovalGate, clock: _Clock) -> None: + first = _pause(gate) + assert first.nonce is not None + clock.now += 3600 + 1 + second = _pause(gate) + assert second.nonce is not None + pending = gate.store.list_pending(now=clock()) + assert [record.nonce for record in pending] == [second.nonce] + + +async def test_alist_pending_excludes_expired( + gate: ApprovalGate, clock: _Clock +) -> None: + first = _pause(gate) + assert first.nonce is not None + clock.now += 3600 + 1 + second = _pause(gate) + assert second.nonce is not None + pending = await gate.store.alist_pending(now=clock()) + assert [record.nonce for record in pending] == [second.nonce] + + async def test_async_evaluate_executes_after_approval( gate: ApprovalGate, receipts: list[tuple[str, dict[str, Any]]] ) -> None: @@ -496,7 +556,29 @@ async def test_async_evaluate_executes_after_approval( replayed = await _aretry(gate, decision.payload["requestState"], decision.nonce) assert replayed.action == "REJECT" assert replayed.reason == "replayed" - assert [event for event, _ in receipts] == ["replayed"] + assert [event for event, _ in receipts] == ["consumed", "replayed"] + + +async def test_db_concurrent_retries_execute_exactly_once( + db_gate: ApprovalGate, + clock: _Clock, + receipts: list[tuple[str, dict[str, Any]]], + clean_database: Any, + purge_approval_gate_table: Any, +) -> None: + """Two retries racing on one approval spend it exactly once.""" + decision = await _apause(db_gate) + assert decision.nonce is not None + state: str = decision.payload["requestState"] + await db_gate.store.adecide(decision.nonce, True, now=clock()) + first, second = await asyncio.gather( + _aretry(db_gate, state, decision.nonce), + _aretry(db_gate, state, decision.nonce), + ) + assert sorted([first.action, second.action]) == ["EXECUTE", "REJECT"] + loser = first if first.action == "REJECT" else second + assert loser.reason == "replayed" + assert sorted(event for event, _ in receipts) == ["consumed", "replayed"] def test_missing_secret_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None: @@ -561,7 +643,7 @@ async def test_db_consumed_nonce_stays_consumed_across_restart( replayed = await _aretry(db_gate, state, decision.nonce) assert replayed.action == "REJECT" assert replayed.reason == "replayed" - assert [event for event, _ in receipts] == ["replayed"] + assert [event for event, _ in receipts] == ["consumed", "replayed"] async def test_db_denied_decision_visible_across_instances( @@ -616,3 +698,36 @@ async def test_db_sync_store_refuses_running_loop() -> None: store = DbApprovalStore() with pytest.raises(RuntimeError, match="running event loop"): store.get(_fresh_id()) + + +async def test_db_adecide_refuses_expired_approval( + db_gate: ApprovalGate, + clock: _Clock, + clean_database: Any, + purge_approval_gate_table: Any, +) -> None: + """The atomic decide UPDATE refuses an approval past its deadline.""" + decision = await _apause(db_gate) + assert decision.nonce is not None + store = DbApprovalStore() + clock.now += 3600 + 1 + assert await store.adecide(decision.nonce, True, now=clock()) is None + assert await store.adecide(decision.nonce, False, now=clock()) is None + record = await store.aget(decision.nonce) + assert record is not None + assert record.status == "pending" + + +async def test_db_alist_pending_excludes_expired( + db_gate: ApprovalGate, + clock: _Clock, + clean_database: Any, + purge_approval_gate_table: Any, +) -> None: + first = await _apause(db_gate) + assert first.nonce is not None + clock.now += 3600 + 1 + second = await _apause(db_gate) + assert second.nonce is not None + pending = await DbApprovalStore().alist_pending(now=clock()) + assert [record.nonce for record in pending] == [second.nonce] diff --git a/gateway/tests/test_approvals_router.py b/gateway/tests/test_approvals_router.py index c84f8a533..1710cf450 100644 --- a/gateway/tests/test_approvals_router.py +++ b/gateway/tests/test_approvals_router.py @@ -10,6 +10,7 @@ import sys import time import uuid +from dataclasses import replace from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[2] @@ -165,6 +166,29 @@ def test_second_decision_is_404(client: TestClient) -> None: assert client.post(f"/v1/approvals/{record.nonce}/deny").status_code == 404 +def _seed_expired() -> ApprovalRecord: + record = replace(_make_record(), deadline=time.time() - 1) + get_approval_store().save(record) + return record + + +def test_pending_excludes_expired_record(client: TestClient) -> None: + live = _seed() + _seed_expired() + response = client.get("/v1/approvals/pending") + assert response.status_code == 200 + assert [item["nonce"] for item in response.json()["approvals"]] == [live.nonce] + + +def test_decide_expired_record_is_404(client: TestClient) -> None: + record = _seed_expired() + assert client.post(f"/v1/approvals/{record.nonce}/approve").status_code == 404 + assert client.post(f"/v1/approvals/{record.nonce}/deny").status_code == 404 + stored = get_approval_store().get(record.nonce) + assert stored is not None + assert stored.status == "pending" + + def test_unknown_nonce_is_404(client: TestClient) -> None: unknown = _fresh_id() assert client.post(f"/v1/approvals/{unknown}/approve").status_code == 404 From c102200d45ea5cf3ada98bb1efe5d7dca8ab3b35 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:20:52 -0700 Subject: [PATCH 12/12] fix(gateway): keep CLI missing-key error free of tainted values Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/scripts/amw_approvals.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gateway/scripts/amw_approvals.py b/gateway/scripts/amw_approvals.py index d9bf76b04..4ee597fc9 100644 --- a/gateway/scripts/amw_approvals.py +++ b/gateway/scripts/amw_approvals.py @@ -123,7 +123,7 @@ def main(argv: list[str] | None = None) -> int: api_key = _read_api_key() if not api_key: print( - f"error: {API_KEY_ENV} is not set; export the gateway " + "error: VALID_API_KEYS is not set; export the gateway " "bootstrap admin key first", file=sys.stderr, )