From 638ea21cfb5e2dc3cab4d4c38dc1e3a1bc5cb443 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 13:45:18 +0000 Subject: [PATCH 01/25] fix(trust): refuse before the charge when the signing key cannot sign A governed call whose replica cannot sign (key row disabled, bound to other key material) used to reserve, charge and run the tool, then fail to sign the audit event and receipt: a debited wallet with no evidence and an idempotency record left for manual review. SigningKeyService.assert_ready_to_sign runs the same resolution every signature runs and raises SigningKeyUnavailableError. The governed MCP entry (_execute_registered_tool), the standard /mcp surface before its auto-mint, and AWI HTTP admission call it before anything is reserved or charged. The routers answer it as retryable (-32005, HTTP 409 on REST invoke, HTTP 503 on AWI) since nothing was recorded. Health reads the configured key row without writing it and reports a retired, disabled or mismatched row as down; /health/ready now includes signing_key. Refs #280 (PR A of three). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/core/health.py | 50 +++ gateway/app/main.py | 5 + gateway/app/routers/mcp.py | 19 +- gateway/app/routers/mcp_standard.py | 17 + gateway/app/services/awi_http_governance.py | 24 +- gateway/app/services/signing_keys.py | 51 +++ gateway/app/trust/__init__.py | 2 + gateway/app/trust/signing.py | 2 + gateway/docs/key-management.md | 40 ++- gateway/tests/test_awi_http_governance.py | 69 ++++ gateway/tests/test_signing_key_precharge.py | 345 ++++++++++++++++++++ 11 files changed, 610 insertions(+), 14 deletions(-) create mode 100644 gateway/tests/test_signing_key_precharge.py diff --git a/gateway/app/core/health.py b/gateway/app/core/health.py index 40ae893f2..245a53fe5 100644 --- a/gateway/app/core/health.py +++ b/gateway/app/core/health.py @@ -32,6 +32,7 @@ from .trust_mode import is_production_like_environment from ..services.signing_keys import ( SigningKeyError, + get_signing_key_service, validate_signing_key_configuration, ) @@ -466,6 +467,10 @@ async def _check_signing_key() -> dict[str, Any]: "error": "signing_key_unavailable", } + row_problem = await _configured_key_row_problem() + if row_problem is not None: + return {"status": "down", "state": "unusable", "error": row_problem} + if state == "ephemeral": return { "status": "up", @@ -475,6 +480,51 @@ async def _check_signing_key() -> dict[str, Any]: return {"status": "up", "state": "loaded"} +# Key row states that mean this replica cannot be trusted to sign. A missing +# row is fine (the first signature creates it); an active row is fine. +_UNUSABLE_KEY_ROW_STATUSES: dict[str, str] = { + "retired": "signing_key_retired", + "disabled": "signing_key_disabled", +} + + +async def _configured_key_row_problem() -> str | None: + """Read the configured key's row and name why it cannot sign, if it cannot. + + Read-only: it never creates or reactivates the row, so a health probe can + not undo a retirement. A replica still configured with a retired or + disabled key id, or with key material that does not match its row, is + reported down, which takes it out of a readiness-gated rotation before it + reaches the charge. A row lookup that fails (for example the database is + down) is left to the postgres check rather than reported twice here. + """ + + try: + status = await get_signing_key_service().configured_key_status() + except SigningKeyError as exc: + if str(exc) == "signing_key_id_public_key_mismatch": + return "signing_key_id_public_key_mismatch" + return None + except Exception: + logger.debug("signing key row check raised", exc_info=True) + return None + if status is None: + return None + return _UNUSABLE_KEY_ROW_STATUSES.get(status) + + +async def check_signing_key_readiness() -> dict[str, Any]: + """``/health/ready`` entry for the signing key, shared with the full report. + + Down when this replica's configured key cannot sign: invalid or missing key + material, or a key row that is retired, disabled or bound to other key + material. A load balancer that gates on readiness then stops sending + governed calls to a replica that would refuse them, or, while a retired + row can still be reactivated, would sign under a key the operator retired. + """ + return await _run_check("signing_key", _check_signing_key) + + async def check_database_readiness() -> dict[str, Any]: """Probe the required ORM database with the shared timeout/sanitization.""" result = await _run_check("database", _check_postgres) diff --git a/gateway/app/main.py b/gateway/app/main.py index 8abe0b551..ccfeaa52a 100644 --- a/gateway/app/main.py +++ b/gateway/app/main.py @@ -40,6 +40,7 @@ build_public_dependency_report, check_redis_liveness, check_database_readiness, + check_signing_key_readiness, check_mqtt_readiness, gather_dependency_report, ) @@ -1337,6 +1338,10 @@ async def health_ready(): if checks["database"]["status"] != "up": all_healthy = False + checks["signing_key"] = await check_signing_key_readiness() + if checks["signing_key"]["status"] != "up": + all_healthy = False + return JSONResponse( status_code=200 if all_healthy else 503, content={ diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index 1f8b67e92..b4857950b 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -118,6 +118,7 @@ PermitError, PolicyDecision, ReceiptWriteContendedError, + SigningKeyUnavailableError, evaluate_tool_invocation, evaluate_wallet_policy, get_agent_money, @@ -128,6 +129,7 @@ get_permit_service, get_quote_service, get_receipt_service, + get_signing_key_service, permit_constraints_snapshot, recipient_binding_matches, record_audit_event, @@ -456,6 +458,7 @@ def _safe_jsonrpc_id(value: Any) -> str | int | float | None: "audit_chain_head_contention", "receipt_write_contended", "permit_write_contended", + "signing_key_unavailable", "tool_execution_failed", ) } @@ -468,6 +471,7 @@ def _safe_jsonrpc_id(value: Any) -> str | int | float | None: AuditChainContendedError: "audit_chain_head_contention", ReceiptWriteContendedError: "receipt_write_contended", PermitWriteContendedError: "permit_write_contended", + SigningKeyUnavailableError: SigningKeyUnavailableError.reason, ToolPermissionDenied: "Permission denied", PermissionError: "Permission denied", ToolExecutionError: "tool_execution_failed", @@ -832,7 +836,12 @@ async def handle_messages( AuditChainContendedError, ReceiptWriteContendedError, PermitWriteContendedError, + SigningKeyUnavailableError, ) as e: + # SigningKeyUnavailableError joins this family because it is only + # raised before anything is begun or charged: retrying the same key + # on a replica whose signing key can sign is safe. + # # All five mean the same thing to a caller: nothing terminal was # recorded, retry the same idempotency key. -32005 is this # surface's retryable code. The public message is a canned string @@ -1185,6 +1194,12 @@ async def _execute_registered_tool( Those coordinates name whichever row holds them now; only the granted id names ours. """ + # Refuse before anything is begun, reserved or charged when this replica's + # configured signing key cannot sign. Every governed outcome past the + # charge needs a signed audit event and receipt; finding out there leaves + # a debited wallet with no evidence. Here it costs the caller one retry, + # on a replica whose key can sign, with nothing recorded. + await get_signing_key_service().assert_ready_to_sign() owned_record: dict[str, Any] = {} try: return await _execute_registered_tool_inner( @@ -5228,6 +5243,7 @@ async def _handle_tools_call( (AuditChainContendedError, "audit_chain_head_contention"), (ReceiptWriteContendedError, "receipt_write_contended"), (PermitWriteContendedError, "permit_write_contended"), + (SigningKeyUnavailableError, SigningKeyUnavailableError.reason), (ToolPermissionDenied, "Permission denied"), (PermissionError, "Permission denied"), (ToolExecutionError, "tool_execution_failed"), @@ -5392,8 +5408,9 @@ async def invoke_tool( AuditChainContendedError, ReceiptWriteContendedError, PermitWriteContendedError, + SigningKeyUnavailableError, ) as exc: - # Same five-way retryable family as /mcp/messages: the caller may + # Same retryable family as /mcp/messages: the caller may # retry the same idempotency key. A pre-effect # ReceiptWriteContendedError that reached here without this entry fell # through to except Exception and answered 200 isError internal_error, diff --git a/gateway/app/routers/mcp_standard.py b/gateway/app/routers/mcp_standard.py index 0feb82333..3f4db0d2e 100644 --- a/gateway/app/routers/mcp_standard.py +++ b/gateway/app/routers/mcp_standard.py @@ -81,6 +81,10 @@ from app.core.browser_origin import validate_browser_origin from app.services.audit_chain import AuditChainContendedError from app.services.receipts import ReceiptWriteContendedError +from app.services.signing_keys import ( + SigningKeyUnavailableError, + get_signing_key_service, +) from app.services.billing_engine import LedgerWriteContendedError from app.core.config import get_settings from app.core.time import utc_now @@ -737,6 +741,15 @@ async def _governed_tools_call( }, ) + # Refuse before the auto-mint (which signs a permit) and before anything + # is begun or charged when this replica's signing key cannot sign. The + # governed pipeline checks again at its own entry; this one keeps the mint + # from failing first under a less precise error. + try: + await get_signing_key_service().assert_ready_to_sign() + except SigningKeyUnavailableError as exc: + raise _mcp_error(-32005, SigningKeyUnavailableError.reason) from exc + auto_minted = permit_id is None # Unkeyed mutating calls get a deterministic retry slot so a lost-response # retry resolves to the same auto permit and replays the original receipt @@ -843,6 +856,10 @@ async def _governed_tools_call( # non-retryable type, so what arrives is a refusal that ran nothing and # whose idempotency record has already been released. raise _mcp_error(-32005, ReceiptWriteContendedError.reason) from e + except SigningKeyUnavailableError as e: + # Raised only before anything is begun or charged (the governed entry + # check), so the same key may be retried on a replica that can sign. + raise _mcp_error(-32005, SigningKeyUnavailableError.reason) from e except PermitWriteContendedError as e: # The first guarded write on the way in, and the one this ladder was # missing: a contended permit reserve fell past every branch here into diff --git a/gateway/app/services/awi_http_governance.py b/gateway/app/services/awi_http_governance.py index 386cd96c5..d2bb39361 100644 --- a/gateway/app/services/awi_http_governance.py +++ b/gateway/app/services/awi_http_governance.py @@ -41,7 +41,12 @@ from app.services.ownership import CallerIdentity from app.services.permits import PermitError, get_permit_service from app.services.receipts import get_receipt_service -from app.services.signing_keys import canonical_json, sha256_hex +from app.services.signing_keys import ( + SigningKeyUnavailableError, + canonical_json, + get_signing_key_service, + sha256_hex, +) logger = logging.getLogger(__name__) @@ -448,6 +453,23 @@ async def _admit_awi_http_governed(ctx: AwiHttpGovernedContext) -> None: permits = get_permit_service() idem = get_idempotency_service() + # Refuse before the reservation and the charge when this replica's signing + # key cannot sign: the receipt written after the callback needs it, and + # finding out there would leave a debited wallet with no receipt. Nothing + # is reserved yet, so the begun record is released for a retry. + try: + await get_signing_key_service().assert_ready_to_sign() + except SigningKeyUnavailableError as exc: + await idem.abandon( + wallet_id=ctx.wallet_id, + endpoint=ctx.endpoint, + idempotency_key=ctx.idempotency_key, + expected_record_id=ctx.record_id, + ) + raise HTTPException( + status_code=503, + detail={"error": exc.reason, "tool": ctx.tool_name}, + ) from exc try: await permits.reserve_budget( ctx.permit_id, diff --git a/gateway/app/services/signing_keys.py b/gateway/app/services/signing_keys.py index efcd56653..85c667cfc 100644 --- a/gateway/app/services/signing_keys.py +++ b/gateway/app/services/signing_keys.py @@ -29,6 +29,25 @@ class SigningKeyError(RuntimeError): """Raised when trust-plane signing or verification cannot proceed.""" +class SigningKeyUnavailableError(SigningKeyError): + """The configured signing key cannot sign, found before any effect. + + Raised only by :meth:`SigningKeyService.assert_ready_to_sign`, which the + governed pipelines call before they reserve budget or charge a wallet. + Nothing has been recorded when this is raised, so a caller may retry the + same idempotency key (on a replica whose key can sign). It is deliberately + its own type: a plain :class:`SigningKeyError` raised after a charge must + never be read as retryable. ``cause`` keeps the underlying reason for the + server log; the wire only ever carries ``reason``. + """ + + reason = "signing_key_unavailable" + + def __init__(self, cause: str) -> None: + self.cause = cause + super().__init__(self.reason) + + # Names the exact byte-level contract :func:`canonical_json` implements, so an # independent verifier can state which rules it was written against. Bump only # when the bytes a signature covers change shape — never for additive fields, @@ -323,6 +342,38 @@ async def ensure_active_key(self) -> SigningKeyModel: self._assert_key_not_disabled(key) return key + async def assert_ready_to_sign(self) -> None: + """Fail before any effect when the configured key cannot sign. + + Runs the same resolution every signature runs (``ensure_active_key``) + and converts its refusal into :class:`SigningKeyUnavailableError`. + Governed pipelines call this before reserving budget or charging, so a + replica whose key is disabled, mismatched or otherwise unusable refuses + while nothing has moved, instead of charging and then failing to sign + the audit event and receipt. + """ + + try: + await self.ensure_active_key() + except SigningKeyError as exc: + raise SigningKeyUnavailableError(str(exc)) from exc + + async def configured_key_status(self) -> str | None: + """Read the configured key's row status without writing anything. + + Returns ``None`` when no row exists yet (the first signature creates + it). Raises :class:`SigningKeyError` with + ``signing_key_id_public_key_mismatch`` when the row is bound to other + key material. Used by readiness reporting, which must not mutate state. + """ + + public_key_b64 = self._public_key_b64() + key = await self.get_public_key(self._key_id) + if key is None: + return None + self._assert_public_key_mapping(key, public_key_b64) + return key.status + async def get_active_key(self) -> SigningKeyModel: """Return the current active public metadata, creating it if needed.""" diff --git a/gateway/app/trust/__init__.py b/gateway/app/trust/__init__.py index 7148a4af9..f39e144e7 100644 --- a/gateway/app/trust/__init__.py +++ b/gateway/app/trust/__init__.py @@ -163,6 +163,7 @@ RECEIPT_CANONICALIZATION, SigningKeyError, SigningKeyService, + SigningKeyUnavailableError, canonical_json, get_signing_key_service, sha256_hex, @@ -255,6 +256,7 @@ "RECEIPT_CANONICALIZATION", "SigningKeyService", "SigningKeyError", + "SigningKeyUnavailableError", "get_signing_key_service", "canonical_json", "sha256_hex", diff --git a/gateway/app/trust/signing.py b/gateway/app/trust/signing.py index a70b385b0..c89020a9a 100644 --- a/gateway/app/trust/signing.py +++ b/gateway/app/trust/signing.py @@ -11,6 +11,7 @@ RECEIPT_CANONICALIZATION, SigningKeyError, SigningKeyService, + SigningKeyUnavailableError, canonical_json, get_signing_key_service, sha256_hex, @@ -20,6 +21,7 @@ "RECEIPT_CANONICALIZATION", "SigningKeyError", "SigningKeyService", + "SigningKeyUnavailableError", "canonical_json", "get_signing_key_service", "sha256_hex", diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index 8b1898a2a..2d79c52b6 100644 --- a/gateway/docs/key-management.md +++ b/gateway/docs/key-management.md @@ -243,23 +243,39 @@ Rollout order that avoids the problem: a stale replica un-retires the old row on its next restart, signature or `GET /v1/signing-keys/active` request. -How an operator can and cannot tell a replica is stale: - -- Health does not show it. The signing-key health check - (`validate_signing_key_configuration`) validates configuration only and - never reads the key row status, so a stale replica reports `up`. -- The reactivation is silent. It writes no log line and returns no error. -- The only visible sign is the published key set: the old `kid` flipping from - `retired` back to `active`. - -Why the code is not changed: making a retired key refuse to sign +How an operator can tell a replica is stale: + +- `GET /health/ready` and `GET /health/dependencies` read the configured key's + row without writing it. A row that is `retired` or `disabled`, or that is + bound to other key material, reports `signing_key` as `down` with + `signing_key_retired`, `signing_key_disabled` or + `signing_key_id_public_key_mismatch`, and readiness answers 503. A load + balancer that gates on readiness stops sending traffic to that replica. +- Until a retired key refuses to sign, the window is short: the next request + that reaches the stale replica reactivates the row, and health reports `up` + again. The reactivation itself writes no log line and returns no error. +- The published key set shows it too: the old `kid` flips from `retired` back + to `active`. + +What a governed call does when the key cannot sign: the governed MCP +transports (`/mcp/messages`, `/mcp/tools/{tool}/invoke` and `/mcp`) and the +AWI HTTP routes run `SigningKeyService.assert_ready_to_sign` before they +reserve budget or charge. If the configured key is disabled, bound to other +key material, or otherwise cannot sign, the call is refused with +`signing_key_unavailable` (JSON-RPC `-32005`, HTTP 409 on the REST invoke +route, HTTP 503 on the AWI routes) and nothing is recorded, so the caller can +retry the same idempotency key on a replica whose key can sign. A rotation +that lands after that check and before the call finishes is not covered by +it. + +Why a retired key still signs: making a retired key refuse to sign (`signing_key_retired`) would stop the reactivation, but the pending-refund path relies on it. `RefundReconciliationService.create_pending` resolves the signing key per attempt and restarts after a concurrent rotation, and the restart currently succeeds because `ensure_active_key` reactivates the key. A refusal there would escape as an internal error and lose both the receipt and -the refund work item for a charge that already happened. The maintainer chose -documentation only for now. The analysis and the parked follow-up changes are +the refund work item for a charge that already happened. That path has to +record the refund without a signed receipt first. The plan and its status are in [issue 280](https://github.com/agentmiddleware/agent-middleware/issues/280). This is documented as a known limitation in `SECURITY_LIMITATIONS.md` and diff --git a/gateway/tests/test_awi_http_governance.py b/gateway/tests/test_awi_http_governance.py index f2f24a9cd..4a354faa1 100644 --- a/gateway/tests/test_awi_http_governance.py +++ b/gateway/tests/test_awi_http_governance.py @@ -6,6 +6,7 @@ from typing import Any import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from sqlalchemy import func, select from httpx import ASGITransport, AsyncClient @@ -15,6 +16,7 @@ from app.services import awi_rag_engine as awi_rag_engine_module from app.services.awi_rag_engine import AWIRAGEngine from app.services.idempotency import MAX_CLIENT_IDEMPOTENCY_KEY_LENGTH +from app.services.signing_keys import get_signing_key_service from tests.test_trust_helpers import ( BOOTSTRAP_HEADERS, create_tool_permit, @@ -789,3 +791,70 @@ async def _bridge_raises(*_args: Any, **_kwargs: Any) -> dict[str, Any]: assert debits_after == 1 finally: manager._dom_sessions.pop(session_id, None) + + +async def _wallet_debits(wallet_id: str) -> int: + async with get_session_factory()() as session: + return int( + ( + await session.execute( + select(func.count()) + .select_from(LedgerEntryModel) + .where( + LedgerEntryModel.wallet_id == wallet_id, + LedgerEntryModel.amount < 0, + ) + ) + ).scalar_one() + ) + + +@pytest.mark.anyio +async def test_rag_query_refuses_before_reserving_when_the_key_cannot_sign( + client, clean_database, monkeypatch +): + """An unusable signing key refuses before the reservation and the charge. + + The receipt written after the callback needs the key. Refusing at + admission keeps the wallet whole and releases the begun record, so the + same Idempotency-Key succeeds once the key can sign (issue #280). The key + is made unusable by pairing its id with other key material, which leaves + the stored public key, and so the permit's signature, verifiable. + """ + provisioned = await provision_agent_wallet(client) + wallet_id = provisioned["agent_wallet_id"] + permit = await create_tool_permit( + client, + wallet_id=wallet_id, + key_id=provisioned["key_id"], + tool_name="awi_rag_query", + max_credits=50, + idem_key="permit-awi-signing-precharge", + ) + service = get_signing_key_service() + await service.ensure_active_key() + real_private_key = service._private_key + headers = { + **provisioned["agent_headers"], + "X-Wallet-Id": wallet_id, + "X-Permit-Id": permit["permit_id"], + "Idempotency-Key": "awi-http-signing-precharge-1", + } + debits_before = await _wallet_debits(wallet_id) + monkeypatch.setattr(service, "_private_key", Ed25519PrivateKey.generate()) + + refused = await client.post( + "/v1/awi/rag/query", json=RAG_QUERY_PAYLOAD, headers=headers + ) + + assert refused.status_code == 503, refused.text + assert refused.json()["detail"]["error"] == "signing_key_unavailable" + assert await _wallet_debits(wallet_id) == debits_before + + monkeypatch.setattr(service, "_private_key", real_private_key) + again = await client.post( + "/v1/awi/rag/query", json=RAG_QUERY_PAYLOAD, headers=headers + ) + assert again.status_code == 200, again.text + assert again.json()["receipt"]["outcome"] == "success" + assert await _wallet_debits(wallet_id) == debits_before + 1 diff --git a/gateway/tests/test_signing_key_precharge.py b/gateway/tests/test_signing_key_precharge.py new file mode 100644 index 000000000..8cdaeecc5 --- /dev/null +++ b/gateway/tests/test_signing_key_precharge.py @@ -0,0 +1,345 @@ +"""A replica whose signing key cannot sign refuses before it charges. + +Every governed outcome past the charge needs a signed audit event and a signed +receipt. When the configured key cannot sign (its row is disabled, retired or +bound to other key material) the old order was: reserve, charge, run the tool, +then fail to sign. The wallet was debited and the tool had run, but nothing +recorded either, and the idempotency record stayed in progress for manual +review (issue #280). + +``SigningKeyService.assert_ready_to_sign`` runs the same resolution every +signature runs, before anything is begun, reserved or charged, and the routers +answer its ``SigningKeyUnavailableError`` as retryable (``-32005`` / HTTP 409): +nothing was recorded, so the same key may be retried on a replica whose key +can sign. These tests pin that ordering on each governed transport, and that +the health checks report an unusable key row without changing it. +""" + +from __future__ import annotations + +from typing import Any + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from httpx import ASGITransport, AsyncClient +from sqlalchemy import func, select + +from app.core.health import gather_dependency_report +from app.db.database import get_session_factory +from app.db.models import LedgerEntryModel, ReceiptModel, SigningKeyModel +from app.main import app +from app.schemas.billing import ServiceCategory +from app.services.service_registry import get_service_registry +from app.services.signing_keys import ( + SigningKeyService, + SigningKeyUnavailableError, + get_signing_key_service, +) +from tests.test_trust_helpers import create_tool_permit, provision_agent_wallet + +TOOL_COST = 2.0 +TOOL_NAME = "signing-precharge-echo" + + +@pytest.fixture +async def client() -> AsyncClient: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as value: + yield value + + +@pytest.fixture +def echo_tool(): + runs = {"count": 0} + + def echo(message: str = "ok") -> dict[str, Any]: + runs["count"] += 1 + return {"message": message} + + get_service_registry().register_local( + service_id=TOOL_NAME, + name="Signing precharge echo", + description="Signing-key pre-charge surface test tool", + category=ServiceCategory.AGENT_COMMS, + func=echo, + credits_per_unit=TOOL_COST, + unit_name="call", + ) + try: + yield runs + finally: + get_service_registry().unregister_local(TOOL_NAME) + + +async def _set_key_status(key_id: str, status: str) -> None: + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key_id) + assert row is not None + row.status = status + session.add(row) + await session.commit() + + +async def _key_row(key_id: str) -> SigningKeyModel: + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key_id) + assert row is not None + return row + + +async def _count(model: Any, *conditions: Any) -> int: + async with get_session_factory()() as session: + query = select(func.count()).select_from(model) + for condition in conditions: + query = query.where(condition) + return int(await session.scalar(query) or 0) + + +async def _debits(wallet_id: str) -> int: + return await _count( + LedgerEntryModel, + LedgerEntryModel.wallet_id == wallet_id, + LedgerEntryModel.action == "debit", + ) + + +async def _setup(client: AsyncClient, *, suffix: str) -> dict[str, Any]: + ctx = await provision_agent_wallet(client) + permit = await create_tool_permit( + client, + wallet_id=ctx["agent_wallet_id"], + key_id=ctx["key_id"], + tool_name=TOOL_NAME, + idem_key=f"signing-precharge-permit-{suffix}", + ) + key = await get_signing_key_service().ensure_active_key() + return {"ctx": ctx, "permit": permit, "key_id": key.key_id} + + +def _jsonrpc_body(*, wallet_id: str, permit_id: str, key: str) -> dict[str, Any]: + return { + "jsonrpc": "2.0", + "id": f"call-{key}", + "method": "tools/call", + "params": { + "name": TOOL_NAME, + "arguments": {"message": "hello"}, + "mcpContext": { + "wallet_id": wallet_id, + "permit_id": permit_id, + "idempotency_key": key, + }, + }, + } + + +def _rest_body(*, wallet_id: str, permit_id: str, key: str) -> dict[str, Any]: + return { + "name": TOOL_NAME, + "arguments": {"message": "hello"}, + "mcp_context": { + "wallet_id": wallet_id, + "permit_id": permit_id, + "idempotency_key": key, + }, + } + + +@pytest.mark.anyio +async def test_assert_ready_to_sign_refuses_a_disabled_key_without_touching_it( + clean_database: None, +) -> None: + service = get_signing_key_service() + key = await service.ensure_active_key() + await _set_key_status(key.key_id, "disabled") + + with pytest.raises(SigningKeyUnavailableError) as raised: + await service.assert_ready_to_sign() + + assert str(raised.value) == "signing_key_unavailable" + assert raised.value.cause == "signing_key_disabled" + assert (await _key_row(key.key_id)).status == "disabled" + + +@pytest.mark.anyio +async def test_assert_ready_to_sign_refuses_mismatched_key_material( + clean_database: None, +) -> None: + original = await get_signing_key_service().ensure_active_key() + misconfigured = SigningKeyService() + misconfigured._private_key = Ed25519PrivateKey.generate() + misconfigured._key_id = original.key_id + + with pytest.raises(SigningKeyUnavailableError) as raised: + await misconfigured.assert_ready_to_sign() + + assert raised.value.cause == "signing_key_id_public_key_mismatch" + row = await _key_row(original.key_id) + assert row.public_key_b64 == original.public_key_b64 + assert row.status == "active" + + +@pytest.mark.anyio +async def test_assert_ready_to_sign_passes_for_a_usable_key( + clean_database: None, +) -> None: + await get_signing_key_service().assert_ready_to_sign() + + +@pytest.mark.anyio +async def test_jsonrpc_refuses_before_the_charge_and_the_key_stays_retryable( + client: AsyncClient, clean_database: None, echo_tool +) -> None: + case = await _setup(client, suffix="jsonrpc") + ctx = case["ctx"] + wallet_id = ctx["agent_wallet_id"] + body = _jsonrpc_body( + wallet_id=wallet_id, + permit_id=case["permit"]["permit_id"], + key="signing-precharge-jsonrpc", + ) + debits_before = await _debits(wallet_id) + receipts_before = await _count(ReceiptModel) + await _set_key_status(case["key_id"], "disabled") + + resp = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + + assert resp.status_code == 200, resp.text + error = resp.json()["error"] + assert error["code"] == -32005, error + assert error["message"] == "signing_key_unavailable", error + # Nothing moved: no debit, no receipt, the tool never ran. + assert await _debits(wallet_id) == debits_before + assert await _count(ReceiptModel) == receipts_before + assert echo_tool["count"] == 0 + + # The retry the -32005 promised lands once the key can sign again. + await _set_key_status(case["key_id"], "active") + again = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert again.status_code == 200, again.text + assert "error" not in again.json(), again.text + assert echo_tool["count"] == 1 + assert await _debits(wallet_id) == debits_before + 1 + + +@pytest.mark.anyio +async def test_rest_invoke_refuses_before_the_charge_with_409( + client: AsyncClient, clean_database: None, echo_tool +) -> None: + case = await _setup(client, suffix="rest") + ctx = case["ctx"] + wallet_id = ctx["agent_wallet_id"] + body = _rest_body( + wallet_id=wallet_id, + permit_id=case["permit"]["permit_id"], + key="signing-precharge-rest", + ) + debits_before = await _debits(wallet_id) + await _set_key_status(case["key_id"], "disabled") + + resp = await client.post( + f"/mcp/tools/{TOOL_NAME}/invoke", json=body, headers=ctx["agent_headers"] + ) + + assert resp.status_code == 409, resp.text + assert resp.json()["detail"]["error"] == "signing_key_unavailable" + assert await _debits(wallet_id) == debits_before + assert echo_tool["count"] == 0 + + await _set_key_status(case["key_id"], "active") + again = await client.post( + f"/mcp/tools/{TOOL_NAME}/invoke", json=body, headers=ctx["agent_headers"] + ) + assert again.status_code == 200, again.text + assert again.json()["isError"] is False, again.text + assert echo_tool["count"] == 1 + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("status", "error"), + [("retired", "signing_key_retired"), ("disabled", "signing_key_disabled")], +) +async def test_health_reports_an_unusable_key_row_without_changing_it( + client: AsyncClient, clean_database: None, status: str, error: str +) -> None: + key = await get_signing_key_service().ensure_active_key() + await _set_key_status(key.key_id, status) + before = await _key_row(key.key_id) + + report = await gather_dependency_report() + signing_key = report["dependencies"]["signing_key"] + assert signing_key["status"] == "down", signing_key + assert signing_key["error"] == error, signing_key + assert "signing_key" in report["unhealthy"] + + ready = await client.get("/health/ready") + assert ready.status_code == 503, ready.text + assert ready.json()["checks"]["signing_key"]["error"] == error + + # A health probe never reactivates or otherwise rewrites the row. + after = await _key_row(key.key_id) + assert after.status == status + assert after.activated_at == before.activated_at + assert after.retired_at == before.retired_at + + +@pytest.mark.anyio +async def test_health_reports_a_usable_key_as_up( + client: AsyncClient, clean_database: None +) -> None: + await get_signing_key_service().ensure_active_key() + + ready = await client.get("/health/ready") + assert ready.json()["checks"]["signing_key"]["status"] == "up", ready.text + + +@pytest.fixture +def standard_mcp_enabled(monkeypatch): + from app.core.config import get_settings + + monkeypatch.setenv("ENABLE_STANDARD_MCP_ENDPOINT", "true") + get_settings.cache_clear() + yield + monkeypatch.setenv("ENABLE_STANDARD_MCP_ENDPOINT", "false") + get_settings.cache_clear() + + +@pytest.mark.anyio +async def test_standard_mcp_refuses_before_the_mint_and_the_charge( + client: AsyncClient, clean_database: None, standard_mcp_enabled, echo_tool +) -> None: + ctx = await provision_agent_wallet(client) + wallet_id = ctx["agent_wallet_id"] + key = await get_signing_key_service().ensure_active_key() + request = { + "json": { + "jsonrpc": "2.0", + "id": 7, + "method": "tools/call", + "params": {"name": TOOL_NAME, "arguments": {"message": "hello"}}, + }, + "headers": { + **ctx["agent_headers"], + "Accept": "application/json, text/event-stream", + "Content-Type": "application/json", + "Idempotency-Key": "signing-precharge-standard-1", + }, + } + debits_before = await _debits(wallet_id) + await _set_key_status(key.key_id, "disabled") + + resp = await client.post("/mcp", **request) + + assert resp.status_code == 200, resp.text + error = resp.json()["error"] + assert error["code"] == -32005, error + assert error["message"] == "signing_key_unavailable", error + assert await _debits(wallet_id) == debits_before + assert echo_tool["count"] == 0 + + await _set_key_status(key.key_id, "active") + again = await client.post("/mcp", **request) + assert again.status_code == 200, again.text + assert "error" not in again.json(), again.text + assert echo_tool["count"] == 1 From a573f969cccfdf64bfee149ee415d6490b169687 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 13:54:48 +0000 Subject: [PATCH 02/25] fix(refunds): record a pending refund even when its receipt cannot be signed The refund-failed path runs after the tool ran and the wallet was charged. create_pending wrote the failed_unrefunded receipt and the operator work item in one transaction that needed a usable signing key. A SigningKeyError there (key disabled after admission; once retired keys refuse, a retired key) escaped as internal_error and wrote neither, so the debt was recorded nowhere. create_pending now catches that, and in one transaction completes the idempotency record with the pending work item (receipt_id null, receipt_status unsigned) and a server-side unsigned_receipt marker holding the receipt inputs and the response hash. A replay returns the same pending answer. sign_unsigned_pending, run from the periodic cleanup on every replica, signs the receipt through create_pending from that marker when the replica's key can sign, turning it into an ordinary pending work item for the operator. No schema change: response_json and response_reference are already nullable. Refs #280 (PR B of three). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/main.py | 16 + gateway/app/routers/mcp.py | 27 +- gateway/app/services/refund_reconciliation.py | 266 ++++++++++++++++- gateway/docs/failure-semantics.md | 14 + .../test_refund_reconciliation_unsigned.py | 282 ++++++++++++++++++ 5 files changed, 596 insertions(+), 9 deletions(-) create mode 100644 gateway/tests/test_refund_reconciliation_unsigned.py diff --git a/gateway/app/main.py b/gateway/app/main.py index 8abe0b551..d19a31d72 100644 --- a/gateway/app/main.py +++ b/gateway/app/main.py @@ -298,6 +298,9 @@ async def periodic_cleanup(): # reserve and the receipt write (only touches idle permits). if settings.DATABASE_URL: from .services.idempotency import get_idempotency_service + from .services.refund_reconciliation import ( + get_refund_reconciliation_service, + ) from .services.mcp_dispatch_attempts import ( MAX_UPSTREAM_CALL_TIMEOUT_SECONDS, MAX_UPSTREAM_CONNECT_TIMEOUT_SECONDS, @@ -391,6 +394,19 @@ async def periodic_cleanup(): idempotency_records_needing_review=needs_review, ) + # Pending refunds recorded while this or another replica + # could not sign get their receipt from a replica that can. + ( + refund_receipts_signed, + refund_receipts_unsigned, + ) = await get_refund_reconciliation_service().sign_unsigned_pending() + if refund_receipts_signed or refund_receipts_unsigned: + logger.info( + "cleanup_completed", + refund_receipts_signed=refund_receipts_signed, + refund_receipts_still_unsigned=refund_receipts_unsigned, + ) + except asyncio.CancelledError: logger.info("cleanup_task_stopped") break diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index 1f8b67e92..8b5bf2e0b 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -3168,7 +3168,18 @@ async def _repair_pre_dispatch(exc: BaseException) -> Any: ok=False, error="refund_failed", metadata={ - "receipt_id": receipt_payload["receipt_id"], + "receipt_id": ( + receipt_payload["receipt_id"] + if receipt_payload is not None + else None + ), + # Only an unsigned receipt adds a key, so the + # signed case keeps its existing audit shape. + **( + {"receipt_status": "unsigned"} + if receipt_payload is None + else {} + ), "permit_id": permit_model.permit_id, "ledger_entry_id": charge_result.entry_id, "credits": str(credits_charged), @@ -4521,9 +4532,14 @@ async def _finalize_unrefunded_failure( response_hash_override: str | None = None, approval_id: str | None = None, counterparty: str | None = None, -) -> tuple[dict[str, Any], dict[str, Any]]: +) -> tuple[dict[str, Any] | None, dict[str, Any]]: """Persist the signed failure and its exact-once operator work item. + The receipt payload is ``None`` when the receipt could not be signed (the + signing key became unusable after the call was admitted). The work item is + recorded all the same, marked ``receipt_status: unsigned``, and a replica + whose key can sign signs the receipt later. + Both call sites reach here having already charged the caller, run the tool and failed the refund, so this is unconditionally a post-effects site -- unlike ``_finalize_governed_denial``, which serves both sides of the charge @@ -4565,6 +4581,13 @@ async def _finalize_unrefunded_failure( # losses at the other post-effects sites, and it still may not be # called retryable: the charge stands and the tool already ran. raise _receipt_contention_after_effects() from exc + if receipt is None: + logger.error( + "mcp_refund_reconciliation_receipt_unsigned ledger_entry_id=%s wallet_id=%s", + ledger_entry_id, + wallet_id, + ) + return None, reconciliation receipt_payload = _receipt_response_payload(receipt) return receipt_payload, reconciliation diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index c9291cb2f..d8a018f7e 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -6,6 +6,7 @@ from datetime import datetime, timezone from decimal import Decimal, InvalidOperation import json +import logging from typing import Any, Literal, cast from sqlalchemy import select, update as sa_update @@ -28,12 +29,45 @@ from app.schemas.trust import ReceiptResponse from app.services.permits import get_permit_service from app.services.receipts import get_receipt_service -from app.services.signing_keys import SigningKeyError, get_signing_key_service +from app.services.signing_keys import ( + SigningKeyError, + get_signing_key_service, + sha256_hex, +) + +logger = logging.getLogger(__name__) RECONCILIATION_KIND = "mcp_failed_refund" RECONCILIATION_VERSION = 1 +# Top-level key of a stored response whose failed_unrefunded receipt could not +# be signed yet. It holds the inputs a replica with a usable key needs to sign +# that receipt later (``sign_unsigned_pending``). It is never replayed to a +# caller: replay reads only named keys of the stored response. +UNSIGNED_RECEIPT_KEY = "unsigned_receipt" +UNSIGNED_RECEIPT_VERSION = 1 + + +def _unsigned_marker(record: IdempotencyRecordModel) -> dict[str, Any] | None: + """Return the unsigned-receipt marker of ``record``'s stored response.""" + if record.response_json is None: + return None + try: + payload = json.loads(record.response_json) + except (json.JSONDecodeError, TypeError): + return None + if not isinstance(payload, dict): + return None + marker = payload.get(UNSIGNED_RECEIPT_KEY) + if ( + not isinstance(marker, dict) + or marker.get("version") != UNSIGNED_RECEIPT_VERSION + or not isinstance(marker.get("inputs"), dict) + ): + return None + return marker + class RefundReconciliationError(RuntimeError): """Fail-closed reconciliation state or linkage error.""" @@ -80,7 +114,7 @@ def __init__(self) -> None: def build_pending_refund_reconciliation( *, - receipt_id: str, + receipt_id: str | None, wallet_id: str, permit_id: str, ledger_entry_id: str, @@ -164,7 +198,7 @@ async def create_pending( permit_id: str, key_id: str | None, tool_name: str, - request_payload: dict[str, Any], + request_payload: dict[str, Any] | None, ledger_entry_id: str, credits_authorized: Decimal, credits_charged: Decimal, @@ -175,8 +209,23 @@ async def create_pending( response_payload: dict[str, Any] | None = None, response_hash_override: str | None = None, counterparty: str | None = None, - ) -> tuple[ReceiptResponse, dict[str, Any]]: - """Atomically insert the signed receipt and durable pending work item.""" + request_hash: str | None = None, + _from_unsigned: bool = False, + ) -> tuple[ReceiptResponse | None, dict[str, Any]]: + """Atomically insert the signed receipt and durable pending work item. + + When the receipt cannot be signed (any ``SigningKeyError`` that is not + the one restart reason, for example a key retired or disabled after + the call was admitted), the debt is still recorded: the stored + response carries the pending work item with ``receipt_id`` ``None`` + and an ``unsigned_receipt`` marker holding everything needed to sign + the receipt later. The receipt is then ``None`` in the return value. + ``sign_unsigned_pending`` signs it from a replica whose key can sign, + through this same method with ``_from_unsigned=True``, which accepts + that marker as the checkpoint instead of an empty response. + """ + if (request_payload is None) == (request_hash is None): + raise RefundReconciliationError("refund_reconciliation_request_invalid") async def validated_checkpoint( session: AsyncSession, @@ -203,12 +252,22 @@ async def validated_checkpoint( if ( record is None or record.ledger_entry_id != ledger_entry_id - or record.response_json is not None or record.response_reference is not None ): raise RefundReconciliationError( "refund_reconciliation_checkpoint_invalid" ) + # A fresh checkpoint has no stored response yet; signing an + # unsigned pending item later starts from its marker instead. + if _from_unsigned: + if _unsigned_marker(record) is None: + raise RefundReconciliationError( + "refund_reconciliation_checkpoint_invalid" + ) + elif record.response_json is not None: + raise RefundReconciliationError( + "refund_reconciliation_checkpoint_invalid" + ) permit = await session.get(PermitModel, permit_id) if permit is None: raise RefundReconciliationError( @@ -303,6 +362,7 @@ def finalize_record( key_id=key_id, tool=tool_name, request_payload=request_payload, + request_hash=request_hash, response_payload=response_payload or {"error": reason}, ledger_entry_id=ledger_entry_id, credits_authorized=credits_authorized, @@ -352,12 +412,204 @@ def retired_under_the_attempt(exc: BaseException) -> bool: "signing_key_not_active" ) + try: + return await run_with_write_conflict_retry( + attempt, + on_exhausted=lambda exc: RefundReconciliationContendedError(), + restart_on=retired_under_the_attempt, + ) + except SigningKeyError as exc: + if _from_unsigned: + # Signing later on a replica that still cannot sign: leave the + # unsigned item in place for the next pass. + raise + effective_payload = response_payload or {"error": reason} + inputs: dict[str, Any] = { + "wallet_id": wallet_id, + "endpoint": endpoint, + "idempotency_key": idempotency_key, + "permit_id": permit_id, + "key_id": key_id, + "tool_name": tool_name, + "request_hash": ( + request_hash + if request_hash is not None + else sha256_hex(cast(dict[str, Any], request_payload)) + ), + "ledger_entry_id": ledger_entry_id, + "credits_authorized": str(credits_authorized), + "credits_charged": str(credits_charged), + "audit_event_id": audit_event_id, + "reason": reason, + "dispatch_attempt_id": dispatch_attempt_id, + "approval_id": approval_id, + "response_payload": effective_payload, + "response_hash_override": response_hash_override, + "counterparty": counterparty, + } + reconciliation = await self._record_unsigned_pending( + validated_checkpoint=validated_checkpoint, + inputs=inputs, + response_hash=sha256_hex(effective_payload), + signing_error=str(exc), + ) + return None, reconciliation + + async def _record_unsigned_pending( + self, + *, + validated_checkpoint: Any, + inputs: dict[str, Any], + response_hash: str, + signing_error: str, + ) -> dict[str, Any]: + """Store the pending refund without a receipt, in one transaction. + + The work item names no receipt yet (``receipt_id`` ``None``) and the + marker beside it keeps the receipt inputs. ``response_hash`` is the hash + of the response payload as it was handed in, so signing later can + refuse a payload the JSON round trip changed instead of signing a + different hash. The record is completed with status 500, so a replay + of the same key returns the same pending answer and never runs the + tool again. + """ + factory = get_session_factory() + + async def attempt() -> dict[str, Any]: + async with factory() as session: + async with session.begin(): + record = await validated_checkpoint(session, lock=True) + reconciliation = build_pending_refund_reconciliation( + receipt_id=None, + wallet_id=inputs["wallet_id"], + permit_id=inputs["permit_id"], + ledger_entry_id=inputs["ledger_entry_id"], + credits=Decimal(inputs["credits_charged"]), + ) + reconciliation["receipt_status"] = "unsigned" + record.response_json = json.dumps( + { + "content": [], + "isError": True, + "error": inputs["reason"], + "receipt": None, + "refund_reconciliation": reconciliation, + UNSIGNED_RECEIPT_KEY: { + "version": UNSIGNED_RECEIPT_VERSION, + "signing_error": signing_error, + "recorded_at": utc_now().isoformat(), + "response_hash": response_hash, + "inputs": inputs, + }, + }, + default=str, + ) + record.status_code = 500 + session.add(record) + await session.flush() + return reconciliation + return await run_with_write_conflict_retry( attempt, on_exhausted=lambda exc: RefundReconciliationContendedError(), - restart_on=retired_under_the_attempt, ) + async def sign_unsigned_pending(self, *, limit: int = 50) -> tuple[int, int]: + """Sign the receipts of pending refunds recorded without one. + + Runs from the periodic cleanup on every replica. A replica whose key + cannot sign leaves each item as it is; one whose key can sign writes + the ``failed_unrefunded`` receipt and turns the item into an ordinary + pending work item (the same shape ``create_pending`` writes when it + can sign), which the operator list and ``retry`` then see. Concurrent + signers are safe: the checkpoint is re-read under a row lock and the + second signer finds it already signed. + + Returns ``(signed, still_unsigned)``. + """ + factory = get_session_factory() + async with factory() as session: + records = ( + ( + await session.execute( + select(IdempotencyRecordModel) + .where( + cast( + ColumnElement[bool], + cast( + Any, IdempotencyRecordModel.response_reference + ).is_(None), + ), + cast( + ColumnElement[bool], + cast( + Any, IdempotencyRecordModel.response_json + ).contains(f'"{UNSIGNED_RECEIPT_KEY}"'), + ), + ) + .order_by( + cast(ColumnElement[Any], IdempotencyRecordModel.created_at) + ) + .limit(limit) + ) + ) + .scalars() + .all() + ) + signed = 0 + still_unsigned = 0 + for record in records: + marker = _unsigned_marker(record) + if marker is None: + continue + inputs = dict(marker["inputs"]) + if sha256_hex(inputs["response_payload"]) != marker.get("response_hash"): + # The stored payload no longer hashes to what the caller's + # response was; signing it would sign a different response. + logger.error( + "refund_reconciliation_unsigned_payload_mismatch", + extra={"record_id": record.record_id}, + ) + still_unsigned += 1 + continue + try: + await self.create_pending( + wallet_id=inputs["wallet_id"], + endpoint=inputs["endpoint"], + idempotency_key=inputs["idempotency_key"], + permit_id=inputs["permit_id"], + key_id=inputs["key_id"], + tool_name=inputs["tool_name"], + request_payload=None, + request_hash=inputs["request_hash"], + ledger_entry_id=inputs["ledger_entry_id"], + credits_authorized=Decimal(inputs["credits_authorized"]), + credits_charged=Decimal(inputs["credits_charged"]), + audit_event_id=inputs["audit_event_id"], + reason=inputs["reason"], + dispatch_attempt_id=inputs["dispatch_attempt_id"], + approval_id=inputs["approval_id"], + response_payload=inputs["response_payload"], + response_hash_override=inputs["response_hash_override"], + counterparty=inputs["counterparty"], + _from_unsigned=True, + ) + except SigningKeyError: + still_unsigned += 1 + continue + except (RefundReconciliationError, RefundReconciliationContendedError): + # Signed concurrently by another replica, or contended: the + # next pass reads it again. + logger.info( + "refund_reconciliation_unsigned_skipped", + extra={"record_id": record.record_id}, + exc_info=True, + ) + still_unsigned += 1 + continue + signed += 1 + return signed, still_unsigned + @staticmethod def _decode_response(record: IdempotencyRecordModel) -> dict[str, Any]: try: diff --git a/gateway/docs/failure-semantics.md b/gateway/docs/failure-semantics.md index 4b94f9221..4e9319e0f 100644 --- a/gateway/docs/failure-semantics.md +++ b/gateway/docs/failure-semantics.md @@ -368,6 +368,20 @@ ack was lost is recognized rather than duplicated `resolved` claim without the matching ledger row fails closed on every read and replay (`test_forged_resolved_reconciliation_without_refund_fails_closed`). +If the receipt cannot be signed at that moment (the signing key became +unusable after the call was admitted, for example it was disabled), the work +item is still recorded, without a receipt: the caller gets the same 500 / +`-32603` answer with `refund_reconciliation.status` `pending`, `receipt_id` +`null` and `receipt_status` `unsigned`, and a replay of the same key returns +the same answer without running the tool. The stored record keeps the receipt +inputs server side. The periodic cleanup on every replica runs +`RefundReconciliationService.sign_unsigned_pending`: a replica whose key can +sign writes the `failed_unrefunded` receipt and turns the item into an +ordinary pending work item, which the operator list and retry then see; a +replica that cannot sign leaves it for the next pass. Until it is signed the +item does not appear in the operator list +(`tests/test_refund_reconciliation_unsigned.py`). + ## What this deliberately does not claim 1. **Post-dispatch ambiguity is never resolved automatically.** No retry, no diff --git a/gateway/tests/test_refund_reconciliation_unsigned.py b/gateway/tests/test_refund_reconciliation_unsigned.py new file mode 100644 index 000000000..79d1a3a13 --- /dev/null +++ b/gateway/tests/test_refund_reconciliation_unsigned.py @@ -0,0 +1,282 @@ +"""A pending refund is recorded even when its receipt cannot be signed yet. + +The refund-failed path runs after the tool ran and the wallet was charged. Its +``failed_unrefunded`` receipt and the operator work item used to be written in +one transaction that needed a usable signing key. If the key became unusable +after the call was admitted (disabled, or retired once a retired key refuses +to sign), ``create_pending`` raised a ``SigningKeyError`` that nothing +classified: the caller got ``internal_error`` and neither the receipt nor the +work item was written, so the debt was recorded nowhere (issue #280). + +``create_pending`` now records the work item without a receipt in that case, +with an ``unsigned_receipt`` marker holding the receipt inputs, and +``sign_unsigned_pending`` signs the receipt from a replica whose key can sign. +These tests pin both halves and that the item then flows through the normal +operator path. +""" + +from __future__ import annotations + +from decimal import Decimal +import json +from typing import Any +from unittest.mock import patch + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import func, select + +from app.db.database import get_session_factory +from app.db.models import ( + IdempotencyRecordModel, + LedgerEntryModel, + ReceiptModel, + SigningKeyModel, +) +from app.main import app +from app.routers.mcp import INTERNAL_ERROR_MESSAGE +from app.schemas.billing import ServiceCategory +from app.services.refund_reconciliation import ( + UNSIGNED_RECEIPT_KEY, + get_refund_reconciliation_service, +) +from app.services.service_registry import get_service_registry +from app.services.signing_keys import get_signing_key_service +from tests.test_trust_helpers import create_tool_permit, provision_agent_wallet + +TOOL_COST = 2.0 +TOOL_NAME = "refund-unsigned-tool" + + +@pytest.fixture +async def client() -> AsyncClient: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as value: + yield value + + +async def _set_key_status(key_id: str, status: str) -> None: + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key_id) + assert row is not None + row.status = status + session.add(row) + await session.commit() + + +@pytest.fixture +def key_lost_mid_call_tool(): + """A tool that, while it runs, loses this replica its signing key. + + It stands in for an operator disabling (or, once retired keys refuse, + retiring) the key after the call was admitted and charged. Then the tool + fails, so the call goes down the refund path with no usable key. + """ + state: dict[str, Any] = {"runs": 0, "key_id": None} + + async def run() -> dict[str, Any]: + state["runs"] += 1 + await _set_key_status(state["key_id"], "disabled") + raise RuntimeError("tool exploded") + + get_service_registry().register_local( + service_id=TOOL_NAME, + name="Refund unsigned tool", + description="Pending refund without a signable receipt test tool", + category=ServiceCategory.AGENT_COMMS, + func=run, + credits_per_unit=TOOL_COST, + unit_name="call", + ) + try: + yield state + finally: + get_service_registry().unregister_local(TOOL_NAME) + + +async def _failing_refund(self, **_kwargs): # noqa: ANN001 + raise RuntimeError("refund down") + + +async def _record_for(key: str) -> IdempotencyRecordModel: + async with get_session_factory()() as session: + record = ( + await session.execute( + select(IdempotencyRecordModel).where( + IdempotencyRecordModel.idempotency_key == key + ) + ) + ).scalar_one() + return record + + +async def _count(model: Any) -> int: + async with get_session_factory()() as session: + return int(await session.scalar(select(func.count()).select_from(model)) or 0) + + +async def _run_call_that_loses_its_key( + client: AsyncClient, state: dict[str, Any], *, key: str +) -> dict[str, Any]: + ctx = await provision_agent_wallet(client) + permit = await create_tool_permit( + client, + wallet_id=ctx["agent_wallet_id"], + key_id=ctx["key_id"], + tool_name=TOOL_NAME, + max_credits=10, + idem_key=f"{key}-permit", + ) + signing_key = await get_signing_key_service().ensure_active_key() + state["key_id"] = signing_key.key_id + body = { + "jsonrpc": "2.0", + "id": f"call-{key}", + "method": "tools/call", + "params": { + "name": TOOL_NAME, + "arguments": {}, + "mcpContext": { + "wallet_id": ctx["agent_wallet_id"], + "permit_id": permit["permit_id"], + "idempotency_key": key, + }, + }, + } + with patch("app.services.agent_money.AgentMoney.refund_charge", _failing_refund): + resp = await client.post( + "/mcp/messages", json=body, headers=ctx["agent_headers"] + ) + return {"ctx": ctx, "permit": permit, "body": body, "resp": resp} + + +@pytest.mark.anyio +async def test_a_refund_whose_receipt_cannot_be_signed_is_still_recorded( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + receipts_before = await _count(ReceiptModel) + case = await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-1" + ) + resp = case["resp"] + + assert key_lost_mid_call_tool["runs"] == 1 + assert resp.status_code == 200, resp.text + error = resp.json()["error"] + # Not the unclassified answer: the reason and the debt are on the wire. + assert error["message"] != INTERNAL_ERROR_MESSAGE, error + reconciliation = error["data"]["refund_reconciliation"] + assert reconciliation["status"] == "pending", reconciliation + assert reconciliation["receipt_id"] is None, reconciliation + assert reconciliation["receipt_status"] == "unsigned", reconciliation + assert Decimal(reconciliation["credits"]) == Decimal("2") + # Internal receipt inputs never reach the caller. + assert UNSIGNED_RECEIPT_KEY not in json.dumps(resp.json()) + + # The debt is durable: the record is completed with the work item and the + # marker, and no receipt was written. + assert await _count(ReceiptModel) == receipts_before + record = await _record_for("refund-unsigned-1") + assert record.response_reference is None + assert record.status_code == 500 + stored = json.loads(record.response_json or "{}") + assert stored["refund_reconciliation"]["status"] == "pending" + marker = stored[UNSIGNED_RECEIPT_KEY] + assert marker["signing_error"] == "signing_key_disabled" + assert marker["inputs"]["ledger_entry_id"] == record.ledger_entry_id + + # The same key replays the same pending answer and never runs the tool. + # (The key is usable again first: a disabled key also fails the permit's + # signature check, which runs before the replay is served.) + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + with patch("app.services.agent_money.AgentMoney.refund_charge", _failing_refund): + replay = await client.post( + "/mcp/messages", json=case["body"], headers=case["ctx"]["agent_headers"] + ) + assert key_lost_mid_call_tool["runs"] == 1 + replayed = replay.json()["error"]["data"]["refund_reconciliation"] + assert replayed["status"] == "pending" + assert replayed["receipt_id"] is None + + +@pytest.mark.anyio +async def test_a_replica_that_cannot_sign_leaves_the_item_unsigned( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-2" + ) + service = get_refund_reconciliation_service() + + signed, still_unsigned = await service.sign_unsigned_pending() + + assert (signed, still_unsigned) == (0, 1) + record = await _record_for("refund-unsigned-2") + assert record.response_reference is None + assert UNSIGNED_RECEIPT_KEY in json.loads(record.response_json or "{}") + + +@pytest.mark.anyio +async def test_a_replica_that_can_sign_completes_the_item_and_it_can_be_refunded( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + case = await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-3" + ) + wallet_id = case["ctx"]["agent_wallet_id"] + service = get_refund_reconciliation_service() + # The key is usable again (for example the replica was redeployed). + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + + signed, still_unsigned = await service.sign_unsigned_pending() + assert (signed, still_unsigned) == (1, 0) + + record = await _record_for("refund-unsigned-3") + assert record.response_reference is not None + stored = json.loads(record.response_json or "{}") + assert UNSIGNED_RECEIPT_KEY not in stored + assert stored["receipt"]["outcome"] == "failed_unrefunded" + assert stored["refund_reconciliation"]["receipt_id"] == record.response_reference + + async with get_session_factory()() as session: + receipt = await session.get(ReceiptModel, record.response_reference) + assert receipt is not None + assert receipt.outcome == "failed_unrefunded" + assert receipt.ledger_entry_id == record.ledger_entry_id + assert receipt.idempotency_record_id == record.record_id + assert receipt.credits_charged == Decimal("2") + + # A second pass finds nothing left to sign. + assert await service.sign_unsigned_pending() == (0, 0) + + # The signed item is now an ordinary pending work item for the operator. + items, _total = await service.list_items(status="pending", wallet_id=wallet_id) + assert [item.receipt_id for item in items] == [record.response_reference] + assert await get_receipt_service_verifies(record.response_reference) + + # And the operator retry refunds it exactly once. + item, already = await service.retry(record.response_reference) + assert item.status == "resolved" + assert already is False + async with get_session_factory()() as session: + refunds = int( + await session.scalar( + select(func.count()) + .select_from(LedgerEntryModel) + .where( + LedgerEntryModel.wallet_id == wallet_id, + LedgerEntryModel.action == "refund", + ) + ) + or 0 + ) + assert refunds == 1 + + +async def get_receipt_service_verifies(receipt_id: str) -> bool: + from app.services.receipts import get_receipt_service + + async with get_session_factory()() as session: + receipt = await session.get(ReceiptModel, receipt_id) + assert receipt is not None + return await get_receipt_service().verify_model(receipt, session=session) From c7abc3d8561f63b09a25045efb089b64ca0ce379 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 14:05:46 +0000 Subject: [PATCH 03/25] fix(trust): a retired signing key refuses to sign instead of reactivating ensure_active_key used to set a retired row for the process's configured key id back to active (activated_at reset, retired_at cleared) and sign, so any replica or restart still on the old id silently reversed a rotation. The spec says a retired key no longer signs new objects. ensure_active_key now never rewrites an existing row: an active key signs, a retired one (or an active row with retired_at set) refuses with signing_key_retired, disabled keeps signing_key_disabled, an unknown status refuses with signing_key_status_invalid. A key id with no row still bootstraps. rotate_active_key_metadata is unchanged and stays the only way a row becomes active again. This relies on #329 (refuse before the charge) and #330 (record a pending refund without a signed receipt), which this branch merges. The refund contention tests that pinned reactivation now assert the new behavior: the pending refund is recorded unsigned and signed after a redeploy with the new key; the exhaustion test uses real rotations to fresh key ids. Closes #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/services/signing_keys.py | 58 +++-- gateway/docs/key-management.md | 85 ++++---- ...efund_reconciliation_contention_surface.py | 205 ++++++++++++------ gateway/tests/test_signing_key_lifecycle.py | 141 ++++++++++++ gateway/tests/test_signing_key_precharge.py | 36 +++ 5 files changed, 392 insertions(+), 133 deletions(-) diff --git a/gateway/app/services/signing_keys.py b/gateway/app/services/signing_keys.py index 85c667cfc..0c9a697d5 100644 --- a/gateway/app/services/signing_keys.py +++ b/gateway/app/services/signing_keys.py @@ -293,6 +293,31 @@ def _assert_key_not_disabled(key: SigningKeyModel) -> None: if key.status == "disabled": raise SigningKeyError("signing_key_disabled") + @staticmethod + def _assert_configured_key_can_sign(key: SigningKeyModel) -> None: + """Refuse a configured key that may no longer sign new objects. + + ``disabled`` is terminal for signing and verification. ``retired`` + means the key stopped signing new objects at a rotation + (``spec/key-set-v0.1.md``); its row stays published so older + signatures keep verifying. Neither is ever flipped back to ``active`` + by a signer: a replica still configured with a retired key id refuses + with ``signing_key_retired`` until it is redeployed with the new key id + and key material. Only ``rotate_active_key_metadata`` reactivates a + row, and only the explicit target of a rotation. + """ + + SigningKeyService._assert_key_not_disabled(key) + if key.status == "retired" or ( + key.status == "active" and key.retired_at is not None + ): + raise SigningKeyError("signing_key_retired") + if key.status != "active": + # Not "signing_key_not_active": that reason is the refund path's + # restart signal for a rotation landing mid-attempt, and an unknown + # status would only repeat on every restart. + raise SigningKeyError("signing_key_status_invalid") + async def ensure_active_key(self) -> SigningKeyModel: factory = get_session_factory() public_key_b64 = self._public_key_b64() @@ -303,26 +328,21 @@ async def ensure_active_key(self) -> SigningKeyModel: ) ) key = result.scalar_one_or_none() - # Read-mostly fast path: when the active key already matches, do no - # write. This keeps the common (per-signature) call free of write - # contention and the first-time insert race below. + # An existing row is only ever read here, never rewritten: an + # active key signs with no write, and a retired, disabled or + # mismatched one refuses. Only a key id with no row yet is + # inserted, as active (the first-time bootstrap below). if key: self._assert_public_key_mapping(key, public_key_b64) - self._assert_key_not_disabled(key) - if key.status == "active" and key.retired_at is None: - return key - key.status = "active" - key.activated_at = utc_now() - key.retired_at = None - session.add(key) - else: - key = SigningKeyModel( - key_id=self._key_id, - public_key_b64=public_key_b64, - status="active", - activated_at=utc_now(), - ) - session.add(key) + self._assert_configured_key_can_sign(key) + return key + key = SigningKeyModel( + key_id=self._key_id, + public_key_b64=public_key_b64, + status="active", + activated_at=utc_now(), + ) + session.add(key) try: await session.commit() except IntegrityError: @@ -339,7 +359,7 @@ async def ensure_active_key(self) -> SigningKeyModel: ) ).scalar_one() self._assert_public_key_mapping(key, public_key_b64) - self._assert_key_not_disabled(key) + self._assert_configured_key_can_sign(key) return key async def assert_ready_to_sign(self) -> None: diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index 2d79c52b6..91f096025 100644 --- a/gateway/docs/key-management.md +++ b/gateway/docs/key-management.md @@ -130,8 +130,8 @@ This is the property that closes the gap in `SECURITY_LIMITATIONS.md` between > the only signing-key routes today are the read-only > `GET /v1/signing-keys/active` and `GET /v1/signing-keys/{key_id}` > (`app/routers/keys.py`). For what rotation means now, see [Status](#status). -> This design also assumes a retired row stays retired. That is not true of -> the code today: see [Retirement is not durable today](#retirement-is-not-durable-today). +> A retired row stays retired: a signer never reactivates it. See +> [Retired keys refuse to sign](#retired-keys-refuse-to-sign). Rotation under KMS is metadata + key-version change, not a redeploy: @@ -196,10 +196,10 @@ Until the KMS integration ships, the production posture is: `retire_key_metadata` and `rotate_active_key_metadata` are service methods only, and no `POST /v1/admin/signing-keys/rotate` route exists. The post-rotation steps are in the hosted-service deploy runbook (not in this repository). -- Retirement is not durable while any replica still runs the old key id. Use - the rollout order in the next section. +- A replica still configured with a retired key id refuses to sign. Use the + rollout order in the next section so that no replica is left on it. -### Retirement is not durable today +### Retired keys refuse to sign What the code does, checked against `app/services/signing_keys.py`: @@ -209,26 +209,31 @@ What the code does, checked against `app/services/signing_keys.py`: - `ensure_active_key` runs before receipt, audit event, permit and quote signing. It is also reached without any signing: trust-mode startup calls it (`app/main.py`), and `GET /v1/signing-keys/active` calls it through - `get_active_key` (`app/routers/keys.py`). When the row for the process's configured `TRUST_SIGNING_KEY_ID` - is `retired`, it sets the row back to `active`, resets `activated_at` and - clears `retired_at`, then signs. Only `disabled` is terminal: that row - refuses with `signing_key_disabled`. -- The prepared-key path does not reactivate. `validate_prepared_signing_key` + `get_active_key` (`app/routers/keys.py`). It never rewrites an existing row. + When the row for the process's configured `TRUST_SIGNING_KEY_ID` is + `retired` (or `active` with `retired_at` set) it refuses with + `signing_key_retired`; a `disabled` row refuses with `signing_key_disabled`. + A key id with no row yet is inserted as `active` (first bootstrap). This is + what the spec wording (`spec/key-set-v0.1.md`) means by a retired key no + longer signing new objects. +- The prepared-key path refuses the same keys. `validate_prepared_signing_key` (used when a caller signs under a key it resolved earlier, such as the receipt write in the pending-refund path) refuses a key that is not `active` or has `retired_at` set, with `signing_key_not_active`. That is the existing behavior when a rotation lands in the middle of a call. -- So a replica that still runs the old key id and key material silently - un-retires the old row when it starts in trust mode, when it answers a - request to `GET /v1/signing-keys/active`, or when it signs anything. - Retirement holds only while no process configured with the old id does any - of these, even an idle one. The spec wording - (`spec/key-set-v0.1.md`) says a retired key no longer signs new objects; the - runtime does not enforce that. -- `rotate_active_key_metadata` changes the configured id only on the instance - that calls it. Other replicas keep their startup id. - -Rollout order that avoids the problem: +- `rotate_active_key_metadata` is the only call that sets a row `active` + again, and only the explicit target of a rotation. It changes the + configured id only on the instance that calls it; other replicas keep their + startup id. + +Operator impact: after a rotation, every replica must be redeployed with the +new `TRUST_SIGNING_KEY_ID` and the matching new +`TRUST_SIGNING_PRIVATE_KEY_B64`. A replica left on the old id refuses to sign +with `signing_key_retired`: in trust mode it fails at startup +(`trust_signing_key_failed`), and if it was already running it reports not +ready and refuses governed calls, as described below. + +Rollout order: 1. Deploy every replica with the new `TRUST_SIGNING_KEY_ID` and the matching new `TRUST_SIGNING_PRIVATE_KEY_B64`. The new row is created `active` at @@ -238,10 +243,8 @@ Rollout order that avoids the problem: 2. Confirm no replica or scheduled job still runs the old id. 3. Only then retire the old row with `retire_key_metadata`. It is a manual service call; no route calls it. -4. Check `GET /.well-known/trust-keys.json`: the old `kid` should show - `retired` and the new `kid` `active`. Check again after normal traffic, since - a stale replica un-retires the old row on its next restart, signature or - `GET /v1/signing-keys/active` request. +4. Check `GET /.well-known/trust-keys.json`: the old `kid` shows `retired` and + the new `kid` `active`. How an operator can tell a replica is stale: @@ -251,32 +254,24 @@ How an operator can tell a replica is stale: `signing_key_retired`, `signing_key_disabled` or `signing_key_id_public_key_mismatch`, and readiness answers 503. A load balancer that gates on readiness stops sending traffic to that replica. -- Until a retired key refuses to sign, the window is short: the next request - that reaches the stale replica reactivates the row, and health reports `up` - again. The reactivation itself writes no log line and returns no error. -- The published key set shows it too: the old `kid` flips from `retired` back - to `active`. +- Its governed calls are refused with `signing_key_unavailable`, and the + server log carries the underlying reason. What a governed call does when the key cannot sign: the governed MCP transports (`/mcp/messages`, `/mcp/tools/{tool}/invoke` and `/mcp`) and the AWI HTTP routes run `SigningKeyService.assert_ready_to_sign` before they -reserve budget or charge. If the configured key is disabled, bound to other -key material, or otherwise cannot sign, the call is refused with +reserve budget or charge. If the configured key is retired, disabled, bound to +other key material, or otherwise cannot sign, the call is refused with `signing_key_unavailable` (JSON-RPC `-32005`, HTTP 409 on the REST invoke route, HTTP 503 on the AWI routes) and nothing is recorded, so the caller can -retry the same idempotency key on a replica whose key can sign. A rotation -that lands after that check and before the call finishes is not covered by -it. - -Why a retired key still signs: making a retired key refuse to sign -(`signing_key_retired`) would stop the reactivation, but the pending-refund -path relies on it. `RefundReconciliationService.create_pending` resolves the -signing key per attempt and restarts after a concurrent rotation, and the -restart currently succeeds because `ensure_active_key` reactivates the key. A -refusal there would escape as an internal error and lose both the receipt and -the refund work item for a charge that already happened. That path has to -record the refund without a signed receipt first. The plan and its status are -in [issue 280](https://github.com/agentmiddleware/agent-middleware/issues/280). +retry the same idempotency key on a replica whose key can sign. + +A rotation that lands after that check and before the call finishes is +handled on the refund-failed path: if the `failed_unrefunded` receipt cannot be +signed, the pending refund is recorded without a receipt and a replica whose +key can sign signs it later (see "Refunds are written at most once" in +[failure semantics](failure-semantics.md)). The analysis is in +[issue 280](https://github.com/agentmiddleware/agent-middleware/issues/280). This is documented as a known limitation in `SECURITY_LIMITATIONS.md` and should be the default answer to "where do the private keys live?" until the diff --git a/gateway/tests/test_refund_reconciliation_contention_surface.py b/gateway/tests/test_refund_reconciliation_contention_surface.py index 8d176d2b6..b4760d4d5 100644 --- a/gateway/tests/test_refund_reconciliation_contention_surface.py +++ b/gateway/tests/test_refund_reconciliation_contention_surface.py @@ -45,6 +45,7 @@ from unittest.mock import patch import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from httpx import ASGITransport, AsyncClient from sqlalchemy import func, select from sqlalchemy.exc import OperationalError @@ -65,9 +66,13 @@ ) from app.schemas.billing import ServiceCategory from app.services import refund_reconciliation as reconciliation_module -from app.services.refund_reconciliation import RefundReconciliationContendedError +from app.services.refund_reconciliation import ( + RefundReconciliationContendedError, + get_refund_reconciliation_service, +) from app.services.receipts import ReceiptWriteContendedError from app.services.service_registry import get_service_registry +from app.services.signing_keys import get_signing_key_service from tests.test_trust_helpers import create_tool_permit, provision_agent_wallet TOOL_COST = 2.0 @@ -123,9 +128,12 @@ async def _retire_active_keys() -> int: """Retire every published signing key, as a concurrent rotation would. Written directly rather than through ``rotate_active_key_metadata`` so the - process-wide service keeps its key id: ``ensure_active_key`` then finds its - own key retired and re-activates it, which is the restart's job to do and - what the tests below watch for. Nothing restores the table afterwards -- + process-wide service keeps its key id: it is then a replica left on a + retired key, and ``ensure_active_key`` refuses it with + ``signing_key_retired`` instead of re-activating it (issue #280). What the + tests below watch for is that the pending refund is still recorded, without + a receipt, and signed once the key is restored. Nothing restores the table + afterwards -- ``clean_database`` deletes ``signing_keys`` at the start of every test that asks for it, so a retired key never outlives the test that retired it. """ @@ -156,11 +164,16 @@ class _KeyRetiredAfterResolution: """ def __init__( - self, real: Any, state: dict[str, int], retirements: int | None + self, + real: Any, + state: dict[str, int], + retirements: int | None, + rotate: bool = False, ) -> None: self._real = real self._state = state self._retirements = retirements + self._rotate = rotate def __getattr__(self, name: str) -> Any: return getattr(self._real, name) @@ -169,20 +182,34 @@ async def ensure_active_key(self) -> Any: key = await self._real.ensure_active_key() self._state["resolved"] += 1 if self._retirements is None or self._state["retired"] < self._retirements: - self._state["retired"] += await _retire_active_keys() + if self._rotate: + # A real rotation to a fresh key id: the resolved key is + # retired and the process signs under the new id from the next + # resolution on, as the replica that rotated would. + await self._real.rotate_active_key_metadata( + f"{key.key_id}-rotated-{self._state['resolved']}" + ) + self._state["retired"] += 1 + else: + self._state["retired"] += await _retire_active_keys() return key def _retire_key_after_resolution( - monkeypatch, *, retirements: int | None + monkeypatch, *, retirements: int | None, rotate: bool = False ) -> dict[str, int]: """Retire the signing key inside ``create_pending``'s attempt, after resolution.""" real_get_signing_key_service = reconciliation_module.get_signing_key_service state = {"resolved": 0, "retired": 0} + # A rotation moves the process-wide service to a new key id; put it back + # when the test ends so later tests sign under the key they expect. + real_service = real_get_signing_key_service() + real_service._public_key_b64() # settle an ephemeral key's own id first + monkeypatch.setattr(real_service, "_key_id", real_service._key_id) def patched_get_signing_key_service(): return _KeyRetiredAfterResolution( - real_get_signing_key_service(), state, retirements + real_get_signing_key_service(), state, retirements, rotate ) monkeypatch.setattr( @@ -328,6 +355,46 @@ async def _count_receipts() -> int: ) +def _redeploy_with_new_key(monkeypatch) -> str: + """Give the process-wide signing service a new key id and key material. + + This is what restoring a replica left on a retired key looks like: it is + redeployed with the key the rotation moved to. The monkeypatch puts the + old identity back when the test ends. + """ + service = get_signing_key_service() + service._public_key_b64() + new_key_id = f"{service._key_id}-redeployed" + monkeypatch.setattr(service, "_private_key", Ed25519PrivateKey.generate()) + monkeypatch.setattr(service, "_key_id", new_key_id) + return new_key_id + + +async def _assert_unsigned_pending(resp: Any) -> None: + """The caller is told the debt is pending, with no receipt yet.""" + assert resp.status_code == 200, resp.text + error = resp.json()["error"] + # Not the unclassified answer, and not a stale-key reason on the wire. + assert error["message"] != INTERNAL_ERROR_MESSAGE, error + assert "signing_key" not in str(error), error + assert "receipt" not in error["data"] or not error["data"]["receipt"], error + reconciliation = error["data"]["refund_reconciliation"] + assert reconciliation["status"] == "pending", reconciliation + assert reconciliation["receipt_id"] is None, reconciliation + assert reconciliation["receipt_status"] == "unsigned", reconciliation + + +async def _sign_after_redeploy(monkeypatch) -> tuple[str, list[dict[str, Any]]]: + """Redeploy with the new key, run the signer, and return the signed items.""" + new_key_id = _redeploy_with_new_key(monkeypatch) + ( + signed, + still_unsigned, + ) = await get_refund_reconciliation_service().sign_unsigned_pending() + assert (signed, still_unsigned) == (1, 0) + return new_key_id, await _work_items() + + async def _work_items() -> list[dict[str, Any]]: """Every durable pending-refund work item currently recorded.""" async with get_session_factory()() as session: @@ -405,19 +472,19 @@ async def test_a_contended_pending_refund_is_restarted_until_it_lands( @pytest.mark.anyio -async def test_a_key_retired_between_attempts_does_not_strand_the_restart( +async def test_a_key_retired_between_attempts_records_the_refund_unsigned( client: AsyncClient, clean_database: None, exploding_tool ) -> None: - """The restart resolves the active signing key per attempt, not once. + """A key retired between attempts no longer comes back, and no debt is lost. - A key resolved before the loop can retire during it. ``create_receipt`` - revalidates a prepared key under a row lock and rejects a retired one with - ``signing_key_not_active`` -- a ``SigningKeyError``, which is not an - ``OperationalError``. So a stale key would not be retried by - ``run_with_write_conflict_retry``, would never reach ``on_exhausted``, and - would arrive at routers that have no handler for it: the unclassified - ``internal_error``, with the receipt and the work item both lost, which is - the exact failure this module exists to remove. + This test used to pin the opposite: the restart's next resolution found + the process's own key retired and quietly re-activated it, so the refund + record landed signed under a key the operator had retired. A retired key + now refuses (``signing_key_retired``, issue #280), so the restart cannot + sign. What it must still never do is lose the debt or answer + ``internal_error``: the pending work item is recorded without a receipt, + and once the replica is redeployed with the new key the receipt is signed + under that key while the old one stays retired. Rotation is forced between attempts rather than raced, so the ordering is the test's rather than the scheduler's: the key is retired at the moment @@ -431,6 +498,7 @@ async def test_a_key_retired_between_attempts_does_not_strand_the_restart( permit_id=case["permit"]["permit_id"], idempotency_key="refund-contention-rotate", ) + old_key_id = (await get_signing_key_service().ensure_active_key()).key_id with pytest.MonkeyPatch.context() as monkeypatch: state = _lose_reconciliation_commits( @@ -445,49 +513,48 @@ async def test_a_key_retired_between_attempts_does_not_strand_the_restart( # The rotation actually happened, so the assertions below are load-bearing. assert state["retired"] >= 1, state - assert state["commits"] == 2, state + await _assert_unsigned_pending(resp) + assert await _count_receipts() == 0 + items = await _work_items() + assert len(items) == 1, items + assert items[0]["status"] == "pending", items[0] + assert runs["count"] == 1 - assert resp.status_code == 200, resp.text - error = resp.json()["error"] - # A recorded pending refund and an unclassified failure share the -32603 - # code, so the code alone cannot tell them apart. What separates them is - # that this one names the real reason and carries the evidence, where the - # stale-key failure would have answered an opaque internal_error with a - # bare correlation id and nothing written. - assert error["message"] != INTERNAL_ERROR_MESSAGE, error - assert "signing_key_not_active" not in str(error), error - data = error["data"] - assert data["receipt"]["outcome"] == "failed_unrefunded", data - assert data["refund_reconciliation"]["status"] == "pending", data + async with get_session_factory()() as session: + old_key = await session.get(SigningKeyModel, old_key_id) + assert old_key is not None + assert old_key.status == "retired" + + with pytest.MonkeyPatch.context() as monkeypatch: + new_key_id, items = await _sign_after_redeploy(monkeypatch) - # The debt is recorded exactly once, signed under a key that was active - # when the attempt that landed ran. assert await _count_receipts() == 1 - items = await _work_items() assert len(items) == 1, items assert items[0]["status"] == "pending", items[0] - assert runs["count"] == 1 + async with get_session_factory()() as session: + receipt = await session.get(ReceiptModel, items[0]["receipt_id"]) + assert receipt is not None + assert receipt.outcome == "failed_unrefunded" + assert receipt.signature_key_id == new_key_id + old_key = await session.get(SigningKeyModel, old_key_id) + assert old_key is not None + assert old_key.status == "retired" @pytest.mark.anyio -async def test_a_key_retired_inside_an_attempt_restarts_it( +async def test_a_key_retired_inside_an_attempt_records_the_refund_unsigned( client: AsyncClient, clean_database: None, exploding_tool ) -> None: - """A rotation landing mid-attempt is a restart, not an internal error. - - The test above stages the rotation between attempts, where resolving the - key per attempt is enough. This one stages it inside an attempt: after - ``ensure_active_key`` has handed back an active key and before - ``create_receipt`` locks that key's row. The lock finds it retired and - rejects it with ``signing_key_not_active`` -- a ``SigningKeyError``, not an - ``OperationalError``, so on its own ``run_with_write_conflict_retry`` let - it straight through, past ``on_exhausted``, into the router's unclassified - branch. The caller got ``internal_error`` with nothing written: the tool - had run, the money was owed, and the idempotency record stayed in progress - so even a retry answered ``-32005`` rather than recording the debt. - - Fails against the version without the restart hook with that exact - exception in the captured log, and ``internal_error`` in the response. + """A rotation landing mid-attempt is a restart, and the restart refuses. + + The test above stages the rotation between attempts. This one stages it + inside an attempt: after ``ensure_active_key`` has handed back an active + key and before ``create_receipt`` locks that key's row. The lock finds it + retired and rejects it with ``signing_key_not_active``, which is still a + restart. The restart used to re-activate the retired key and land on a + second resolution; it now meets ``signing_key_retired`` (issue #280), so + instead of a receipt under a retired key the pending item is recorded + without one. It is never ``internal_error`` with nothing written. """ _tool_name, runs = exploding_tool case = await _setup(client, idem_suffix="mid-attempt") @@ -507,31 +574,26 @@ async def test_a_key_retired_inside_an_attempt_restarts_it( "/mcp/messages", json=body, headers=ctx["agent_headers"] ) - # The staging worked: the key the first attempt held was retired under it. - assert state["retired"] >= 1, state - - assert resp.status_code == 200, resp.text - error = resp.json()["error"] - assert error["message"] != INTERNAL_ERROR_MESSAGE, error - assert "signing_key_not_active" not in str(error), error - data = error["data"] - assert data["receipt"]["outcome"] == "failed_unrefunded", data - assert data["refund_reconciliation"]["status"] == "pending", data - - # The restart resolved the key again instead of replaying the retired one, - # and it landed on that second resolution. - assert state["resolved"] == 2, state + # The staging worked: the key the first attempt held was retired under it, + # and the restart's resolution refused rather than re-activating it. + assert state["retired"] == 1, state + assert state["resolved"] == 1, state - assert await _count_receipts() == 1 + await _assert_unsigned_pending(resp) + assert await _count_receipts() == 0 items = await _work_items() assert len(items) == 1, items assert items[0]["status"] == "pending", items[0] - assert items[0]["receipt_id"] == data["receipt"]["receipt_id"], items[0] assert runs["count"] == 1 + with pytest.MonkeyPatch.context() as monkeypatch: + _new_key_id, items = await _sign_after_redeploy(monkeypatch) + assert await _count_receipts() == 1 + assert items[0]["receipt_id"] is not None, items + @pytest.mark.anyio -async def test_a_key_retired_under_every_attempt_exhausts_like_contention( +async def test_a_key_rotated_under_every_attempt_exhausts_like_contention( client: AsyncClient, clean_database: None, exploding_tool ) -> None: """The restart on a stale key spends the same budget and ends the same way. @@ -541,6 +603,11 @@ async def test_a_key_retired_under_every_attempt_exhausts_like_contention( contended write already gives: nothing durable, named non-retryably. This pins the hook to the existing budget and the existing exhausted classification rather than a channel of its own. + + Each attempt now has to meet a real rotation to a fresh key id, which the + process then signs under: retiring the same key in place would make the + next resolution refuse (``signing_key_retired``) and record the refund + unsigned, as the two tests above pin, rather than reach the budget. """ _tool_name, runs = exploding_tool case = await _setup(client, idem_suffix="always-stale") @@ -552,7 +619,7 @@ async def test_a_key_retired_under_every_attempt_exhausts_like_contention( ) with pytest.MonkeyPatch.context() as monkeypatch: - state = _retire_key_after_resolution(monkeypatch, retirements=None) + state = _retire_key_after_resolution(monkeypatch, retirements=None, rotate=True) with patch( "app.services.agent_money.AgentMoney.refund_charge", _failing_refund ): diff --git a/gateway/tests/test_signing_key_lifecycle.py b/gateway/tests/test_signing_key_lifecycle.py index 8c04a658b..954892ef0 100644 --- a/gateway/tests/test_signing_key_lifecycle.py +++ b/gateway/tests/test_signing_key_lifecycle.py @@ -422,3 +422,144 @@ async def test_signing_key_by_id_requires_authentication( # confirm or deny the id's existence to an anonymous caller. resp = await client.get("/v1/signing-keys/key-does-not-exist", headers=headers) assert resp.status_code == expected_status, resp.text + + +def _same_identity(service: SigningKeyService) -> SigningKeyService: + """A second service instance with the same key id and key material. + + Stands in for another replica, or a restart, still configured with the + key ``service`` was configured with. + """ + service._public_key_b64() # settle an ephemeral key's own id first + other = SigningKeyService() + other._private_key = service._private_key + other._key_id = service._key_id + return other + + +async def _key_row(key_id: str) -> SigningKeyModel: + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key_id) + assert row is not None + return row + + +@pytest.mark.anyio +async def test_retired_configured_key_refuses_to_sign_and_stays_retired( + clean_database, +): + """A retired key is not flipped back to active by a signer (issue #280). + + Before the fix, ``ensure_active_key`` on any process still configured with + the retired key id set the row back to ``active`` (resetting + ``activated_at`` and clearing ``retired_at``) and signed. + """ + service = _same_identity(get_signing_key_service()) + await service.sign_payload({"purpose": "before-retirement"}) + key_id = service._key_id + retired = await service.retire_key_metadata(key_id) + + with pytest.raises(SigningKeyError, match="^signing_key_retired$"): + await service.sign_payload({"purpose": "must-not-sign"}) + with pytest.raises(SigningKeyError, match="^signing_key_retired$"): + await service.ensure_active_key() + + row = await _key_row(key_id) + assert row.status == "retired" + assert row.retired_at == retired.retired_at + assert row.activated_at == retired.activated_at + + +@pytest.mark.anyio +async def test_active_row_with_retired_at_set_also_refuses(clean_database): + service = _same_identity(get_signing_key_service()) + key = await service.ensure_active_key() + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key.key_id) + assert row is not None + row.retired_at = row.activated_at + session.add(row) + await session.commit() + + with pytest.raises(SigningKeyError, match="^signing_key_retired$"): + await service.ensure_active_key() + row = await _key_row(key.key_id) + assert row.status == "active" + assert row.retired_at is not None + + +@pytest.mark.anyio +async def test_fresh_key_id_still_bootstraps_and_signs(clean_database): + service = SigningKeyService() + signature, key_id, payload_hash = await service.sign_payload( + {"purpose": "fresh-bootstrap"} + ) + + row = await _key_row(key_id) + assert row.status == "active" + assert row.retired_at is None + assert await service.verify_payload( + { + "purpose": "fresh-bootstrap", + "alg": "Ed25519", + "kid": key_id, + "payload_hash": payload_hash, + }, + signature=signature, + key_id=key_id, + ) + + +@pytest.mark.anyio +async def test_rotation_survives_a_second_instance_on_the_old_key_id( + client, clean_database +): + """Rotation to a new id holds against a replica still on the old id. + + The rotating instance moves to the new key id. A second instance built with + the old key id and material (another replica, or a restart before its + redeploy) refuses to sign, the old row stays retired, the new row stays + active, and the published key set still lists the old key as retired so + receipts signed under it remain verifiable. + """ + rotating = _same_identity(get_signing_key_service()) + old_signature, old_key_id, old_hash = await rotating.sign_payload( + {"purpose": "before-rotation"} + ) + stale = _same_identity(rotating) + new_key_id = f"{old_key_id}-next" + + rotated = await rotating.rotate_active_key_metadata(new_key_id) + assert rotated.key_id == new_key_id + _sig, signed_kid, _hash = await rotating.sign_payload({"purpose": "after"}) + assert signed_kid == new_key_id + + with pytest.raises(SigningKeyError, match="^signing_key_retired$"): + await stale.sign_payload({"purpose": "must-not-sign"}) + + old_row = await _key_row(old_key_id) + new_row = await _key_row(new_key_id) + assert old_row.status == "retired" + assert old_row.retired_at is not None + assert new_row.status == "active" + + published = {key.key_id: key.status for key in await stale.list_public_keys()} + assert published[old_key_id] == "retired" + assert published[new_key_id] == "active" + assert await stale.verify_payload( + { + "purpose": "before-rotation", + "alg": "Ed25519", + "kid": old_key_id, + "payload_hash": old_hash, + }, + signature=old_signature, + key_id=old_key_id, + ) + + resp = await client.get("/.well-known/trust-keys.json") + assert resp.status_code == 200, resp.text + by_kid = {key["kid"]: key for key in resp.json()["keys"]} + assert by_kid[old_key_id]["status"] == "retired" + assert by_kid[old_key_id]["retired_at"] is not None + assert by_kid[new_key_id]["status"] == "active" diff --git a/gateway/tests/test_signing_key_precharge.py b/gateway/tests/test_signing_key_precharge.py index 8cdaeecc5..10e82bded 100644 --- a/gateway/tests/test_signing_key_precharge.py +++ b/gateway/tests/test_signing_key_precharge.py @@ -343,3 +343,39 @@ async def test_standard_mcp_refuses_before_the_mint_and_the_charge( assert again.status_code == 200, again.text assert "error" not in again.json(), again.text assert echo_tool["count"] == 1 + + +@pytest.mark.anyio +async def test_a_replica_left_on_a_retired_key_refuses_before_the_charge( + client: AsyncClient, clean_database: None, echo_tool +) -> None: + """After a rotation, a replica still on the old key id charges nothing. + + A retired key refuses to sign (``signing_key_retired``), and the entry + check turns that into the same retryable ``signing_key_unavailable`` + before any reservation or debit, so the caller retries on a redeployed + replica instead of paying for a call this one cannot receipt. + """ + case = await _setup(client, suffix="retired") + ctx = case["ctx"] + wallet_id = ctx["agent_wallet_id"] + body = _jsonrpc_body( + wallet_id=wallet_id, + permit_id=case["permit"]["permit_id"], + key="signing-precharge-retired", + ) + debits_before = await _debits(wallet_id) + await get_signing_key_service().retire_key_metadata(case["key_id"]) + + with pytest.raises(SigningKeyUnavailableError) as raised: + await get_signing_key_service().assert_ready_to_sign() + assert raised.value.cause == "signing_key_retired" + + resp = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + + error = resp.json()["error"] + assert error["code"] == -32005, error + assert error["message"] == "signing_key_unavailable", error + assert await _debits(wallet_id) == debits_before + assert echo_tool["count"] == 0 + assert (await _key_row(case["key_id"])).status == "retired" From b054b5416b014b632e71c0c39d597700a94998f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 14:07:29 +0000 Subject: [PATCH 04/25] test(awi): swap the module's signing service instead of patching the singleton The AWI pre-charge test made the key unusable by patching the process-wide service's private key. Install a separate misconfigured SigningKeyService as the module's service for the refused call instead, per the test convention. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/tests/test_awi_http_governance.py | 27 ++++++++++++++--------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/gateway/tests/test_awi_http_governance.py b/gateway/tests/test_awi_http_governance.py index 4a354faa1..bda76e7f6 100644 --- a/gateway/tests/test_awi_http_governance.py +++ b/gateway/tests/test_awi_http_governance.py @@ -16,7 +16,8 @@ from app.services import awi_rag_engine as awi_rag_engine_module from app.services.awi_rag_engine import AWIRAGEngine from app.services.idempotency import MAX_CLIENT_IDEMPOTENCY_KEY_LENGTH -from app.services.signing_keys import get_signing_key_service +from app.services import signing_keys as signing_keys_module +from app.services.signing_keys import SigningKeyService, get_signing_key_service from tests.test_trust_helpers import ( BOOTSTRAP_HEADERS, create_tool_permit, @@ -811,7 +812,7 @@ async def _wallet_debits(wallet_id: str) -> int: @pytest.mark.anyio async def test_rag_query_refuses_before_reserving_when_the_key_cannot_sign( - client, clean_database, monkeypatch + client, clean_database ): """An unusable signing key refuses before the reservation and the charge. @@ -831,9 +832,13 @@ async def test_rag_query_refuses_before_reserving_when_the_key_cannot_sign( max_credits=50, idem_key="permit-awi-signing-precharge", ) - service = get_signing_key_service() - await service.ensure_active_key() - real_private_key = service._private_key + real_service = get_signing_key_service() + await real_service.ensure_active_key() + # A replica whose key id is bound to other key material: a fresh service + # instance installed as the module's service, never a patched singleton. + misconfigured = SigningKeyService() + misconfigured._key_id = real_service._key_id + misconfigured._private_key = Ed25519PrivateKey.generate() headers = { **provisioned["agent_headers"], "X-Wallet-Id": wallet_id, @@ -841,17 +846,17 @@ async def test_rag_query_refuses_before_reserving_when_the_key_cannot_sign( "Idempotency-Key": "awi-http-signing-precharge-1", } debits_before = await _wallet_debits(wallet_id) - monkeypatch.setattr(service, "_private_key", Ed25519PrivateKey.generate()) - - refused = await client.post( - "/v1/awi/rag/query", json=RAG_QUERY_PAYLOAD, headers=headers - ) + with pytest.MonkeyPatch.context() as patched: + patched.setattr(signing_keys_module, "_signing_key_service", misconfigured) + refused = await client.post( + "/v1/awi/rag/query", json=RAG_QUERY_PAYLOAD, headers=headers + ) assert refused.status_code == 503, refused.text assert refused.json()["detail"]["error"] == "signing_key_unavailable" assert await _wallet_debits(wallet_id) == debits_before - monkeypatch.setattr(service, "_private_key", real_private_key) + # The module's own service is back in place: the key can sign again. again = await client.post( "/v1/awi/rag/query", json=RAG_QUERY_PAYLOAD, headers=headers ) From d5b94410bc101146201fed46726eac8cd3520fd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 14:08:26 +0000 Subject: [PATCH 05/25] test(refunds): run rotations and redeploys on separate signing services The rewritten refund contention tests mutated the process-wide signing service (its key id on rotation, its key on redeploy). Install separate SigningKeyService instances as the module's service instead, so the singleton is never patched and is restored when each test ends. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- ...efund_reconciliation_contention_surface.py | 46 +++++++++++++------ 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/gateway/tests/test_refund_reconciliation_contention_surface.py b/gateway/tests/test_refund_reconciliation_contention_surface.py index b4760d4d5..527b7ef69 100644 --- a/gateway/tests/test_refund_reconciliation_contention_surface.py +++ b/gateway/tests/test_refund_reconciliation_contention_surface.py @@ -72,7 +72,8 @@ ) from app.services.receipts import ReceiptWriteContendedError from app.services.service_registry import get_service_registry -from app.services.signing_keys import get_signing_key_service +from app.services import signing_keys as signing_keys_module +from app.services.signing_keys import SigningKeyService, get_signing_key_service from tests.test_trust_helpers import create_tool_permit, provision_agent_wallet TOOL_COST = 2.0 @@ -201,11 +202,11 @@ def _retire_key_after_resolution( """Retire the signing key inside ``create_pending``'s attempt, after resolution.""" real_get_signing_key_service = reconciliation_module.get_signing_key_service state = {"resolved": 0, "retired": 0} - # A rotation moves the process-wide service to a new key id; put it back - # when the test ends so later tests sign under the key they expect. - real_service = real_get_signing_key_service() - real_service._public_key_b64() # settle an ephemeral key's own id first - monkeypatch.setattr(real_service, "_key_id", real_service._key_id) + # A rotation moves the signing service it runs on to a new key id. Run it + # on a separate instance with the same key, installed as the module's + # service, so the process-wide one is never mutated and is back in place + # when the test ends. + _install_signing_service(monkeypatch, _copy_of_signing_service()) def patched_get_signing_key_service(): return _KeyRetiredAfterResolution( @@ -355,19 +356,34 @@ async def _count_receipts() -> int: ) +def _copy_of_signing_service() -> SigningKeyService: + """A separate service instance with the current key id and key material.""" + current = get_signing_key_service() + current._public_key_b64() # settle an ephemeral key's own id first + copy = SigningKeyService() + copy._private_key = current._private_key + copy._key_id = current._key_id + return copy + + +def _install_signing_service(monkeypatch, service: SigningKeyService) -> None: + """Make ``service`` the module's signing service until the test ends.""" + monkeypatch.setattr(signing_keys_module, "_signing_key_service", service) + + def _redeploy_with_new_key(monkeypatch) -> str: - """Give the process-wide signing service a new key id and key material. + """Install a signing service with a new key id and new key material. This is what restoring a replica left on a retired key looks like: it is - redeployed with the key the rotation moved to. The monkeypatch puts the - old identity back when the test ends. + redeployed with the key the rotation moved to. The original service is + back in place when the test ends. """ - service = get_signing_key_service() - service._public_key_b64() - new_key_id = f"{service._key_id}-redeployed" - monkeypatch.setattr(service, "_private_key", Ed25519PrivateKey.generate()) - monkeypatch.setattr(service, "_key_id", new_key_id) - return new_key_id + current_key_id = _copy_of_signing_service()._key_id + redeployed = SigningKeyService() + redeployed._private_key = Ed25519PrivateKey.generate() + redeployed._key_id = f"{current_key_id}-redeployed" + _install_signing_service(monkeypatch, redeployed) + return redeployed._key_id async def _assert_unsigned_pending(resp: Any) -> None: From 9943006554716b0f18a1be9c2b160d0c1abdd14e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 14:14:57 +0000 Subject: [PATCH 06/25] test(refunds): a tampered stored payload is never signed sign_unsigned_pending refuses to sign when the stored response payload no longer hashes to the hash recorded at failure time, but no test exercised that branch (disabling it failed nothing). Create the unsigned item with a real governed call, tamper only the stored payload, make the key usable, and assert the signer leaves it unsigned: (0, 1), no receipt row, record unchanged. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- .../test_refund_reconciliation_unsigned.py | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/gateway/tests/test_refund_reconciliation_unsigned.py b/gateway/tests/test_refund_reconciliation_unsigned.py index 79d1a3a13..4b83c8cee 100644 --- a/gateway/tests/test_refund_reconciliation_unsigned.py +++ b/gateway/tests/test_refund_reconciliation_unsigned.py @@ -280,3 +280,48 @@ async def get_receipt_service_verifies(receipt_id: str) -> bool: receipt = await session.get(ReceiptModel, receipt_id) assert receipt is not None return await get_receipt_service().verify_model(receipt, session=session) + + +@pytest.mark.anyio +async def test_a_tampered_stored_payload_is_never_signed( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + """The signer refuses a payload that no longer hashes to the caller's response. + + The unsigned item keeps the response payload and, separately, its hash as + recorded when the call failed. If the stored payload changes afterwards (a + JSON round trip that alters a value, or an edit), signing it would put the + gateway's signature on a response the caller never got. The item stays + unsigned and the record is left exactly as it was. + """ + await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-tampered" + ) + record = await _record_for("refund-unsigned-tampered") + stored = json.loads(record.response_json or "{}") + # The injected fault: change the stored payload, not the recorded hash. + stored[UNSIGNED_RECEIPT_KEY]["inputs"]["response_payload"] = { + "error": "not what the caller was told" + } + tampered_json = json.dumps(stored) + async with get_session_factory()() as session: + row = await session.get(IdempotencyRecordModel, record.record_id) + assert row is not None + row.response_json = tampered_json + session.add(row) + await session.commit() + receipts_before = await _count(ReceiptModel) + # A key that can sign, so the hash check is the only thing that refuses. + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + + ( + signed, + still_unsigned, + ) = await get_refund_reconciliation_service().sign_unsigned_pending() + + assert (signed, still_unsigned) == (0, 1) + assert await _count(ReceiptModel) == receipts_before + after = await _record_for("refund-unsigned-tampered") + assert after.response_reference is None + assert after.response_json == tampered_json + assert after.status_code == record.status_code From d5e8369d4ae2504e3063e2808e5ed5a5ea4fd91f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 14:15:27 +0000 Subject: [PATCH 07/25] test(trust): pin signing_key_status_invalid and document it A key row whose status is not active, retired or disabled refuses to sign with signing_key_status_invalid and is not rewritten. Add the test and name the reason in key-management.md next to the other two refusals. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/docs/key-management.md | 3 ++- gateway/tests/test_signing_key_lifecycle.py | 27 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index 91f096025..1f1744cb9 100644 --- a/gateway/docs/key-management.md +++ b/gateway/docs/key-management.md @@ -212,7 +212,8 @@ What the code does, checked against `app/services/signing_keys.py`: `get_active_key` (`app/routers/keys.py`). It never rewrites an existing row. When the row for the process's configured `TRUST_SIGNING_KEY_ID` is `retired` (or `active` with `retired_at` set) it refuses with - `signing_key_retired`; a `disabled` row refuses with `signing_key_disabled`. + `signing_key_retired`; a `disabled` row refuses with `signing_key_disabled`; + any other status refuses with `signing_key_status_invalid`. A key id with no row yet is inserted as `active` (first bootstrap). This is what the spec wording (`spec/key-set-v0.1.md`) means by a retired key no longer signing new objects. diff --git a/gateway/tests/test_signing_key_lifecycle.py b/gateway/tests/test_signing_key_lifecycle.py index 954892ef0..9e824ecca 100644 --- a/gateway/tests/test_signing_key_lifecycle.py +++ b/gateway/tests/test_signing_key_lifecycle.py @@ -563,3 +563,30 @@ async def test_rotation_survives_a_second_instance_on_the_old_key_id( assert by_kid[old_key_id]["status"] == "retired" assert by_kid[old_key_id]["retired_at"] is not None assert by_kid[new_key_id]["status"] == "active" + + +@pytest.mark.anyio +async def test_unknown_key_status_refuses_without_rewriting_the_row(clean_database): + """A status that is not active, retired or disabled refuses to sign. + + Its reason is ``signing_key_status_invalid``, deliberately not + ``signing_key_not_active``: that one is the refund path's restart signal, + and an unknown status would only repeat on every restart. + """ + service = _same_identity(get_signing_key_service()) + key = await service.ensure_active_key() + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key.key_id) + assert row is not None + row.status = "suspended" + session.add(row) + await session.commit() + before = await _key_row(key.key_id) + + with pytest.raises(SigningKeyError, match="^signing_key_status_invalid$"): + await service.sign_payload({"purpose": "must-not-sign"}) + + after = await _key_row(key.key_id) + assert after.status == "suspended" + assert after.activated_at == before.activated_at + assert after.retired_at == before.retired_at From d44aa9e99b1c7af930dde31a48bed4a9c238ba25 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 14:16:12 +0000 Subject: [PATCH 08/25] fix(keys): answer 503 signing_key_unavailable on the active-key route With a retired key now refusing to sign, GET /v1/signing-keys/active reached ensure_active_key and fell through to the global handler as HTTP 500 internal_error. Map SigningKeyError there to 503 signing_key_unavailable, the reason the governed paths give, keep the underlying reason in the server log, and test it for retired and disabled keys (the by-id route and the published key set keep serving). OpenAPI description regenerated. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/routers/keys.py | 24 +++++++++++--- gateway/docs/key-management.md | 6 ++-- gateway/docs/openapi.json | 2 +- gateway/tests/test_signing_key_lifecycle.py | 35 +++++++++++++++++++++ 4 files changed, 60 insertions(+), 7 deletions(-) diff --git a/gateway/app/routers/keys.py b/gateway/app/routers/keys.py index 5d7ad906e..95b0ec97e 100644 --- a/gateway/app/routers/keys.py +++ b/gateway/app/routers/keys.py @@ -1,10 +1,14 @@ from __future__ import annotations +import logging + from fastapi import APIRouter, Depends, HTTPException from app.core.auth import AuthContext, get_auth_context from app.schemas.trust import SigningKeyResponse -from app.trust import get_signing_key_service +from app.trust import SigningKeyError, get_signing_key_service + +logger = logging.getLogger(__name__) router = APIRouter(prefix="/v1/signing-keys", tags=["Trust Signing Keys"]) @@ -25,9 +29,21 @@ def _key_response(key) -> SigningKeyResponse: async def get_active_signing_key( auth: AuthContext = Depends(get_auth_context), ) -> SigningKeyResponse: - """Return public metadata for the active transaction-evidence signing key.""" - - key = await get_signing_key_service().get_active_key() + """Return public metadata for the active transaction-evidence signing key. + + A replica whose configured key cannot sign (retired, disabled, bound to + other key material) answers 503 ``signing_key_unavailable``, the same + reason the governed paths give, rather than an unclassified 500. The + underlying reason stays in the server log. + """ + + try: + key = await get_signing_key_service().get_active_key() + except SigningKeyError as exc: + logger.warning("signing_key_active_unavailable reason=%s", exc) + raise HTTPException( + status_code=503, detail={"error": "signing_key_unavailable"} + ) from exc return _key_response(key) diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index 1f1744cb9..2e58508f6 100644 --- a/gateway/docs/key-management.md +++ b/gateway/docs/key-management.md @@ -255,8 +255,10 @@ How an operator can tell a replica is stale: `signing_key_retired`, `signing_key_disabled` or `signing_key_id_public_key_mismatch`, and readiness answers 503. A load balancer that gates on readiness stops sending traffic to that replica. -- Its governed calls are refused with `signing_key_unavailable`, and the - server log carries the underlying reason. +- Its governed calls are refused with `signing_key_unavailable`, and so is + `GET /v1/signing-keys/active` (HTTP 503); the server log carries the + underlying reason. `GET /v1/signing-keys/{key_id}` and + `/.well-known/trust-keys.json` keep serving the published keys. What a governed call does when the key cannot sign: the governed MCP transports (`/mcp/messages`, `/mcp/tools/{tool}/invoke` and `/mcp`) and the diff --git a/gateway/docs/openapi.json b/gateway/docs/openapi.json index bb1f1f1ac..5fe06a712 100644 --- a/gateway/docs/openapi.json +++ b/gateway/docs/openapi.json @@ -4351,7 +4351,7 @@ "Trust Signing Keys" ], "summary": "Get Active Signing Key", - "description": "Return public metadata for the active transaction-evidence signing key.", + "description": "Return public metadata for the active transaction-evidence signing key.\n\nA replica whose configured key cannot sign (retired, disabled, bound to\nother key material) answers 503 ``signing_key_unavailable``, the same\nreason the governed paths give, rather than an unclassified 500. The\nunderlying reason stays in the server log.", "operationId": "get_active_signing_key_v1_signing_keys_active_get", "security": [ { diff --git a/gateway/tests/test_signing_key_lifecycle.py b/gateway/tests/test_signing_key_lifecycle.py index 9e824ecca..0dc577168 100644 --- a/gateway/tests/test_signing_key_lifecycle.py +++ b/gateway/tests/test_signing_key_lifecycle.py @@ -590,3 +590,38 @@ async def test_unknown_key_status_refuses_without_rewriting_the_row(clean_databa assert after.status == "suspended" assert after.activated_at == before.activated_at assert after.retired_at == before.retired_at + + +@pytest.mark.anyio +@pytest.mark.parametrize("status", ["retired", "disabled"]) +async def test_active_key_route_answers_503_when_the_configured_key_cannot_sign( + client, clean_database, status +): + """``GET /v1/signing-keys/active`` names the refusal instead of a 500. + + The other key routes keep serving: a retired key's metadata is still + readable by id and still published in the key set. + """ + key = await get_signing_key_service().ensure_active_key() + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key.key_id) + assert row is not None + row.status = status + session.add(row) + await session.commit() + + resp = await client.get("/v1/signing-keys/active", headers=BOOTSTRAP_HEADERS) + + assert resp.status_code == 503, resp.text + assert resp.json()["detail"]["error"] == "signing_key_unavailable" + assert status not in resp.text # the reason stays server side + assert (await _key_row(key.key_id)).status == status + + by_id = await client.get( + f"/v1/signing-keys/{key.key_id}", headers=BOOTSTRAP_HEADERS + ) + assert by_id.status_code == 200, by_id.text + if status == "retired": + key_set = await client.get("/.well-known/trust-keys.json") + assert key_set.status_code == 200, key_set.text + assert key.key_id in {k["kid"] for k in key_set.json()["keys"]} From 1b7cc37fc71810e08413f989892b300307851fdc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 15:35:41 +0000 Subject: [PATCH 09/25] fix(refunds): give an unsigned pending refund a single owner An upstream refund-failed call recorded without a signed receipt left the dispatch attempt returned_error with no receipt, so the dispatch reconciler also compensated it: it refunded the charge, and sign_unsigned_pending then signed a failed_unrefunded receipt for money already returned. The operator retry then hit refund_reconciliation_budget_conflict forever, or, with an earlier paid call on the same permit, released that call's budget too. - list_unfinalized_terminal_contexts skips attempts whose idempotency record carries the unsigned_receipt marker, as it skips a signed failed_unrefunded receipt: the unsigned item and the operator retry own the debt. - sign_unsigned_pending refuses (leaves it unsigned, logs refund_reconciliation_unsigned_already_refunded) when the ledger already holds a refund for the charge. Tests: real upstream calls whose refund fails and whose key is disabled just after the terminal audit, with and without an earlier paid call on the same permit; and the already-refunded state staged through the reconciler's own compensation step. Each fails with its fix removed. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/services/mcp_dispatch_attempts.py | 17 +- gateway/app/services/refund_reconciliation.py | 43 ++++ gateway/docs/failure-semantics.md | 7 +- gateway/tests/test_mcp_upstream_governed.py | 238 +++++++++++++++++- 4 files changed, 302 insertions(+), 3 deletions(-) diff --git a/gateway/app/services/mcp_dispatch_attempts.py b/gateway/app/services/mcp_dispatch_attempts.py index fd3780b49..78778261e 100644 --- a/gateway/app/services/mcp_dispatch_attempts.py +++ b/gateway/app/services/mcp_dispatch_attempts.py @@ -15,7 +15,7 @@ from typing import Any, cast from urllib.parse import urlsplit -from sqlalchemy import func, select, update as sa_update +from sqlalchemy import func, not_, or_, select, update as sa_update from sqlalchemy.exc import IntegrityError, SQLAlchemyError from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql.elements import ColumnElement @@ -42,6 +42,7 @@ get_permit_service, ) from app.services.signing_keys import canonical_json, sha256_hex +from app.services.refund_reconciliation import UNSIGNED_RECEIPT_KEY logger = logging.getLogger(__name__) @@ -2143,6 +2144,20 @@ async def list_unfinalized_terminal_contexts( ColumnElement[bool], cast(Any, ReceiptModel.receipt_id).is_(None), ), + # A pending refund recorded without a signed receipt + # (RefundReconciliationService.create_pending) is + # owned by sign_unsigned_pending and the operator + # retry, exactly as a signed failed_unrefunded receipt + # is: compensating it here as well could refund money + # that the unsigned item still lists as owed. + or_( + cast(Any, IdempotencyRecordModel.response_json).is_(None), + not_( + cast( + Any, IdempotencyRecordModel.response_json + ).contains(f'"{UNSIGNED_RECEIPT_KEY}"') + ), + ), ) .order_by( cast(ColumnElement[Any], McpDispatchAttemptModel.updated_at) diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index d8a018f7e..eef6ea166 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -455,6 +455,33 @@ def retired_under_the_attempt(exc: BaseException) -> bool: ) return None, reconciliation + @staticmethod + async def _charge_already_refunded(ledger_entry_id: str) -> bool: + """Whether any refund ledger row already answers this charge.""" + factory = get_session_factory() + async with factory() as session: + refund = ( + await session.execute( + select(cast(Any, LedgerEntryModel.entry_id)) + .where( + cast( + ColumnElement[bool], + LedgerEntryModel.correlation_id == ledger_entry_id, + ), + cast( + ColumnElement[bool], + LedgerEntryModel.action == "refund", + ), + ) + .limit(1) + ) + ).scalar_one_or_none() + if refund is not None: + return True + return ( + await session.get(LedgerEntryModel, f"refund-{ledger_entry_id}") + ) is not None + async def _record_unsigned_pending( self, *, @@ -563,6 +590,22 @@ async def sign_unsigned_pending(self, *, limit: int = 50) -> tuple[int, int]: if marker is None: continue inputs = dict(marker["inputs"]) + if await self._charge_already_refunded(inputs["ledger_entry_id"]): + # The money already came back by another path (for example a + # dispatch reconciler pass that ran before it learned to leave + # these items alone). A failed_unrefunded receipt would then + # claim a debt that no longer exists, and the operator retry + # would release the permit budget a second time. Leave it for + # an operator, loudly. + logger.error( + "refund_reconciliation_unsigned_already_refunded", + extra={ + "record_id": record.record_id, + "ledger_entry_id": inputs["ledger_entry_id"], + }, + ) + still_unsigned += 1 + continue if sha256_hex(inputs["response_payload"]) != marker.get("response_hash"): # The stored payload no longer hashes to what the caller's # response was; signing it would sign a different response. diff --git a/gateway/docs/failure-semantics.md b/gateway/docs/failure-semantics.md index 4e9319e0f..a4bfa3b7b 100644 --- a/gateway/docs/failure-semantics.md +++ b/gateway/docs/failure-semantics.md @@ -380,7 +380,12 @@ sign writes the `failed_unrefunded` receipt and turns the item into an ordinary pending work item, which the operator list and retry then see; a replica that cannot sign leaves it for the next pass. Until it is signed the item does not appear in the operator list -(`tests/test_refund_reconciliation_unsigned.py`). +(`tests/test_refund_reconciliation_unsigned.py`). The unsigned item is the +only owner of that debt: the dispatch reconciler skips an upstream attempt +whose record carries it, as it skips one with a signed `failed_unrefunded` +receipt, so the money is refunded once, through the operator retry. If a +refund for the charge is already in the ledger anyway, the signer refuses and +logs `refund_reconciliation_unsigned_already_refunded` for an operator. ## What this deliberately does not claim diff --git a/gateway/tests/test_mcp_upstream_governed.py b/gateway/tests/test_mcp_upstream_governed.py index 6f471bdce..2fbfda733 100644 --- a/gateway/tests/test_mcp_upstream_governed.py +++ b/gateway/tests/test_mcp_upstream_governed.py @@ -26,6 +26,7 @@ McpDispatchAttemptModel, PermitModel, ReceiptModel, + SigningKeyModel, WalletModel, ) from app.main import app @@ -40,6 +41,7 @@ DispatchPrepareCommitUncertainError, DispatchPrepareRolledBackError, McpDispatchAttemptService, + get_mcp_dispatch_attempt_service, ) from app.services.mcp_dispatch_reconciliation import ( McpDispatchReconciliationService, @@ -49,7 +51,8 @@ from app.services.quotes import get_quote_service from app.services.receipts import ReceiptService, get_receipt_service from app.services.service_registry import get_service_registry -from app.services.signing_keys import sha256_hex +from app.services.refund_reconciliation import get_refund_reconciliation_service +from app.services.signing_keys import get_signing_key_service, sha256_hex from app.core.config import Settings from app.services.upstream_mcp import ( DiscoveredUpstreamTool, @@ -3329,3 +3332,236 @@ def test_register_upstream_read_only_is_operator_declared(read_only): assert registry.get_local(tool_name)["read_only"] is read_only finally: registry.unregister_local(tool_name) + + +async def _set_signing_key_status(key_id: str, status: str) -> None: + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key_id) + assert row is not None + row.status = status + session.add(row) + await session.commit() + + +async def _wallet_state(wallet_id: str) -> tuple[Decimal, int]: + async with get_session_factory()() as session: + wallet = await session.get(WalletModel, wallet_id) + assert wallet is not None + refunds = int( + await session.scalar( + select(func.count()) + .select_from(LedgerEntryModel) + .where( + LedgerEntryModel.wallet_id == wallet_id, + LedgerEntryModel.action == "refund", + ) + ) + or 0 + ) + return Decimal(str(wallet.balance)), refunds + + +async def _backdate_attempt(attempt_id: str) -> None: + async with get_session_factory()() as session: + attempt = await session.get(McpDispatchAttemptModel, attempt_id) + assert attempt is not None + attempt.updated_at = utc_now() - timedelta(minutes=10) + session.add(attempt) + await session.commit() + + +async def _upstream_refund_failure_with_key_lost( + client: AsyncClient, *, suffix: str, prior_success: bool +) -> dict[str, Any]: + """A real upstream call that errors, whose refund fails, and whose replica + loses its signing key just after the terminal audit event is written. + + The refund-failed path then records the pending refund without a receipt + (issue #280). Faults are injected at class or module level only: the + refund store fails, and the signing key row is disabled. + """ + provisioned = await provision_agent_wallet(client) + wallet_id = provisioned["agent_wallet_id"] + tool_name = f"partner-upstream-unsigned-{suffix}" + executor = FakeUpstreamExecutor("success") + _register_upstream(tool_name, executor) + permit = await create_tool_permit( + client, + wallet_id=wallet_id, + key_id=provisioned["key_id"], + tool_name=tool_name, + max_credits=10, + idem_key=f"partner-upstream-unsigned-{suffix}-permit", + ) + if prior_success: + ok = await client.post( + "/mcp/messages", + json=_call_body( + tool_name=tool_name, + wallet_id=wallet_id, + permit_id=permit["permit_id"], + idempotency_key=f"partner-upstream-unsigned-{suffix}-ok", + ), + headers=provisioned["agent_headers"], + ) + assert ok.status_code == 200 and "error" not in ok.json(), ok.text + executor.mode = "returned_error" + signing_key = await get_signing_key_service().ensure_active_key() + balance_before, refunds_before = await _wallet_state(wallet_id) + real_audit = mcp_router._audit_mcp_invocation + + async def audit_then_lose_key(**kwargs: Any) -> Any: + event = await real_audit(**kwargs) + if str(kwargs.get("error") or "").startswith("refund_failed"): + await _set_signing_key_status(signing_key.key_id, "disabled") + return event + + async def failing_refund(*_args: Any, **_kwargs: Any) -> None: + raise RuntimeError("refund unavailable") + + idempotency_key = f"partner-upstream-unsigned-{suffix}-1" + with pytest.MonkeyPatch.context() as patched: + patched.setattr(mcp_router, "_audit_mcp_invocation", audit_then_lose_key) + patched.setattr( + "app.services.agent_money.AgentMoney.refund_charge", failing_refund + ) + response = await client.post( + "/mcp/messages", + json=_call_body( + tool_name=tool_name, + wallet_id=wallet_id, + permit_id=permit["permit_id"], + idempotency_key=idempotency_key, + ), + headers=provisioned["agent_headers"], + ) + error = response.json()["error"] + reconciliation = error["data"]["refund_reconciliation"] + assert reconciliation["status"] == "pending", error + assert reconciliation["receipt_status"] == "unsigned", error + async with get_session_factory()() as session: + attempt = ( + await session.execute( + select(McpDispatchAttemptModel) + .join( + IdempotencyRecordModel, + IdempotencyRecordModel.record_id + == McpDispatchAttemptModel.idempotency_record_id, + ) + .where(IdempotencyRecordModel.idempotency_key == idempotency_key) + ) + ).scalar_one() + assert attempt.state == "returned_error" + return { + "wallet_id": wallet_id, + "tool_name": tool_name, + "permit_id": permit["permit_id"], + "attempt_id": attempt.attempt_id, + "key_id": signing_key.key_id, + "balance_before": balance_before, + "refunds_before": refunds_before, + } + + +@pytest.mark.anyio +@pytest.mark.parametrize("prior_success", [False, True]) +async def test_dispatch_reconciler_leaves_an_unsigned_pending_refund_to_its_owner( + client: AsyncClient, clean_database: None, prior_success: bool +) -> None: + """One owner for the debt: the unsigned item, not the dispatch reconciler. + + Before the fix the reconciler compensated the returned_error attempt (it + has no receipt yet), refunding the charge, and the unsigned signer then + wrote a failed_unrefunded receipt for money already returned; the operator + retry either failed forever (budget conflict) or, with an earlier paid + call on the same permit, released that call's budget too, so the permit + under-counted. Now the reconciler skips the attempt like it skips a signed + failed_unrefunded receipt, and the refund happens exactly once, through + the operator retry. + """ + case = await _upstream_refund_failure_with_key_lost( + client, suffix=f"owner-{prior_success}", prior_success=prior_success + ) + try: + await _backdate_attempt(case["attempt_id"]) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + + # The reconciler did not touch the money it does not own. + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"] - Decimal("2"), + case["refunds_before"], + ) + + await _set_signing_key_status(case["key_id"], "active") + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending() == (1, 0) + await _backdate_attempt(case["attempt_id"]) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + + async with get_session_factory()() as session: + receipt = ( + await session.execute( + select(ReceiptModel).where( + ReceiptModel.dispatch_attempt_id == case["attempt_id"] + ) + ) + ).scalar_one() + assert receipt.outcome == "failed_unrefunded" + + item, already = await service.retry(receipt.receipt_id) + assert item.status == "resolved" and already is False + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + permit = await get_permit_service().get_permit(case["permit_id"]) + assert permit is not None + # Only the paid earlier call (if any) still counts against the permit. + assert permit.spent_credits == (Decimal("2") if prior_success else 0) + finally: + get_service_registry().unregister_local(case["tool_name"]) + + +@pytest.mark.anyio +async def test_unsigned_item_is_never_signed_after_a_refund_landed_elsewhere( + client: AsyncClient, clean_database: None +) -> None: + """Defense in depth for a refund that already landed by another path. + + Stages the state the reconciler produced before it learned to skip these + items (its own compensation step, called directly): the charge is + refunded while the unsigned item still lists it as owed. Signing must + refuse, leaving no failed_unrefunded receipt claiming a debt that is gone. + """ + case = await _upstream_refund_failure_with_key_lost( + client, suffix="landed-elsewhere", prior_success=False + ) + try: + reconciler = get_mcp_dispatch_reconciliation_service() + attempt = await get_mcp_dispatch_attempt_service().get_context( + case["attempt_id"] + ) + assert attempt is not None + await reconciler._compensate_returned_error(attempt.attempt) + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + await _set_signing_key_status(case["key_id"], "active") + + assert await get_refund_reconciliation_service().sign_unsigned_pending() == ( + 0, + 1, + ) + async with get_session_factory()() as session: + receipts = int( + await session.scalar( + select(func.count()) + .select_from(ReceiptModel) + .where(ReceiptModel.dispatch_attempt_id == case["attempt_id"]) + ) + or 0 + ) + assert receipts == 0 + finally: + get_service_registry().unregister_local(case["tool_name"]) From 11ed397d3a71b2cf89b1b88fd6121c4243faa8fb Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 15:38:07 +0000 Subject: [PATCH 10/25] fix(billing): refuse a charge before the debit when the signing key cannot sign POST /v1/billing/charge debits and then signs its governance audit event. With a disabled or retired key it answered 500 after the debit, with no audit event, and a retry of the same key got idempotency_in_progress. Run assert_ready_to_sign before the idempotency record is begun and answer 503 signing_key_unavailable; nothing is recorded, so the key can be retried on a replica that can sign. Test: refused with no debit, then the same key succeeds. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/routers/billing.py | 17 +++++++++++ gateway/docs/key-management.md | 20 ++++++------ gateway/tests/test_signing_key_precharge.py | 34 +++++++++++++++++++++ 3 files changed, 62 insertions(+), 9 deletions(-) diff --git a/gateway/app/routers/billing.py b/gateway/app/routers/billing.py index d14eea8c8..1a12d95ef 100644 --- a/gateway/app/routers/billing.py +++ b/gateway/app/routers/billing.py @@ -42,6 +42,10 @@ get_idempotency_service, ) from ..services.policies import evaluate_wallet_policy +from ..services.signing_keys import ( + SigningKeyUnavailableError, + get_signing_key_service, +) from ..services.velocity_monitor import WalletFrozenError from ..services.wallet_engine import CrossTenantTransferError, WalletExpiredError from ..services.stripe_integration import get_stripe_integration @@ -684,6 +688,19 @@ async def charge_wallet( }, ) + # Refuse before anything is begun or debited when this replica's signing + # key cannot sign: the charge's governance audit event is signed after the + # debit, and finding out there would leave a debit with no audit event and + # the idempotency key stuck in progress. Nothing is recorded here, so the + # caller may retry the same key on a replica whose key can sign. + try: + await get_signing_key_service().assert_ready_to_sign() + except SigningKeyUnavailableError as exc: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail={"error": exc.reason}, + ) from exc + # Idempotency is opt-in via the Idempotency-Key header: a client that # retries a charge (e.g. after a timeout) with the same key gets the # original outcome replayed instead of being billed twice. diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index 2d79c52b6..f54d217a1 100644 --- a/gateway/docs/key-management.md +++ b/gateway/docs/key-management.md @@ -258,15 +258,17 @@ How an operator can tell a replica is stale: to `active`. What a governed call does when the key cannot sign: the governed MCP -transports (`/mcp/messages`, `/mcp/tools/{tool}/invoke` and `/mcp`) and the -AWI HTTP routes run `SigningKeyService.assert_ready_to_sign` before they -reserve budget or charge. If the configured key is disabled, bound to other -key material, or otherwise cannot sign, the call is refused with -`signing_key_unavailable` (JSON-RPC `-32005`, HTTP 409 on the REST invoke -route, HTTP 503 on the AWI routes) and nothing is recorded, so the caller can -retry the same idempotency key on a replica whose key can sign. A rotation -that lands after that check and before the call finishes is not covered by -it. +transports (`/mcp/messages`, `/mcp/tools/{tool}/invoke` and `/mcp`), the AWI +HTTP routes and `POST /v1/billing/charge` run +`SigningKeyService.assert_ready_to_sign` before they reserve budget or charge. +If the configured key is disabled, bound to other key material, or otherwise +cannot sign, the call is refused with `signing_key_unavailable` (JSON-RPC +`-32005`, HTTP 409 on the REST invoke route, HTTP 503 on the AWI routes and on +the billing charge route) and nothing is recorded, so the caller can retry the +same idempotency key on a replica whose key can sign. The underlying reason is +logged once, as a `signing_key_unavailable cause=...` warning from +`app.services.signing_keys`. A rotation that lands after that check and before +the call finishes is not covered by it. Why a retired key still signs: making a retired key refuse to sign (`signing_key_retired`) would stop the reactivation, but the pending-refund diff --git a/gateway/tests/test_signing_key_precharge.py b/gateway/tests/test_signing_key_precharge.py index 8cdaeecc5..c4a4a46b0 100644 --- a/gateway/tests/test_signing_key_precharge.py +++ b/gateway/tests/test_signing_key_precharge.py @@ -343,3 +343,37 @@ async def test_standard_mcp_refuses_before_the_mint_and_the_charge( assert again.status_code == 200, again.text assert "error" not in again.json(), again.text assert echo_tool["count"] == 1 + + +@pytest.mark.anyio +async def test_billing_charge_refuses_before_the_debit_and_the_key_stays_retryable( + client: AsyncClient, clean_database: None +) -> None: + """``POST /v1/billing/charge`` debits, then signs its governance audit event. + + With a key that cannot sign it used to debit and then fail: HTTP 500, one + debit, no audit event, and a retry of the same key answered + ``idempotency_in_progress``. It now refuses first. + """ + ctx = await provision_agent_wallet(client) + wallet_id = ctx["agent_wallet_id"] + key = await get_signing_key_service().ensure_active_key() + url = ( + f"/v1/billing/charge?wallet_id={wallet_id}" + "&service=agent_comms&units=2&request_path=POST+/v1/agent-comms/send" + ) + headers = {**ctx["agent_headers"], "Idempotency-Key": "signing-precharge-billing"} + debits_before = await _debits(wallet_id) + await _set_key_status(key.key_id, "disabled") + + refused = await client.post(url, headers=headers) + + assert refused.status_code == 503, refused.text + assert refused.json()["detail"]["error"] == "signing_key_unavailable" + assert await _debits(wallet_id) == debits_before + + await _set_key_status(key.key_id, "active") + again = await client.post(url, headers=headers) + assert again.status_code == 200, again.text + assert await _debits(wallet_id) == debits_before + 1 + From 0768bb8d80f55b4509a915da0fca81e88e4af72f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 15:38:07 +0000 Subject: [PATCH 11/25] fix(trust): log the underlying reason when a key cannot sign SigningKeyUnavailableError kept the cause for the server log, but nothing logged it: every caller answers with the canned signing_key_unavailable. assert_ready_to_sign now writes one warning with the cause and the key id. Test with caplog. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/services/signing_keys.py | 10 ++++++++++ gateway/tests/test_signing_key_precharge.py | 22 +++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/gateway/app/services/signing_keys.py b/gateway/app/services/signing_keys.py index 85c667cfc..c09d90159 100644 --- a/gateway/app/services/signing_keys.py +++ b/gateway/app/services/signing_keys.py @@ -1,5 +1,7 @@ from __future__ import annotations +import logging + import base64 import binascii import hashlib @@ -25,6 +27,9 @@ from app.db.models import SigningKeyModel +logger = logging.getLogger(__name__) + + class SigningKeyError(RuntimeError): """Raised when trust-plane signing or verification cannot proceed.""" @@ -356,6 +361,11 @@ async def assert_ready_to_sign(self) -> None: try: await self.ensure_active_key() except SigningKeyError as exc: + # The one place the underlying reason is written down: callers + # answer with the canned ``signing_key_unavailable`` only. + logger.warning( + "signing_key_unavailable cause=%s key_id=%s", exc, self._key_id + ) raise SigningKeyUnavailableError(str(exc)) from exc async def configured_key_status(self) -> str | None: diff --git a/gateway/tests/test_signing_key_precharge.py b/gateway/tests/test_signing_key_precharge.py index c4a4a46b0..bdc48a8f9 100644 --- a/gateway/tests/test_signing_key_precharge.py +++ b/gateway/tests/test_signing_key_precharge.py @@ -377,3 +377,25 @@ async def test_billing_charge_refuses_before_the_debit_and_the_key_stays_retryab assert again.status_code == 200, again.text assert await _debits(wallet_id) == debits_before + 1 + +@pytest.mark.anyio +async def test_the_refusal_logs_its_underlying_reason_once( + clean_database: None, caplog: pytest.LogCaptureFixture +) -> None: + """Callers answer with the canned reason; the cause is in the server log.""" + service = get_signing_key_service() + key = await service.ensure_active_key() + await _set_key_status(key.key_id, "disabled") + + with caplog.at_level("WARNING", logger="app.services.signing_keys"): + with pytest.raises(SigningKeyUnavailableError): + await service.assert_ready_to_sign() + + lines = [ + record.getMessage() + for record in caplog.records + if record.name == "app.services.signing_keys" + ] + assert len(lines) == 1, lines + assert "cause=signing_key_disabled" in lines[0] + assert key.key_id in lines[0] From 55b42acd48b42f1effd8832a8bc03743f195c509 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 15:39:30 +0000 Subject: [PATCH 12/25] fix(health): judge the signing key by the rule signing uses Readiness matched only the status names retired and disabled, so it reported up for an active row with retired_at set and for an unknown status, both of which ensure_active_key now refuses. Add a read-only SigningKeyService.configured_key_problem that applies the same mapping and _assert_configured_key_can_sign checks and returns the refusal reason; health reports that reason. Drop the stale comment that a retired row can still be reactivated. Tests for both edge rows. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/core/health.py | 37 ++++++------------- gateway/app/services/signing_keys.py | 21 +++++++++++ gateway/tests/test_signing_key_precharge.py | 41 +++++++++++++++++++++ 3 files changed, 73 insertions(+), 26 deletions(-) diff --git a/gateway/app/core/health.py b/gateway/app/core/health.py index 245a53fe5..1ac6b7d98 100644 --- a/gateway/app/core/health.py +++ b/gateway/app/core/health.py @@ -480,47 +480,32 @@ async def _check_signing_key() -> dict[str, Any]: return {"status": "up", "state": "loaded"} -# Key row states that mean this replica cannot be trusted to sign. A missing -# row is fine (the first signature creates it); an active row is fine. -_UNUSABLE_KEY_ROW_STATUSES: dict[str, str] = { - "retired": "signing_key_retired", - "disabled": "signing_key_disabled", -} - - async def _configured_key_row_problem() -> str | None: """Read the configured key's row and name why it cannot sign, if it cannot. - Read-only: it never creates or reactivates the row, so a health probe can - not undo a retirement. A replica still configured with a retired or - disabled key id, or with key material that does not match its row, is - reported down, which takes it out of a readiness-gated rotation before it - reaches the charge. A row lookup that fails (for example the database is - down) is left to the postgres check rather than reported twice here. + Uses ``SigningKeyService.configured_key_problem``, the same rule + ``ensure_active_key`` signs by, so readiness and signing cannot disagree: + a retired row (or an active row with ``retired_at`` set), a disabled row, + an unknown status, or a row bound to other key material is reported down. + Read-only: it never creates or rewrites the row. A row lookup that fails + (for example the database is down) is left to the postgres check rather + than reported twice here. """ try: - status = await get_signing_key_service().configured_key_status() - except SigningKeyError as exc: - if str(exc) == "signing_key_id_public_key_mismatch": - return "signing_key_id_public_key_mismatch" - return None + return await get_signing_key_service().configured_key_problem() except Exception: logger.debug("signing key row check raised", exc_info=True) return None - if status is None: - return None - return _UNUSABLE_KEY_ROW_STATUSES.get(status) async def check_signing_key_readiness() -> dict[str, Any]: """``/health/ready`` entry for the signing key, shared with the full report. Down when this replica's configured key cannot sign: invalid or missing key - material, or a key row that is retired, disabled or bound to other key - material. A load balancer that gates on readiness then stops sending - governed calls to a replica that would refuse them, or, while a retired - row can still be reactivated, would sign under a key the operator retired. + material, or a key row that is retired, disabled, in an unknown status or + bound to other key material. A load balancer that gates on readiness then + stops sending governed calls to a replica that would refuse them. """ return await _run_check("signing_key", _check_signing_key) diff --git a/gateway/app/services/signing_keys.py b/gateway/app/services/signing_keys.py index a09267c3b..8919c603e 100644 --- a/gateway/app/services/signing_keys.py +++ b/gateway/app/services/signing_keys.py @@ -404,6 +404,27 @@ async def configured_key_status(self) -> str | None: self._assert_public_key_mapping(key, public_key_b64) return key.status + async def configured_key_problem(self) -> str | None: + """Why the configured key cannot sign, by the same rule signing uses. + + Read-only: applies ``_assert_public_key_mapping`` and + ``_assert_configured_key_can_sign`` to the stored row and returns the + refusal reason, or ``None`` when the key can sign (or has no row yet, + which the first signature creates). Readiness uses this so it can + never report ``up`` for a key that ``ensure_active_key`` refuses. + """ + + public_key_b64 = self._public_key_b64() + key = await self.get_public_key(self._key_id) + if key is None: + return None + try: + self._assert_public_key_mapping(key, public_key_b64) + self._assert_configured_key_can_sign(key) + except SigningKeyError as exc: + return str(exc) + return None + async def get_active_key(self) -> SigningKeyModel: """Return the current active public metadata, creating it if needed.""" diff --git a/gateway/tests/test_signing_key_precharge.py b/gateway/tests/test_signing_key_precharge.py index 9fb8b1613..523cac8aa 100644 --- a/gateway/tests/test_signing_key_precharge.py +++ b/gateway/tests/test_signing_key_precharge.py @@ -435,3 +435,44 @@ async def test_the_refusal_logs_its_underlying_reason_once( assert len(lines) == 1, lines assert "cause=signing_key_disabled" in lines[0] assert key.key_id in lines[0] + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("edit", "error"), + [ + ({"retired_at_from_activated": True}, "signing_key_retired"), + ({"status": "suspended"}, "signing_key_status_invalid"), + ], +) +async def test_health_agrees_with_signing_on_edge_rows( + client: AsyncClient, clean_database: None, edit: dict[str, Any], error: str +) -> None: + """Readiness reports down exactly where ``ensure_active_key`` refuses. + + An active row with ``retired_at`` set, and a status that is none of + active, retired or disabled, both refuse to sign; health used to report + both ``up`` because it only matched the status names. + """ + service = get_signing_key_service() + key = await service.ensure_active_key() + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key.key_id) + assert row is not None + if edit.get("retired_at_from_activated"): + row.retired_at = row.activated_at + if "status" in edit: + row.status = edit["status"] + session.add(row) + await session.commit() + + with pytest.raises(SigningKeyUnavailableError) as raised: + await service.assert_ready_to_sign() + assert raised.value.cause == error + + report = await gather_dependency_report() + assert report["dependencies"]["signing_key"]["status"] == "down" + assert report["dependencies"]["signing_key"]["error"] == error + ready = await client.get("/health/ready") + assert ready.status_code == 503, ready.text + assert ready.json()["checks"]["signing_key"]["error"] == error From 1e2af9ba91e78c2a660d68131e95860bf9df6fa1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 15:40:00 +0000 Subject: [PATCH 13/25] docs(keys): say exactly which in-flight paths a mid-call retirement covers The doc said a rotation landing after the pre-charge check is handled on the refund-failed path. That is true for local tools, and for upstream tools only when the terminal audit was written first. On the success path the call ends with a debit, no receipt, internal_error and the key held in progress until reconcile_stuck_records flags it, as a disabled key already does. Spell out the three cases and point at the rollout order. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/docs/key-management.md | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index 896c49aec..18c18d5c7 100644 --- a/gateway/docs/key-management.md +++ b/gateway/docs/key-management.md @@ -272,11 +272,27 @@ can retry the same idempotency key on a replica whose key can sign. The underlying reason is logged once, as a `signing_key_unavailable cause=...` warning from `app.services.signing_keys`. -A rotation that lands after that check and before the call finishes is -handled on the refund-failed path: if the `failed_unrefunded` receipt cannot be -signed, the pending refund is recorded without a receipt and a replica whose -key can sign signs it later (see "Refunds are written at most once" in -[failure semantics](failure-semantics.md)). The analysis is in +A key retired (or disabled) after that check and before the call finishes is +only partly covered: + +- Success path: the tool ran and the wallet was charged, but the audit event + or receipt cannot be signed. The caller gets `-32603` `internal_error`, the + debit stands with no receipt, and a retry of the same key answers + `idempotency_in_progress` until `reconcile_stuck_records` flags the record + for manual review. A disabled key already behaves this way; a retired one + now does too. The rollout order above (retire the old row only after no + replica runs the old id) is what keeps this from happening. +- Refund-failed path, local tools: if the `failed_unrefunded` receipt cannot + be signed, the pending refund is recorded without a receipt and a replica + whose key can sign signs it later (see "Refunds are written at most once" + in [failure semantics](failure-semantics.md)). +- Refund-failed path, upstream (remote MCP) tools: the same holds when the + terminal audit event was written before the key was lost. If the key was + lost before that audit event, nothing is recorded by the call; the dispatch + attempt row remains and the dispatch reconciler rebuilds the evidence from + a replica whose key can sign. + +The analysis is in [issue 280](https://github.com/agentmiddleware/agent-middleware/issues/280). This is documented as a known limitation in `SECURITY_LIMITATIONS.md` and From 8a1c6d7e6c6ecd78bc5f1fa5151ce034f652d9c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 15:40:31 +0000 Subject: [PATCH 14/25] test(trust): pin rotation back to a retired key id as the one reactivation path Rotating to an existing retired target from an instance holding its key sets it active again and retires the key rotated away from. Dropping that branch failed no test before. Refs #280. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/tests/test_signing_key_lifecycle.py | 24 +++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/gateway/tests/test_signing_key_lifecycle.py b/gateway/tests/test_signing_key_lifecycle.py index 0dc577168..90f9a2fe5 100644 --- a/gateway/tests/test_signing_key_lifecycle.py +++ b/gateway/tests/test_signing_key_lifecycle.py @@ -625,3 +625,27 @@ async def test_active_key_route_answers_503_when_the_configured_key_cannot_sign( key_set = await client.get("/.well-known/trust-keys.json") assert key_set.status_code == 200, key_set.text assert key.key_id in {k["kid"] for k in key_set.json()["keys"]} + + +@pytest.mark.anyio +async def test_rotation_back_to_a_retired_key_id_reactivates_it(clean_database): + """The one documented way a retired row becomes active again. + + ``rotate_active_key_metadata`` to an existing (retired) target id, from an + instance that holds that key's material, sets the target active and + retires the key it rotates away from. Signing then works under the target. + """ + first = _same_identity(get_signing_key_service()) + first_key_id = (await first.ensure_active_key()).key_id + second_key_id = f"{first_key_id}-second" + await first.rotate_active_key_metadata(second_key_id) + assert (await _key_row(first_key_id)).status == "retired" + + await first.rotate_active_key_metadata(first_key_id) + + back = await _key_row(first_key_id) + assert back.status == "active" + assert back.retired_at is None + assert (await _key_row(second_key_id)).status == "retired" + _sig, kid, _hash = await first.sign_payload({"purpose": "after-rotation-back"}) + assert kid == first_key_id From 881028aed67054b0f8625cf6b52241e8ef0bbe43 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:32:21 +0000 Subject: [PATCH 15/25] fix(refunds): sign an unsigned item whose refund landed but was never acknowledged The already-refunded backstop in sign_unsigned_pending refused any item whose charge had a refund row. That also caught the lost acknowledgement case: the live path refunds the charge, mark_debit_refunded fails, and the call goes down the refund-failed path with the reservation still held. Nothing else releases that reservation (the dispatch sweep skips an attempt whose refund was never checkpointed while its debit stands), so it stayed held until the permit expired. The signer now refuses only when the refund landed and the dispatch attempt shows the reservation already released. Otherwise it signs as usual and the operator retry, finding the refund row, refunds nothing more and releases the reservation once. The probe test drives a real upstream returned_error call with mark_debit_refunded failing at class level and the key lost after the refund_failed audit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/services/refund_reconciliation.py | 60 ++++++++--- gateway/docs/failure-semantics.md | 11 +- gateway/tests/test_mcp_upstream_governed.py | 100 +++++++++++++++++- 3 files changed, 150 insertions(+), 21 deletions(-) diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index eef6ea166..f1beec856 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -20,6 +20,7 @@ HumanApprovalModel, IdempotencyRecordModel, LedgerEntryModel, + McpDispatchAttemptModel, PermitModel, ReceiptModel, WalletModel, @@ -456,8 +457,23 @@ def retired_under_the_attempt(exc: BaseException) -> bool: return None, reconciliation @staticmethod - async def _charge_already_refunded(ledger_entry_id: str) -> bool: - """Whether any refund ledger row already answers this charge.""" + async def _refund_landed_and_budget_released(inputs: dict[str, Any]) -> bool: + """Whether this charge was refunded *and* its reservation released. + + Only that combination makes the unsigned item wrong to sign. A refund + row with the reservation still held is the lost acknowledgement case: + the live path refunded the charge, then failed to checkpoint it on the + dispatch attempt (``mark_debit_refunded``), and went down the + refund-failed path. Nothing else releases that reservation (the + dispatch sweep skips an attempt whose refund was never checkpointed + while its debit stands), so the item is signed as usual and the + operator retry, finding the refund row, releases the reservation once + without refunding again. + + The reservation counts as released when the dispatch attempt says so. + Without a dispatch attempt nothing but the operator retry releases it. + """ + ledger_entry_id = inputs["ledger_entry_id"] factory = get_session_factory() async with factory() as session: refund = ( @@ -476,11 +492,26 @@ async def _charge_already_refunded(ledger_entry_id: str) -> bool: .limit(1) ) ).scalar_one_or_none() - if refund is not None: - return True - return ( - await session.get(LedgerEntryModel, f"refund-{ledger_entry_id}") - ) is not None + if ( + refund is None + and (await session.get(LedgerEntryModel, f"refund-{ledger_entry_id}")) + is None + ): + return False + attempt_id = inputs.get("dispatch_attempt_id") + if not attempt_id: + return False + attempt = await session.get(McpDispatchAttemptModel, attempt_id) + released = attempt is not None and attempt.budget_released_at is not None + if not released: + logger.warning( + "refund_reconciliation_unsigned_refund_unacknowledged", + extra={ + "ledger_entry_id": ledger_entry_id, + "dispatch_attempt_id": attempt_id, + }, + ) + return released async def _record_unsigned_pending( self, @@ -590,13 +621,14 @@ async def sign_unsigned_pending(self, *, limit: int = 50) -> tuple[int, int]: if marker is None: continue inputs = dict(marker["inputs"]) - if await self._charge_already_refunded(inputs["ledger_entry_id"]): - # The money already came back by another path (for example a - # dispatch reconciler pass that ran before it learned to leave - # these items alone). A failed_unrefunded receipt would then - # claim a debt that no longer exists, and the operator retry - # would release the permit budget a second time. Leave it for - # an operator, loudly. + if await self._refund_landed_and_budget_released(inputs): + # The money already came back and the permit reservation was + # already given back, by another path (for example a dispatch + # reconciler pass that ran before it learned to leave these + # items alone). A failed_unrefunded receipt would then claim a + # debt that no longer exists, and the operator retry would + # release the permit budget a second time. Leave it for an + # operator, loudly. logger.error( "refund_reconciliation_unsigned_already_refunded", extra={ diff --git a/gateway/docs/failure-semantics.md b/gateway/docs/failure-semantics.md index a4bfa3b7b..1d67bd596 100644 --- a/gateway/docs/failure-semantics.md +++ b/gateway/docs/failure-semantics.md @@ -384,8 +384,15 @@ item does not appear in the operator list only owner of that debt: the dispatch reconciler skips an upstream attempt whose record carries it, as it skips one with a signed `failed_unrefunded` receipt, so the money is refunded once, through the operator retry. If a -refund for the charge is already in the ledger anyway, the signer refuses and -logs `refund_reconciliation_unsigned_already_refunded` for an operator. +refund for the charge is already in the ledger and its permit reservation is +still held (the live path refunded, then failed to record the refund on the +dispatch attempt), the signer signs as usual and logs +`refund_reconciliation_unsigned_refund_unacknowledged`; the operator retry +then finds that refund, refunds nothing more, and releases the reservation +once. If the reservation was already released as well, the signer refuses and +logs `refund_reconciliation_unsigned_already_refunded`; that item has no +automatic resolution and needs an operator +(`tests/test_mcp_upstream_governed.py`). ## What this deliberately does not claim diff --git a/gateway/tests/test_mcp_upstream_governed.py b/gateway/tests/test_mcp_upstream_governed.py index 2fbfda733..60697dc5d 100644 --- a/gateway/tests/test_mcp_upstream_governed.py +++ b/gateway/tests/test_mcp_upstream_governed.py @@ -3371,14 +3371,21 @@ async def _backdate_attempt(attempt_id: str) -> None: async def _upstream_refund_failure_with_key_lost( - client: AsyncClient, *, suffix: str, prior_success: bool + client: AsyncClient, + *, + suffix: str, + prior_success: bool, + lost_ack: bool = False, ) -> dict[str, Any]: """A real upstream call that errors, whose refund fails, and whose replica loses its signing key just after the terminal audit event is written. The refund-failed path then records the pending refund without a receipt (issue #280). Faults are injected at class or module level only: the - refund store fails, and the signing key row is disabled. + refund store fails, and the signing key row is disabled. With + ``lost_ack`` the refund itself lands and only its checkpoint on the + dispatch attempt (``mark_debit_refunded``) fails, so the live path takes + the refund-failed branch with the money already back. """ provisioned = await provision_agent_wallet(client) wallet_id = provisioned["agent_wallet_id"] @@ -3419,12 +3426,20 @@ async def audit_then_lose_key(**kwargs: Any) -> Any: async def failing_refund(*_args: Any, **_kwargs: Any) -> None: raise RuntimeError("refund unavailable") + async def failing_ack(*_args: Any, **_kwargs: Any) -> None: + raise RuntimeError("refund checkpoint unavailable") + idempotency_key = f"partner-upstream-unsigned-{suffix}-1" with pytest.MonkeyPatch.context() as patched: patched.setattr(mcp_router, "_audit_mcp_invocation", audit_then_lose_key) - patched.setattr( - "app.services.agent_money.AgentMoney.refund_charge", failing_refund - ) + if lost_ack: + patched.setattr( + McpDispatchAttemptService, "mark_debit_refunded", failing_ack + ) + else: + patched.setattr( + "app.services.agent_money.AgentMoney.refund_charge", failing_refund + ) response = await client.post( "/mcp/messages", json=_call_body( @@ -3565,3 +3580,78 @@ async def test_unsigned_item_is_never_signed_after_a_refund_landed_elsewhere( assert receipts == 0 finally: get_service_registry().unregister_local(case["tool_name"]) + + +@pytest.mark.anyio +@pytest.mark.parametrize("prior_success", [False, True]) +async def test_unsigned_item_whose_refund_landed_unacknowledged_is_signed_and_released_once( + client: AsyncClient, clean_database: None, prior_success: bool +) -> None: + """The lost acknowledgement case: refund landed, reservation still held. + + The live path refunds the charge, then fails to checkpoint the refund on + the dispatch attempt, so it records a pending refund (unsigned, because + the key is lost too). Nothing else releases that reservation: the + dispatch sweep skips an attempt whose refund was never checkpointed while + its debit stands. The signer must therefore not refuse this item just + because a refund row exists. Signed, the operator retry finds the refund + row, refunds nothing more, and releases the reservation exactly once. + """ + case = await _upstream_refund_failure_with_key_lost( + client, + suffix=f"lost-ack-{prior_success}", + prior_success=prior_success, + lost_ack=True, + ) + try: + # The money is already back, and the reservation is still held. + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + permit = await get_permit_service().get_permit(case["permit_id"]) + assert permit is not None + held = Decimal("4") if prior_success else Decimal("2") + assert permit.spent_credits == held + + # The dispatch sweep does not release it. + await _backdate_attempt(case["attempt_id"]) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + permit = await get_permit_service().get_permit(case["permit_id"]) + assert permit is not None + assert permit.spent_credits == held + + await _set_signing_key_status(case["key_id"], "active") + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending() == (1, 0) + async with get_session_factory()() as session: + receipt = ( + await session.execute( + select(ReceiptModel).where( + ReceiptModel.dispatch_attempt_id == case["attempt_id"] + ) + ) + ).scalar_one() + assert receipt.outcome == "failed_unrefunded" + + item, already = await service.retry(receipt.receipt_id) + assert item.status == "resolved" and already is False + # No second refund, and the reservation is released once. + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + permit = await get_permit_service().get_permit(case["permit_id"]) + assert permit is not None + assert permit.spent_credits == (Decimal("2") if prior_success else 0) + + # Neither a second retry nor a later sweep releases it again. + _item, already = await service.retry(receipt.receipt_id) + assert already is True + await _backdate_attempt(case["attempt_id"]) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + permit = await get_permit_service().get_permit(case["permit_id"]) + assert permit is not None + assert permit.spent_credits == (Decimal("2") if prior_success else 0) + finally: + get_service_registry().unregister_local(case["tool_name"]) From 00c0b0f6d5c7ba7b08fb8ed1cc7467fb1aabcf20 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:33:43 +0000 Subject: [PATCH 16/25] fix(billing): check the signing key before the wallet lookup on charge A missing wallet writes a signed wallet_not_found audit event. With a key that cannot sign, that signature failed before the key check ran, so the caller got an unclassified error instead of the retryable 503. The check now runs right after the wallet id is resolved. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/routers/billing.py | 30 ++++++++++++--------- gateway/tests/test_signing_key_precharge.py | 25 +++++++++++++++++ 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/gateway/app/routers/billing.py b/gateway/app/routers/billing.py index 1a12d95ef..4db2c1767 100644 --- a/gateway/app/routers/billing.py +++ b/gateway/app/routers/billing.py @@ -666,6 +666,23 @@ async def charge_wallet( request_id = request.headers.get("X-Request-ID") endpoint = "/v1/billing/charge" + # Refuse before anything is looked up, begun or debited when this + # replica's signing key cannot sign: the charge's governance audit event is + # signed after the debit, and finding out there would leave a debit with no + # audit event and the idempotency key stuck in progress. The wallet lookup + # below also writes a signed audit event when the wallet is missing, so + # the check runs first. Nothing is recorded here, so the caller may retry + # the same key on a replica whose key can sign. A completed idempotent + # charge is not replayed from this replica either: the same key gets its + # recorded answer from a replica whose key can sign. + try: + await get_signing_key_service().assert_ready_to_sign() + except SigningKeyUnavailableError as exc: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail={"error": exc.reason}, + ) from exc + # Resolve after tenant authorization and before the idempotency row's FK. if not await money.get_wallet(wallet_id): await _record_billing_governance( @@ -688,19 +705,6 @@ async def charge_wallet( }, ) - # Refuse before anything is begun or debited when this replica's signing - # key cannot sign: the charge's governance audit event is signed after the - # debit, and finding out there would leave a debit with no audit event and - # the idempotency key stuck in progress. Nothing is recorded here, so the - # caller may retry the same key on a replica whose key can sign. - try: - await get_signing_key_service().assert_ready_to_sign() - except SigningKeyUnavailableError as exc: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail={"error": exc.reason}, - ) from exc - # Idempotency is opt-in via the Idempotency-Key header: a client that # retries a charge (e.g. after a timeout) with the same key gets the # original outcome replayed instead of being billed twice. diff --git a/gateway/tests/test_signing_key_precharge.py b/gateway/tests/test_signing_key_precharge.py index bdc48a8f9..9e56568ee 100644 --- a/gateway/tests/test_signing_key_precharge.py +++ b/gateway/tests/test_signing_key_precharge.py @@ -378,6 +378,31 @@ async def test_billing_charge_refuses_before_the_debit_and_the_key_stays_retryab assert await _debits(wallet_id) == debits_before + 1 +@pytest.mark.anyio +async def test_billing_charge_refuses_before_the_wallet_lookup( + client: AsyncClient, clean_database: None +) -> None: + """The wallet lookup writes a signed audit event when the wallet is missing. + + So the key check runs before it: an unknown wallet on a replica whose key + cannot sign gets the same retryable 503, not a failed audit signature. + """ + key = await get_signing_key_service().ensure_active_key() + url = "/v1/billing/charge?wallet_id=wal-does-not-exist-000000&service=agent_comms&units=1" + headers = {"X-API-Key": "test-key"} + await _set_key_status(key.key_id, "disabled") + + refused = await client.post(url, headers=headers) + + assert refused.status_code == 503, refused.text + assert refused.json()["detail"]["error"] == "signing_key_unavailable" + + await _set_key_status(key.key_id, "active") + missing = await client.post(url, headers=headers) + assert missing.status_code == 404, missing.text + assert missing.json()["detail"]["error"] == "wallet_not_found" + + @pytest.mark.anyio async def test_the_refusal_logs_its_underlying_reason_once( clean_database: None, caplog: pytest.LogCaptureFixture From 8dd9593abc9a4915cbb70e22a367a275235f5770 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:34:13 +0000 Subject: [PATCH 17/25] fix(health): log a failed signing key row read at warning Readiness still leaves a database outage to the postgres check, but a row read that fails for any other reason no longer disappears at debug level. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/core/health.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gateway/app/core/health.py b/gateway/app/core/health.py index 245a53fe5..1c766aeb7 100644 --- a/gateway/app/core/health.py +++ b/gateway/app/core/health.py @@ -506,7 +506,10 @@ async def _configured_key_row_problem() -> str | None: return "signing_key_id_public_key_mismatch" return None except Exception: - logger.debug("signing key row check raised", exc_info=True) + # Not reported down here (the postgres check owns a database outage), + # but never silent: a failure that is not the database would otherwise + # leave readiness "up" with no trace of why the row went unread. + logger.warning("signing key row check raised", exc_info=True) return None if status is None: return None From 5f8619c408a815634afc9d5cc1e6288b57152bea Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:34:13 +0000 Subject: [PATCH 18/25] test(health): pin the key material mismatch and the logged row read failure Readiness reports signing_key_id_public_key_mismatch for a replica whose key material does not match its key id's row, and leaves the row unchanged. A row read that raises is logged at warning. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/tests/test_signing_key_precharge.py | 50 +++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/gateway/tests/test_signing_key_precharge.py b/gateway/tests/test_signing_key_precharge.py index 9e56568ee..741437653 100644 --- a/gateway/tests/test_signing_key_precharge.py +++ b/gateway/tests/test_signing_key_precharge.py @@ -29,6 +29,7 @@ from app.db.models import LedgerEntryModel, ReceiptModel, SigningKeyModel from app.main import app from app.schemas.billing import ServiceCategory +from app.services import signing_keys as signing_keys_module from app.services.service_registry import get_service_registry from app.services.signing_keys import ( SigningKeyService, @@ -284,6 +285,55 @@ async def test_health_reports_an_unusable_key_row_without_changing_it( assert after.retired_at == before.retired_at +@pytest.mark.anyio +async def test_health_reports_a_key_row_bound_to_other_key_material( + client: AsyncClient, clean_database: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """A replica whose key material does not match its key id's row is down.""" + original = await get_signing_key_service().ensure_active_key() + misconfigured = SigningKeyService() + misconfigured._private_key = Ed25519PrivateKey.generate() + misconfigured._key_id = original.key_id + monkeypatch.setattr(signing_keys_module, "_signing_key_service", misconfigured) + + report = await gather_dependency_report() + signing_key = report["dependencies"]["signing_key"] + assert signing_key["status"] == "down", signing_key + assert signing_key["error"] == "signing_key_id_public_key_mismatch" + + ready = await client.get("/health/ready") + assert ready.status_code == 503, ready.text + assert ( + ready.json()["checks"]["signing_key"]["error"] + == "signing_key_id_public_key_mismatch" + ) + # The probe left the row as it found it. + row = await _key_row(original.key_id) + assert row.public_key_b64 == original.public_key_b64 + assert row.status == "active" + + +@pytest.mark.anyio +async def test_health_logs_a_key_row_read_that_fails( + clean_database: None, + caplog: pytest.LogCaptureFixture, + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def broken(self: SigningKeyService) -> None: + raise RuntimeError("row read failed") + + monkeypatch.setattr(SigningKeyService, "configured_key_status", broken) + with caplog.at_level("WARNING", logger="app.core.health"): + report = await gather_dependency_report() + + assert report["dependencies"]["signing_key"]["status"] == "up" + assert any( + record.levelname == "WARNING" + and record.getMessage() == "signing key row check raised" + for record in caplog.records + ), caplog.records + + @pytest.mark.anyio async def test_health_reports_a_usable_key_as_up( client: AsyncClient, clean_database: None From 86e3ab521d2a364784557eed4f84430bde3c7d26 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:34:38 +0000 Subject: [PATCH 19/25] docs(health): readiness checks the signing key; billing replays get 503 too The backup and restore runbook and SECURITY_LIMITATIONS.md still listed only the state store, MQTT and database checks for /health/ready. key-management.md now also says that the billing charge route's key check runs before an idempotent replay. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/SECURITY_LIMITATIONS.md | 3 ++- gateway/docs/backup-restore-runbook.md | 2 +- gateway/docs/key-management.md | 5 ++++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/gateway/SECURITY_LIMITATIONS.md b/gateway/SECURITY_LIMITATIONS.md index d6bde98fc..28c1b0852 100644 --- a/gateway/SECURITY_LIMITATIONS.md +++ b/gateway/SECURITY_LIMITATIONS.md @@ -263,7 +263,8 @@ missing control. or keyed, cannot consume the readiness budget. Readiness requests themselves can still exhaust the route-wide readiness bucket (ten times the per-client limit), and probes then receive 429 until the window resets. It is limited - rather than exempt because it runs state store, MQTT and database checks. + rather than exempt because it runs state store, MQTT, database and signing + key checks. `/health/dependencies` stays on the ordinary limits because it runs live Stripe and Sentinel probes. - **Namespaced buckets:** per-key and anonymous bucket names, and so their diff --git a/gateway/docs/backup-restore-runbook.md b/gateway/docs/backup-restore-runbook.md index 89a96bf4c..bfdc480e9 100644 --- a/gateway/docs/backup-restore-runbook.md +++ b/gateway/docs/backup-restore-runbook.md @@ -457,7 +457,7 @@ After backup, upgrade, restore, or rollback: | Check | What it proves | Source | | --- | --- | --- | | `GET /health` | Process up. Redis PING when `REDIS_URL` is set. Returns `commit_sha`, `build_provenance`, `tenant_rls_mode`. | `gateway/app/main.py` `/health`; Docker `HEALTHCHECK` in `gateway/Dockerfile` and `gateway/docker-compose.yml` | - | `GET /health/ready` | Durable state store, MQTT (or `not_used` when simulated), and database `SELECT 1`. Database not `up` is not ready. | `gateway/app/main.py` `/health/ready`; `gateway/app/core/health.py` `check_database_readiness` | + | `GET /health/ready` | Durable state store, MQTT (or `not_used` when simulated), database `SELECT 1`, and the signing key (key material loads and the configured key's row can sign). State store, MQTT or signing key `down`, or database not `up`, is not ready. | `gateway/app/main.py` `/health/ready`; `gateway/app/core/health.py` `check_database_readiness`, `check_signing_key_readiness` | | `GET /health/dependencies` | Postgres, Redis, signing key, upstream MCP, version and commit SHA (production posture). | `gateway/app/main.py` `/health/dependencies` | | `scripts/human_preflight.sh` | Unauthenticated GETs: `/health`, `/health/dependencies`, OpenAPI, agent manifest, catalogs. | `gateway/scripts/human_preflight.sh`; `gateway/docs/human-onboarding.md` Preflight script | diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index f54d217a1..72e80b7ef 100644 --- a/gateway/docs/key-management.md +++ b/gateway/docs/key-management.md @@ -265,7 +265,10 @@ If the configured key is disabled, bound to other key material, or otherwise cannot sign, the call is refused with `signing_key_unavailable` (JSON-RPC `-32005`, HTTP 409 on the REST invoke route, HTTP 503 on the AWI routes and on the billing charge route) and nothing is recorded, so the caller can retry the -same idempotency key on a replica whose key can sign. The underlying reason is +same idempotency key on a replica whose key can sign. On the billing charge +route the check also runs before an idempotent replay, so a key whose charge +already completed gets the same 503 from this replica and its recorded answer +from a replica whose key can sign. The underlying reason is logged once, as a `signing_key_unavailable cause=...` warning from `app.services.signing_keys`. A rotation that lands after that check and before the call finishes is not covered by it. From 7a924f9f150da70971d4e43c36d4024305129e70 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:37:25 +0000 Subject: [PATCH 20/25] refactor(trust): drop configured_key_status; list every readiness reason Readiness reads the key row through configured_key_problem, the rule signing uses, so configured_key_status had no caller left. key-management.md now names all four reasons readiness reports, including signing_key_status_invalid and an active row with retired_at set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/services/signing_keys.py | 16 ---------------- gateway/docs/key-management.md | 10 ++++++---- 2 files changed, 6 insertions(+), 20 deletions(-) diff --git a/gateway/app/services/signing_keys.py b/gateway/app/services/signing_keys.py index 8919c603e..d12259ec7 100644 --- a/gateway/app/services/signing_keys.py +++ b/gateway/app/services/signing_keys.py @@ -388,22 +388,6 @@ async def assert_ready_to_sign(self) -> None: ) raise SigningKeyUnavailableError(str(exc)) from exc - async def configured_key_status(self) -> str | None: - """Read the configured key's row status without writing anything. - - Returns ``None`` when no row exists yet (the first signature creates - it). Raises :class:`SigningKeyError` with - ``signing_key_id_public_key_mismatch`` when the row is bound to other - key material. Used by readiness reporting, which must not mutate state. - """ - - public_key_b64 = self._public_key_b64() - key = await self.get_public_key(self._key_id) - if key is None: - return None - self._assert_public_key_mapping(key, public_key_b64) - return key.status - async def configured_key_problem(self) -> str | None: """Why the configured key cannot sign, by the same rule signing uses. diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index 31884f4fa..ceac84c50 100644 --- a/gateway/docs/key-management.md +++ b/gateway/docs/key-management.md @@ -250,10 +250,12 @@ Rollout order: How an operator can tell a replica is stale: - `GET /health/ready` and `GET /health/dependencies` read the configured key's - row without writing it. A row that is `retired` or `disabled`, or that is - bound to other key material, reports `signing_key` as `down` with - `signing_key_retired`, `signing_key_disabled` or - `signing_key_id_public_key_mismatch`, and readiness answers 503. A load + row without writing it, by the same rule signing uses. A row that is + `retired` (or `active` with `retired_at` set), `disabled`, in a status the + gateway does not know, or bound to other key material reports `signing_key` + as `down` with `signing_key_retired`, `signing_key_disabled`, + `signing_key_status_invalid` or `signing_key_id_public_key_mismatch`, and + readiness answers 503. A load balancer that gates on readiness stops sending traffic to that replica. - Its governed calls are refused with `signing_key_unavailable`, and so is `GET /v1/signing-keys/active` (HTTP 503); the server log carries the From eef58b5b8cd4fe9a31e2b2573b6a3070943d3f93 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:04:12 +0000 Subject: [PATCH 21/25] test(refunds): pin the later-signed receipt's fields and the cleanup wiring Two tests the review asked for. A receipt signed later by sign_unsigned_pending is compared, column by column, with the receipt the signed path writes for the same wallet, permit and tool. Only the columns that name the individual call differ, and the later receipt links no audit event when the key was lost before the audit write (known limitation, now pinned). The application lifespan is run with the cleanup loop's wait shortened for one pass, and the pass must call sign_unsigned_pending. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- .../test_refund_reconciliation_unsigned.py | 161 +++++++++++++++++- 1 file changed, 159 insertions(+), 2 deletions(-) diff --git a/gateway/tests/test_refund_reconciliation_unsigned.py b/gateway/tests/test_refund_reconciliation_unsigned.py index 4b83c8cee..331560183 100644 --- a/gateway/tests/test_refund_reconciliation_unsigned.py +++ b/gateway/tests/test_refund_reconciliation_unsigned.py @@ -72,11 +72,12 @@ def key_lost_mid_call_tool(): retiring) the key after the call was admitted and charged. Then the tool fails, so the call goes down the refund path with no usable key. """ - state: dict[str, Any] = {"runs": 0, "key_id": None} + state: dict[str, Any] = {"runs": 0, "key_id": None, "lose_key": True} async def run() -> dict[str, Any]: state["runs"] += 1 - await _set_key_status(state["key_id"], "disabled") + if state["lose_key"]: + await _set_key_status(state["key_id"], "disabled") raise RuntimeError("tool exploded") get_service_registry().register_local( @@ -325,3 +326,159 @@ async def test_a_tampered_stored_payload_is_never_signed( assert after.response_reference is None assert after.response_json == tampered_json assert after.status_code == record.status_code + + +@pytest.mark.anyio +async def test_a_receipt_signed_later_carries_the_fields_the_signed_path_writes( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + """Signing later must not lose or change what the receipt says about the call. + + Two calls on the same wallet, permit and tool, both ending refund-failed. + The first keeps its key and gets its ``failed_unrefunded`` receipt on the + spot. The second loses its key, is recorded unsigned, and is signed by + ``sign_unsigned_pending``. Every receipt column that describes the call + is compared; only the columns that identify the individual call differ. + """ + state = key_lost_mid_call_tool + ctx = await provision_agent_wallet(client) + permit = await create_tool_permit( + client, + wallet_id=ctx["agent_wallet_id"], + key_id=ctx["key_id"], + tool_name=TOOL_NAME, + max_credits=10, + idem_key="refund-unsigned-fields-permit", + ) + state["key_id"] = (await get_signing_key_service().ensure_active_key()).key_id + + async def call(key: str) -> IdempotencyRecordModel: + body = { + "jsonrpc": "2.0", + "id": "call-fields", + "method": "tools/call", + "params": { + "name": TOOL_NAME, + "arguments": {}, + "mcpContext": { + "wallet_id": ctx["agent_wallet_id"], + "permit_id": permit["permit_id"], + "idempotency_key": key, + }, + }, + } + with patch( + "app.services.agent_money.AgentMoney.refund_charge", _failing_refund + ): + resp = await client.post( + "/mcp/messages", json=body, headers=ctx["agent_headers"] + ) + assert resp.json()["error"]["data"]["refund_reconciliation"]["status"] == ( + "pending" + ), resp.text + return await _record_for(key) + + state["lose_key"] = False + signed_record = await call("refund-unsigned-fields-signed") + assert signed_record.response_reference is not None + + state["lose_key"] = True + unsigned_record = await call("refund-unsigned-fields-later") + assert unsigned_record.response_reference is None + await _set_key_status(state["key_id"], "active") + assert await get_refund_reconciliation_service().sign_unsigned_pending() == (1, 0) + later_record = await _record_for("refund-unsigned-fields-later") + assert later_record.response_reference is not None + + async with get_session_factory()() as session: + on_the_spot = await session.get(ReceiptModel, signed_record.response_reference) + later = await session.get(ReceiptModel, later_record.response_reference) + assert on_the_spot is not None and later is not None + + # Columns that name the individual call, checked against that call. + per_call = { + "receipt_id", + "idempotency_record_id", + "ledger_entry_id", + "audit_event_id", + "request_hash", + "response_hash", + "created_at", + "signature", + } + same = set(ReceiptModel.model_fields) - per_call + assert { + "tool", + "key_id", + "counterparty", + "dispatch_attempt_id", + "approval_id", + "permit_id", + "wallet_id", + "outcome", + "reason_code", + "credits_authorized", + "credits_charged", + } <= same + differing = { + name: (getattr(on_the_spot, name), getattr(later, name)) + for name in sorted(same) + if getattr(on_the_spot, name) != getattr(later, name) + } + assert differing == {} + assert later.tool == TOOL_NAME + assert later.key_id == ctx["key_id"] + assert later.idempotency_record_id == later_record.record_id + assert later.ledger_entry_id == later_record.ledger_entry_id + assert later.request_hash == later_record.request_hash + # Known limitation: the key was + # lost before the pending audit event could be signed, so the later + # receipt links no audit event. The on-the-spot receipt links its own. + assert on_the_spot.audit_event_id is not None + assert later.audit_event_id is None + + +@pytest.mark.anyio +async def test_the_periodic_cleanup_runs_the_unsigned_signer( + clean_database: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """``sign_unsigned_pending`` only helps if the cleanup loop calls it. + + Runs the application lifespan with the loop's 300 second wait shortened to + nothing for one pass, and observes the signer being called. The signer is + replaced at class level so the pass itself is the thing under test. + """ + import asyncio + + import app.main as main_module + from app.services.refund_reconciliation import RefundReconciliationService + + called = asyncio.Event() + real_sleep = asyncio.sleep + long_waits = 0 + + async def one_pass_sleep(delay: float, result: Any = None) -> Any: + nonlocal long_waits + if delay >= 60: + long_waits += 1 + if long_waits > 1: + # Second wait of the loop: block until shutdown cancels it. + await asyncio.Event().wait() + return result + return await real_sleep(delay, result) + + async def observed(self: RefundReconciliationService, **_kwargs: Any): + called.set() + return (0, 0) + + async def no_upstream(settings: Any = None) -> None: + return None + + monkeypatch.setattr(main_module.asyncio, "sleep", one_pass_sleep) + monkeypatch.setattr(RefundReconciliationService, "sign_unsigned_pending", observed) + monkeypatch.setattr( + "app.services.upstream_mcp.register_configured_upstream_mcp", no_upstream + ) + + async with main_module.lifespan(main_module.app): + await asyncio.wait_for(called.wait(), timeout=10) From 9da448c0a7846cee2c9c71b27dd6f3391e86e80e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:13:29 +0000 Subject: [PATCH 22/25] fix(refunds): scan every unsigned pending refund once per pass sign_unsigned_pending selected the oldest `limit` unsigned records on each pass. Records it refuses stay unsigned (a refund that already landed and was released, a stored payload that no longer matches its hash), so once `limit` such records existed every pass selected the same ones and newer, signable records were never attempted. Those stayed out of the operator refund list. The pass now pages through all unsigned records in keyset order on (created_at, record_id) and advances past every record it has read, signed or not. The refusals themselves are unchanged, and the result is the total for the whole pass. Found by the Codex review on the pull request. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/services/refund_reconciliation.py | 223 ++++++++++-------- gateway/docs/failure-semantics.md | 4 +- .../test_refund_reconciliation_unsigned.py | 47 ++++ 3 files changed, 175 insertions(+), 99 deletions(-) diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index f1beec856..e7765fe8b 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -9,7 +9,7 @@ import logging from typing import Any, Literal, cast -from sqlalchemy import select, update as sa_update +from sqlalchemy import and_, or_, select, update as sa_update from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql.elements import ColumnElement @@ -572,117 +572,144 @@ async def attempt() -> dict[str, Any]: on_exhausted=lambda exc: RefundReconciliationContendedError(), ) - async def sign_unsigned_pending(self, *, limit: int = 50) -> tuple[int, int]: - """Sign the receipts of pending refunds recorded without one. - - Runs from the periodic cleanup on every replica. A replica whose key - cannot sign leaves each item as it is; one whose key can sign writes - the ``failed_unrefunded`` receipt and turns the item into an ordinary - pending work item (the same shape ``create_pending`` writes when it - can sign), which the operator list and ``retry`` then see. Concurrent - signers are safe: the checkpoint is re-read under a row lock and the - second signer finds it already signed. - - Returns ``(signed, still_unsigned)``. + @staticmethod + async def _unsigned_page( + *, after: tuple[Any, str] | None, limit: int + ) -> list[IdempotencyRecordModel]: + """One page of unsigned pending refunds, oldest first, after ``after``. + + Keyset order on ``(created_at, record_id)``, so a caller that advances + past every record it has seen never reads the same one twice in a pass, + whether or not that record could be signed. """ + created = cast(Any, IdempotencyRecordModel.created_at) + record_id = cast(Any, IdempotencyRecordModel.record_id) + conditions = [ + cast(Any, IdempotencyRecordModel.response_reference).is_(None), + cast(Any, IdempotencyRecordModel.response_json).contains( + f'"{UNSIGNED_RECEIPT_KEY}"' + ), + ] + if after is not None: + conditions.append( + or_( + created > after[0], + and_(created == after[0], record_id > after[1]), + ) + ) factory = get_session_factory() async with factory() as session: - records = ( + return list( ( await session.execute( select(IdempotencyRecordModel) - .where( - cast( - ColumnElement[bool], - cast( - Any, IdempotencyRecordModel.response_reference - ).is_(None), - ), - cast( - ColumnElement[bool], - cast( - Any, IdempotencyRecordModel.response_json - ).contains(f'"{UNSIGNED_RECEIPT_KEY}"'), - ), - ) - .order_by( - cast(ColumnElement[Any], IdempotencyRecordModel.created_at) - ) + .where(*conditions) + .order_by(created, record_id) .limit(limit) ) ) .scalars() .all() ) + + async def sign_unsigned_pending(self, *, limit: int = 50) -> tuple[int, int]: + """Sign the receipts of pending refunds recorded without one. + + Runs from the periodic cleanup on every replica. A replica whose key + cannot sign leaves each item as it is; one whose key can sign writes + the ``failed_unrefunded`` receipt and turns the item into an ordinary + pending work item (the same shape ``create_pending`` writes when it + can sign), which the operator list and ``retry`` then see. Concurrent + signers are safe: the checkpoint is re-read under a row lock and the + second signer finds it already signed. + + Every unsigned item is visited once per pass, in pages of ``limit``. + An item that is refused or cannot be signed stays unsigned and the scan + moves past it, so items that can never be signed (a refund that already + landed and was released, a payload that no longer matches its hash) + cannot keep newer items from being signed. + + Returns ``(signed, still_unsigned)`` for the whole pass. + """ + if limit < 1: + raise ValueError("limit must be positive") signed = 0 still_unsigned = 0 - for record in records: - marker = _unsigned_marker(record) - if marker is None: - continue - inputs = dict(marker["inputs"]) - if await self._refund_landed_and_budget_released(inputs): - # The money already came back and the permit reservation was - # already given back, by another path (for example a dispatch - # reconciler pass that ran before it learned to leave these - # items alone). A failed_unrefunded receipt would then claim a - # debt that no longer exists, and the operator retry would - # release the permit budget a second time. Leave it for an - # operator, loudly. - logger.error( - "refund_reconciliation_unsigned_already_refunded", - extra={ - "record_id": record.record_id, - "ledger_entry_id": inputs["ledger_entry_id"], - }, - ) - still_unsigned += 1 - continue - if sha256_hex(inputs["response_payload"]) != marker.get("response_hash"): - # The stored payload no longer hashes to what the caller's - # response was; signing it would sign a different response. - logger.error( - "refund_reconciliation_unsigned_payload_mismatch", - extra={"record_id": record.record_id}, - ) - still_unsigned += 1 - continue - try: - await self.create_pending( - wallet_id=inputs["wallet_id"], - endpoint=inputs["endpoint"], - idempotency_key=inputs["idempotency_key"], - permit_id=inputs["permit_id"], - key_id=inputs["key_id"], - tool_name=inputs["tool_name"], - request_payload=None, - request_hash=inputs["request_hash"], - ledger_entry_id=inputs["ledger_entry_id"], - credits_authorized=Decimal(inputs["credits_authorized"]), - credits_charged=Decimal(inputs["credits_charged"]), - audit_event_id=inputs["audit_event_id"], - reason=inputs["reason"], - dispatch_attempt_id=inputs["dispatch_attempt_id"], - approval_id=inputs["approval_id"], - response_payload=inputs["response_payload"], - response_hash_override=inputs["response_hash_override"], - counterparty=inputs["counterparty"], - _from_unsigned=True, - ) - except SigningKeyError: - still_unsigned += 1 - continue - except (RefundReconciliationError, RefundReconciliationContendedError): - # Signed concurrently by another replica, or contended: the - # next pass reads it again. - logger.info( - "refund_reconciliation_unsigned_skipped", - extra={"record_id": record.record_id}, - exc_info=True, - ) - still_unsigned += 1 - continue - signed += 1 + after: tuple[Any, str] | None = None + while True: + records = await self._unsigned_page(after=after, limit=limit) + if not records: + break + after = (records[-1].created_at, records[-1].record_id) + for record in records: + marker = _unsigned_marker(record) + if marker is None: + continue + inputs = dict(marker["inputs"]) + if await self._refund_landed_and_budget_released(inputs): + # The money already came back and the permit reservation was + # already given back, by another path (for example a dispatch + # reconciler pass that ran before it learned to leave these + # items alone). A failed_unrefunded receipt would then claim a + # debt that no longer exists, and the operator retry would + # release the permit budget a second time. Leave it for an + # operator, loudly. + logger.error( + "refund_reconciliation_unsigned_already_refunded", + extra={ + "record_id": record.record_id, + "ledger_entry_id": inputs["ledger_entry_id"], + }, + ) + still_unsigned += 1 + continue + if sha256_hex(inputs["response_payload"]) != marker.get( + "response_hash" + ): + # The stored payload no longer hashes to what the caller's + # response was; signing it would sign a different response. + logger.error( + "refund_reconciliation_unsigned_payload_mismatch", + extra={"record_id": record.record_id}, + ) + still_unsigned += 1 + continue + try: + await self.create_pending( + wallet_id=inputs["wallet_id"], + endpoint=inputs["endpoint"], + idempotency_key=inputs["idempotency_key"], + permit_id=inputs["permit_id"], + key_id=inputs["key_id"], + tool_name=inputs["tool_name"], + request_payload=None, + request_hash=inputs["request_hash"], + ledger_entry_id=inputs["ledger_entry_id"], + credits_authorized=Decimal(inputs["credits_authorized"]), + credits_charged=Decimal(inputs["credits_charged"]), + audit_event_id=inputs["audit_event_id"], + reason=inputs["reason"], + dispatch_attempt_id=inputs["dispatch_attempt_id"], + approval_id=inputs["approval_id"], + response_payload=inputs["response_payload"], + response_hash_override=inputs["response_hash_override"], + counterparty=inputs["counterparty"], + _from_unsigned=True, + ) + except SigningKeyError: + still_unsigned += 1 + continue + except (RefundReconciliationError, RefundReconciliationContendedError): + # Signed concurrently by another replica, or contended: the + # next pass reads it again. + logger.info( + "refund_reconciliation_unsigned_skipped", + extra={"record_id": record.record_id}, + exc_info=True, + ) + still_unsigned += 1 + continue + signed += 1 return signed, still_unsigned @staticmethod diff --git a/gateway/docs/failure-semantics.md b/gateway/docs/failure-semantics.md index 1d67bd596..126cc266e 100644 --- a/gateway/docs/failure-semantics.md +++ b/gateway/docs/failure-semantics.md @@ -378,7 +378,9 @@ inputs server side. The periodic cleanup on every replica runs `RefundReconciliationService.sign_unsigned_pending`: a replica whose key can sign writes the `failed_unrefunded` receipt and turns the item into an ordinary pending work item, which the operator list and retry then see; a -replica that cannot sign leaves it for the next pass. Until it is signed the +replica that cannot sign leaves it for the next pass. Each pass visits every +unsigned item once, oldest first, and moves past an item it refuses, so an +item that can never be signed does not keep newer ones waiting. Until it is signed the item does not appear in the operator list (`tests/test_refund_reconciliation_unsigned.py`). The unsigned item is the only owner of that debt: the dispatch reconciler skips an upstream attempt diff --git a/gateway/tests/test_refund_reconciliation_unsigned.py b/gateway/tests/test_refund_reconciliation_unsigned.py index 331560183..14fa47ba8 100644 --- a/gateway/tests/test_refund_reconciliation_unsigned.py +++ b/gateway/tests/test_refund_reconciliation_unsigned.py @@ -482,3 +482,50 @@ async def no_upstream(settings: Any = None) -> None: async with main_module.lifespan(main_module.app): await asyncio.wait_for(called.wait(), timeout=10) + + +@pytest.mark.anyio +async def test_an_item_that_can_never_be_signed_does_not_block_newer_items( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + """The scan moves past an item it refuses, within the same pass. + + The oldest unsigned item is made permanently unsignable (its stored + payload no longer matches its recorded hash). A newer item is signable. + With a page size of one, a scan that re-selected the oldest items on every + pass would never reach the newer one, which would then stay invisible to + the operator refund list for good. + """ + await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-blocked-old" + ) + old = await _record_for("refund-unsigned-blocked-old") + stored = json.loads(old.response_json or "{}") + stored[UNSIGNED_RECEIPT_KEY]["inputs"]["response_payload"] = { + "error": "not what the caller was told" + } + async with get_session_factory()() as session: + row = await session.get(IdempotencyRecordModel, old.record_id) + assert row is not None + row.response_json = json.dumps(stored) + session.add(row) + await session.commit() + + # The first call disabled the key; the second call needs it to be admitted. + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-blocked-new" + ) + new = await _record_for("refund-unsigned-blocked-new") + assert (old.created_at, old.record_id) < (new.created_at, new.record_id) + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending(limit=1) == (1, 1) + + assert (await _record_for("refund-unsigned-blocked-old")).response_reference is None + signed = await _record_for("refund-unsigned-blocked-new") + assert signed.response_reference is not None + assert UNSIGNED_RECEIPT_KEY not in json.loads(signed.response_json or "{}") + # The blocked item is still counted on every later pass, never signed. + assert await service.sign_unsigned_pending(limit=1) == (0, 1) From 0c3790ae8fd1c7724d983e31d4bc634e86dc4a32 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 10:27:13 +0000 Subject: [PATCH 23/25] fix(refunds): only a charged record is an unsigned pending refund The signer's page query and the dispatch reconciler's skip recognized an unsigned pending refund by its marker name in the stored response text. A caller chooses text that other stored responses repeat. Under the shipped trust flags, a call to a tool that is not registered, made on /mcp/messages or the REST invoke route with an idempotency key and no permit, has its record completed with "Tool not found: " and is not charged. With a name such as x"unsigned_receipt the stored text contains the marker name in quotes, so that record was on a page of every signing pass on every replica, where it was read, parsed and dropped. One wallet key could grow the cost of every pass at no charge. The underscore is a LIKE wildcard, so a name with another character in its place matched too. An unsigned pending refund is only recorded on a charged record with no receipt reference, so both queries now require that, and the text match is escaped. The reconciler's condition keeps each test separate so that a NULL response_json still leaves the attempt listed. Each page after the first is also bounded below by the last created_at read. The keyset condition already implied it; stating it lets the database seek into the created_at index instead of reading it from the oldest record for every page. No record the gateway writes can tell the escaped match from the plain one, the reconciler's three tests from the single one it had, or a page with the bound from one without it. The two new tests therefore also check the statements that are sent. failure-semantics.md said that a replay returns the same answer and that the operator retry refunds, in a paragraph whose example is a disabled key. While the signing key that signed the call's permit is disabled, the replay is refused before the stored answer is served, and a retry of the pending item refuses. Both sentences now say so. Found by the review of the pull request (items 2 and 3) and by the checks run on it afterwards. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/services/mcp_dispatch_attempts.py | 13 +- gateway/app/services/refund_reconciliation.py | 16 +- gateway/docs/failure-semantics.md | 10 +- .../test_refund_reconciliation_unsigned.py | 273 +++++++++++++++++- 4 files changed, 303 insertions(+), 9 deletions(-) diff --git a/gateway/app/services/mcp_dispatch_attempts.py b/gateway/app/services/mcp_dispatch_attempts.py index 78778261e..a49df3459 100644 --- a/gateway/app/services/mcp_dispatch_attempts.py +++ b/gateway/app/services/mcp_dispatch_attempts.py @@ -2149,13 +2149,22 @@ async def list_unfinalized_terminal_contexts( # owned by sign_unsigned_pending and the operator # retry, exactly as a signed failed_unrefunded receipt # is: compensating it here as well could refund money - # that the unsigned item still lists as owed. + # that the unsigned item still lists as owed. Only a + # charged record with no receipt reference can be such + # an item, so no other attempt is left out, whatever + # text its stored response contains. Each test stands + # alone so that a NULL response_json keeps the attempt + # listed. or_( cast(Any, IdempotencyRecordModel.response_json).is_(None), + cast(Any, IdempotencyRecordModel.response_reference).is_not( + None + ), + cast(Any, IdempotencyRecordModel.ledger_entry_id).is_(None), not_( cast( Any, IdempotencyRecordModel.response_json - ).contains(f'"{UNSIGNED_RECEIPT_KEY}"') + ).contains(f'"{UNSIGNED_RECEIPT_KEY}"', autoescape=True) ), ), ) diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index e7765fe8b..02b8b7062 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -581,16 +581,30 @@ async def _unsigned_page( Keyset order on ``(created_at, record_id)``, so a caller that advances past every record it has seen never reads the same one twice in a pass, whether or not that record could be signed. + + An unsigned pending refund is only ever recorded on a charged record + with no receipt reference (``create_pending`` validates that checkpoint + first), so the page asks for exactly that before it looks at the stored + text. The text alone is not enough: a caller chooses text that other + stored responses repeat, for example the tool name in a ``Tool not + found`` denial, which the shipped trust flags record at no charge. The + match is escaped because ``_`` is a LIKE wildcard. + + The lower bound on ``created_at`` repeats what the keyset condition + already implies. It lets the database seek into the ``created_at`` + index instead of reading it from the oldest record on every page. """ created = cast(Any, IdempotencyRecordModel.created_at) record_id = cast(Any, IdempotencyRecordModel.record_id) conditions = [ cast(Any, IdempotencyRecordModel.response_reference).is_(None), + cast(Any, IdempotencyRecordModel.ledger_entry_id).is_not(None), cast(Any, IdempotencyRecordModel.response_json).contains( - f'"{UNSIGNED_RECEIPT_KEY}"' + f'"{UNSIGNED_RECEIPT_KEY}"', autoescape=True ), ] if after is not None: + conditions.append(created >= after[0]) conditions.append( or_( created > after[0], diff --git a/gateway/docs/failure-semantics.md b/gateway/docs/failure-semantics.md index 126cc266e..9233a19bf 100644 --- a/gateway/docs/failure-semantics.md +++ b/gateway/docs/failure-semantics.md @@ -372,8 +372,10 @@ If the receipt cannot be signed at that moment (the signing key became unusable after the call was admitted, for example it was disabled), the work item is still recorded, without a receipt: the caller gets the same 500 / `-32603` answer with `refund_reconciliation.status` `pending`, `receipt_id` -`null` and `receipt_status` `unsigned`, and a replay of the same key returns -the same answer without running the tool. The stored record keeps the receipt +`null` and `receipt_status` `unsigned`, and a replay of the same key never +runs the tool again; it is refused or given the stored answer, and it is +always refused while the signing key that signed the call's permit is +`disabled`. The stored record keeps the receipt inputs server side. The periodic cleanup on every replica runs `RefundReconciliationService.sign_unsigned_pending`: a replica whose key can sign writes the `failed_unrefunded` receipt and turns the item into an @@ -385,7 +387,9 @@ item does not appear in the operator list (`tests/test_refund_reconciliation_unsigned.py`). The unsigned item is the only owner of that debt: the dispatch reconciler skips an upstream attempt whose record carries it, as it skips one with a signed `failed_unrefunded` -receipt, so the money is refunded once, through the operator retry. If a +receipt, so the money is refunded once, through the operator retry, and a +retry of the pending item refuses while the signing key that signed the +call's permit is `disabled`. If a refund for the charge is already in the ledger and its permit reservation is still held (the live path refunded, then failed to record the refund on the dispatch attempt), the signer signs as usual and logs diff --git a/gateway/tests/test_refund_reconciliation_unsigned.py b/gateway/tests/test_refund_reconciliation_unsigned.py index 14fa47ba8..871e3443a 100644 --- a/gateway/tests/test_refund_reconciliation_unsigned.py +++ b/gateway/tests/test_refund_reconciliation_unsigned.py @@ -17,16 +17,25 @@ from __future__ import annotations +import base64 +from collections.abc import Iterator +from contextlib import contextmanager from decimal import Decimal import json from typing import Any from unittest.mock import patch import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, +) from httpx import ASGITransport, AsyncClient -from sqlalchemy import func, select +from sqlalchemy import event, func, select -from app.db.database import get_session_factory +from app.db.database import get_engine, get_session_factory from app.db.models import ( IdempotencyRecordModel, LedgerEntryModel, @@ -34,10 +43,13 @@ SigningKeyModel, ) from app.main import app +from app.routers import mcp as mcp_router from app.routers.mcp import INTERNAL_ERROR_MESSAGE from app.schemas.billing import ServiceCategory +from app.services.mcp_dispatch_attempts import get_mcp_dispatch_attempt_service from app.services.refund_reconciliation import ( UNSIGNED_RECEIPT_KEY, + RefundReconciliationService, get_refund_reconciliation_service, ) from app.services.service_registry import get_service_registry @@ -451,7 +463,6 @@ async def test_the_periodic_cleanup_runs_the_unsigned_signer( import asyncio import app.main as main_module - from app.services.refund_reconciliation import RefundReconciliationService called = asyncio.Event() real_sleep = asyncio.sleep @@ -529,3 +540,259 @@ async def test_an_item_that_can_never_be_signed_does_not_block_newer_items( assert UNSIGNED_RECEIPT_KEY not in json.loads(signed.response_json or "{}") # The blocked item is still counted on every later pass, never signed. assert await service.sign_unsigned_pending(limit=1) == (0, 1) + + +@contextmanager +def _statements_sent() -> Iterator[list[str]]: + """Collect the text of every statement the engine is sent while open.""" + engine = get_engine() + assert engine is not None + sent: list[str] = [] + + def note( + _conn: Any, + _cursor: Any, + statement: str, + _parameters: Any, + _context: Any, + _executemany: bool, + ) -> None: + sent.append(statement) + + event.listen(engine.sync_engine, "before_cursor_execute", note) + try: + yield sent + finally: + event.remove(engine.sync_engine, "before_cursor_execute", note) + + +@pytest.fixture +def strict_trust_mode(monkeypatch: pytest.MonkeyPatch) -> None: + """The shipped trust flags, which the suite's conftest relaxes. + + Under the relaxed flags the denial of a call without a permit is not + stored. A deployment in trust mode has a configured signing key, so one is + generated here, as ``strict_trust_mode`` in test_mcp_trust_mode does. The + signing service drops the key it had loaded and takes the configured id. + """ + raw_private_key = Ed25519PrivateKey.generate().private_bytes( + Encoding.Raw, PrivateFormat.Raw, NoEncryption() + ) + monkeypatch.setattr(mcp_router.settings, "TRUST_MODE_ENABLED", True) + monkeypatch.setattr(mcp_router.settings, "ALLOW_LEGACY_UNPERMITTED_MCP", False) + monkeypatch.setattr( + mcp_router.settings, + "TRUST_SIGNING_PRIVATE_KEY_B64", + base64.b64encode(raw_private_key).decode(), + ) + signing_keys = get_signing_key_service() + monkeypatch.setattr(signing_keys, "_private_key", None) + monkeypatch.setattr( + signing_keys, "_key_id", mcp_router.settings.TRUST_SIGNING_KEY_ID + ) + + +async def _record_of_a_call_to_an_unregistered_tool( + client: AsyncClient, ctx: dict[str, Any], *, tool_name: str, key: str +) -> IdempotencyRecordModel: + """Call a tool nobody registered and return the record of the denial. + + The call carries an idempotency key and no permit. It needs + ``strict_trust_mode``: under the suite's relaxed flags nothing is stored. + """ + resp = await client.post( + "/mcp/messages", + json={ + "jsonrpc": "2.0", + "id": f"call-{key}", + "method": "tools/call", + "params": { + "name": tool_name, + "arguments": {}, + "mcpContext": { + "wallet_id": ctx["agent_wallet_id"], + "idempotency_key": key, + }, + }, + }, + headers=ctx["agent_headers"], + ) + assert resp.json()["error"]["message"] == "Tool not found", resp.text + record = await _record_for(key) + # What the gateway stored: a completed denial that repeats the caller's + # tool name, with no charge and no receipt. + assert json.loads(record.response_json or "{}")["error"] == ( + f"Tool not found: {tool_name}" + ) + assert record.ledger_entry_id is None + assert record.response_reference is None + return record + + +@pytest.mark.anyio +async def test_a_denial_that_repeats_the_marker_name_is_not_an_unsigned_item( + client: AsyncClient, + clean_database: None, + strict_trust_mode: None, + key_lost_mid_call_tool, +) -> None: + """Only a charged record can be an unsigned pending refund. + + A call to a tool that is not registered, made with an idempotency key and + no permit, is completed with ``Tool not found: `` and is not charged. + The caller picks the name, so the stored text can contain the marker's + name in quotes, which is the text the signer's page looks for. Such a + record used to be on a page of every pass on every replica, to be read, + parsed and dropped, so one wallet key could grow the cost of every pass at + no charge. ``_`` is a LIKE wildcard, so a name with any other character in + its place was returned as well. + + Under the shipped trust flags, one denial of each kind is stored on either + side of a real unsigned item. The page holds the real item alone, the pass + signs it, and the denials are left as they were. + + Both denials are uncharged, so the charge test alone keeps them off the + page, and neither has a dispatch attempt for the reconciler to look at. No + record the gateway writes can tell the escaped match from the plain one, + or the reconciler's three tests from the single one it had, so the two + statements are checked as well: the page escapes its match, and the + reconciler leaves an attempt out only on the same three tests, each a + separate alternative. + """ + state = key_lost_mid_call_tool + caller = await provision_agent_wallet(client) + + # The name ends the stored JSON string, so that string's closing quote + # completes the marker's name in quotes. + exact = await _record_of_a_call_to_an_unregistered_tool( + client, + caller, + tool_name=f'x"{UNSIGNED_RECEIPT_KEY}', + key="refund-unsigned-denied-exact", + ) + assert f'"{UNSIGNED_RECEIPT_KEY}"' in (exact.response_json or "") + + await _run_call_that_loses_its_key( + client, state, key="refund-unsigned-among-denials" + ) + real = await _record_for("refund-unsigned-among-denials") + assert real.ledger_entry_id is not None + assert UNSIGNED_RECEIPT_KEY in json.loads(real.response_json or "{}") + # That call disabled the key; the rest of the test needs it usable again. + await _set_key_status(state["key_id"], "active") + + one_character_off = UNSIGNED_RECEIPT_KEY.replace("_", "X") + wildcard = await _record_of_a_call_to_an_unregistered_tool( + client, + caller, + tool_name=f'x"{one_character_off}', + key="refund-unsigned-denied-wildcard", + ) + assert f'"{one_character_off}"' in (wildcard.response_json or "") + assert f'"{UNSIGNED_RECEIPT_KEY}"' not in (wildcard.response_json or "") + + in_scan_order = [ + (record.created_at, record.record_id) for record in (exact, real, wildcard) + ] + assert in_scan_order == sorted(in_scan_order) + + with _statements_sent() as sent: + page = await RefundReconciliationService._unsigned_page(after=None, limit=50) + await get_mcp_dispatch_attempt_service().list_unfinalized_terminal_contexts( + idle_seconds=0 + ) + assert [record.record_id for record in page] == [real.record_id] + matching = [statement for statement in sent if " LIKE " in statement] + assert len(matching) == 2, sent + page_statement, reconciler_statement = matching + assert " NOT LIKE " not in page_statement + assert " ESCAPE " in page_statement + for alternative in ( + "response_json IS NULL OR ", + "response_reference IS NOT NULL OR ", + "ledger_entry_id IS NULL OR ", + ): + assert alternative in reconciler_statement, reconciler_statement + assert " NOT LIKE " in reconciler_statement + assert " ESCAPE " in reconciler_statement + + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending(limit=1) == (1, 0) + signed = await _record_for("refund-unsigned-among-denials") + assert signed.response_reference is not None + for denial in (exact, wildcard): + unchanged = await _record_for(denial.idempotency_key) + assert unchanged.response_json == denial.response_json + assert unchanged.response_reference is None + assert await service.sign_unsigned_pending(limit=1) == (0, 0) + + +@pytest.mark.anyio +async def test_a_pass_reads_items_recorded_at_the_same_instant_once_each( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + """Paging stays exact when unsigned items share a ``created_at``. + + Each page after the first is bounded below by the last ``created_at`` the + scan has read, so the database can seek into the ``created_at`` index, and + a tie on that instant is broken on ``record_id``. A bound that left the + instant itself out would skip the items that share it. Five unsigned items + are recorded and the middle three are given the same ``created_at``. Pages + of one, two and fifty then read every item exactly once, in order, and one + pass signs them all. The bound changes no result, so the statements are + checked for it as well. + """ + state = key_lost_mid_call_tool + keys = [f"refund-unsigned-tied-{index}" for index in range(5)] + for key in keys: + await _run_call_that_loses_its_key(client, state, key=key) + # Each call disabled the key; the next call and the signing pass need it. + await _set_key_status(state["key_id"], "active") + + recorded = [await _record_for(key) for key in keys] + # The injected condition: three records written in the same instant. + tied_at = recorded[2].created_at + async with get_session_factory()() as session: + for record in (recorded[1], recorded[3]): + row = await session.get(IdempotencyRecordModel, record.record_id) + assert row is not None + row.created_at = tied_at + session.add(row) + await session.commit() + recorded = [await _record_for(key) for key in keys] + assert [record.created_at for record in recorded[1:4]] == [tied_at] * 3 + assert recorded[0].created_at < tied_at < recorded[4].created_at + expected = [ + record.record_id + for record in sorted( + recorded, key=lambda record: (record.created_at, record.record_id) + ) + ] + + async def read_every_page(limit: int) -> list[str]: + seen: list[str] = [] + after: tuple[Any, str] | None = None + while True: + page = await RefundReconciliationService._unsigned_page( + after=after, limit=limit + ) + if not page: + return seen + assert len(page) <= limit + seen.extend(record.record_id for record in page) + # A page that stops advancing fails here; it does not hang. + assert len(seen) <= len(expected), limit + after = (page[-1].created_at, page[-1].record_id) + + for limit in (2, 50): + assert await read_every_page(limit) == expected, limit + with _statements_sent() as sent: + assert await read_every_page(1) == expected + pages = [statement for statement in sent if " LIKE " in statement] + assert len(pages) == len(expected) + 1, sent + assert "created_at >= " not in pages[0] + assert all("created_at >= " in statement for statement in pages[1:]), pages + + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending(limit=2) == (5, 0) + assert await service.sign_unsigned_pending(limit=2) == (0, 0) From c82007485a606e210205dce9d4bb28b8c33fa49a Mon Sep 17 00:00:00 2001 From: PetrefiedThunder <131207452+PetrefiedThunder@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:50:25 -0800 Subject: [PATCH 24/25] docs: say receipt ID and drop exactly-once claims --- gateway/app/services/mcp_dispatch_attempts.py | 2 +- gateway/app/services/refund_reconciliation.py | 2 +- gateway/tests/test_mcp_upstream_governed.py | 4 ++-- gateway/tests/test_refund_reconciliation_unsigned.py | 4 ++-- gateway/tests/test_signing_key_precharge.py | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/gateway/app/services/mcp_dispatch_attempts.py b/gateway/app/services/mcp_dispatch_attempts.py index a49df3459..a6652c97f 100644 --- a/gateway/app/services/mcp_dispatch_attempts.py +++ b/gateway/app/services/mcp_dispatch_attempts.py @@ -2144,7 +2144,7 @@ async def list_unfinalized_terminal_contexts( ColumnElement[bool], cast(Any, ReceiptModel.receipt_id).is_(None), ), - # A pending refund recorded without a signed receipt + # A pending refund recorded without a receipt ID # (RefundReconciliationService.create_pending) is # owned by sign_unsigned_pending and the operator # retry, exactly as a signed failed_unrefunded receipt diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index 02b8b7062..b4538ea5d 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -213,7 +213,7 @@ async def create_pending( request_hash: str | None = None, _from_unsigned: bool = False, ) -> tuple[ReceiptResponse | None, dict[str, Any]]: - """Atomically insert the signed receipt and durable pending work item. + """Atomically insert the receipt ID and durable pending work item. When the receipt cannot be signed (any ``SigningKeyError`` that is not the one restart reason, for example a key retired or disabled after diff --git a/gateway/tests/test_mcp_upstream_governed.py b/gateway/tests/test_mcp_upstream_governed.py index 60697dc5d..00596fd6e 100644 --- a/gateway/tests/test_mcp_upstream_governed.py +++ b/gateway/tests/test_mcp_upstream_governed.py @@ -3491,7 +3491,7 @@ async def test_dispatch_reconciler_leaves_an_unsigned_pending_refund_to_its_owne retry either failed forever (budget conflict) or, with an earlier paid call on the same permit, released that call's budget too, so the permit under-counted. Now the reconciler skips the attempt like it skips a signed - failed_unrefunded receipt, and the refund happens exactly once, through + failed_unrefunded receipt, and the refund is recorded as one ledger entry, through the operator retry. """ case = await _upstream_refund_failure_with_key_lost( @@ -3595,7 +3595,7 @@ async def test_unsigned_item_whose_refund_landed_unacknowledged_is_signed_and_re dispatch sweep skips an attempt whose refund was never checkpointed while its debit stands. The signer must therefore not refuse this item just because a refund row exists. Signed, the operator retry finds the refund - row, refunds nothing more, and releases the reservation exactly once. + row, refunds nothing more, and releases the reservation in that retry. """ case = await _upstream_refund_failure_with_key_lost( client, diff --git a/gateway/tests/test_refund_reconciliation_unsigned.py b/gateway/tests/test_refund_reconciliation_unsigned.py index 871e3443a..f7a8083b3 100644 --- a/gateway/tests/test_refund_reconciliation_unsigned.py +++ b/gateway/tests/test_refund_reconciliation_unsigned.py @@ -267,7 +267,7 @@ async def test_a_replica_that_can_sign_completes_the_item_and_it_can_be_refunded assert [item.receipt_id for item in items] == [record.response_reference] assert await get_receipt_service_verifies(record.response_reference) - # And the operator retry refunds it exactly once. + # And the operator retry refunds that charged row and no additional row. item, already = await service.retry(record.response_reference) assert item.status == "resolved" assert already is False @@ -738,7 +738,7 @@ async def test_a_pass_reads_items_recorded_at_the_same_instant_once_each( a tie on that instant is broken on ``record_id``. A bound that left the instant itself out would skip the items that share it. Five unsigned items are recorded and the middle three are given the same ``created_at``. Pages - of one, two and fifty then read every item exactly once, in order, and one + of one, two and fifty then read each item one time, in order, and one pass signs them all. The bound changes no result, so the statements are checked for it as well. """ diff --git a/gateway/tests/test_signing_key_precharge.py b/gateway/tests/test_signing_key_precharge.py index 08fd4a473..3976af1e1 100644 --- a/gateway/tests/test_signing_key_precharge.py +++ b/gateway/tests/test_signing_key_precharge.py @@ -1,7 +1,7 @@ """A replica whose signing key cannot sign refuses before it charges. -Every governed outcome past the charge needs a signed audit event and a signed -receipt. When the configured key cannot sign (its row is disabled, retired or +Every governed outcome past the charge needs a signed audit event and a +receipt ID. When the configured key cannot sign (its row is disabled, retired or bound to other key material) the old order was: reserve, charge, run the tool, then fail to sign. The wallet was debited and the tool had run, but nothing recorded either, and the idempotency record stayed in progress for manual From 6af04421c0900c7808b3d84328ae8f12dfc6b7cd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 22:59:28 +0000 Subject: [PATCH 25/25] docs(refunds): do not promise the refund of an unsigned pending item failure-semantics.md said that for an unsigned pending refund "the money is refunded once, through the operator retry". The code does not keep that promise in every case, so the paragraph now states what the code does: - The dispatch reconciler's skip applies where an attempt is picked up: its list queries filter on the stored item, and a replay that finds a stored answer does not reconcile. A reconcile that picked up the attempt before the item was recorded does not check the record for the item and can still refund the charge. On a replica that can sign it then replaces the item. - Every refund writer uses the ledger key refund-{ledger_entry_id}, so the charge is refunded at most once. - The operator retry checks the permit signature before it writes anything. When it finds the signing key that signed the permit `disabled` it answers 409 refund_reconciliation_permit_invalid: no refund, no reservation release, and the item is still pending. This also holds when the live path already made the refund. - Only an operator starts that retry, so such an item has no automatic resolution. The _record_unsigned_pending docstring said a replay "returns the same pending answer". A replay is refused or given the stored answer, and the stored answer is not always the pending one, so the docstring now says that and points to the document. Text only. No behavior change. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GyhDYG6Zjfjta9mLD2UfhQ Signed-off-by: Claude --- gateway/app/services/refund_reconciliation.py | 4 ++-- gateway/docs/failure-semantics.md | 18 ++++++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index b4538ea5d..404e8c6c2 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -528,8 +528,8 @@ async def _record_unsigned_pending( of the response payload as it was handed in, so signing later can refuse a payload the JSON round trip changed instead of signing a different hash. The record is completed with status 500, so a replay - of the same key returns the same pending answer and never runs the - tool again. + of the same key never runs the tool again; it is refused or given + the stored answer (docs/failure-semantics.md). """ factory = get_session_factory() diff --git a/gateway/docs/failure-semantics.md b/gateway/docs/failure-semantics.md index 9233a19bf..990d9cea6 100644 --- a/gateway/docs/failure-semantics.md +++ b/gateway/docs/failure-semantics.md @@ -384,12 +384,18 @@ replica that cannot sign leaves it for the next pass. Each pass visits every unsigned item once, oldest first, and moves past an item it refuses, so an item that can never be signed does not keep newer ones waiting. Until it is signed the item does not appear in the operator list -(`tests/test_refund_reconciliation_unsigned.py`). The unsigned item is the -only owner of that debt: the dispatch reconciler skips an upstream attempt -whose record carries it, as it skips one with a signed `failed_unrefunded` -receipt, so the money is refunded once, through the operator retry, and a -retry of the pending item refuses while the signing key that signed the -call's permit is `disabled`. If a +(`tests/test_refund_reconciliation_unsigned.py`). The unsigned item then +owns that debt: the dispatch reconciler skips an upstream attempt whose +record carries it, as it skips one with a signed `failed_unrefunded` +receipt, so no reconcile that picks up the attempt after the item is +recorded refunds that charge. A refund still owed then is left to the +operator retry, unless a reconcile that picked up the attempt before then +makes it first, and the money is refunded at most once. A retry of the +pending item that finds the signing key that signed the call's permit +`disabled` refuses, also in the case described next: it refunds nothing, +releases no reservation and leaves the item pending. Unless such an +earlier reconcile settles the charge and replaces the item, that item has +no automatic resolution and needs an operator. If a refund for the charge is already in the ledger and its permit reservation is still held (the live path refunded, then failed to record the refund on the dispatch attempt), the signer signs as usual and logs