diff --git a/gateway/SECURITY_LIMITATIONS.md b/gateway/SECURITY_LIMITATIONS.md index 7efd84f24..5f9299ab6 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/app/core/health.py b/gateway/app/core/health.py index 0338d79bc..602d68c35 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,39 @@ async def _check_signing_key() -> dict[str, Any]: return {"status": "up", "state": "loaded"} +async def _configured_key_row_problem() -> str | None: + """Read the configured key's row and name why it cannot sign, if it cannot. + + 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: + return await get_signing_key_service().configured_key_problem() + except Exception: + # 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 + + +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, 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) + + 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 d2bfca547..9d18f1bf2 100644 --- a/gateway/app/main.py +++ b/gateway/app/main.py @@ -41,6 +41,7 @@ build_public_dependency_report, check_redis_liveness, check_database_readiness, + check_signing_key_readiness, check_mqtt_readiness, gather_dependency_report, ) @@ -299,6 +300,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, @@ -392,6 +396,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 @@ -1338,6 +1355,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/billing.py b/gateway/app/routers/billing.py index 9b6b3202e..59847aa5b 100644 --- a/gateway/app/routers/billing.py +++ b/gateway/app/routers/billing.py @@ -44,6 +44,10 @@ InvalidIdempotencyKeyError, ) 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 ( @@ -669,6 +673,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( 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/app/routers/mcp.py b/gateway/app/routers/mcp.py index 16c1d24b4..cc7e0f630 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, @@ -461,6 +463,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", ) } @@ -473,6 +476,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", @@ -850,7 +854,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 @@ -1203,6 +1212,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( @@ -3186,7 +3201,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), @@ -4543,9 +4569,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 @@ -4587,6 +4618,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 @@ -5256,6 +5294,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"), @@ -5420,8 +5459,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 8c3fd92a3..be18c7aa9 100644 --- a/gateway/app/routers/mcp_standard.py +++ b/gateway/app/routers/mcp_standard.py @@ -82,6 +82,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 @@ -740,6 +744,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 @@ -846,6 +859,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 c4ae202dc..96fbc39e6 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__) @@ -455,6 +460,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/mcp_dispatch_attempts.py b/gateway/app/services/mcp_dispatch_attempts.py index fd3780b49..a6652c97f 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,29 @@ async def list_unfinalized_terminal_contexts( ColumnElement[bool], cast(Any, ReceiptModel.receipt_id).is_(None), ), + # 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 + # is: compensating it here as well could refund money + # 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}"', autoescape=True) + ), + ), ) .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 8edbaa4a4..8cc8f6d1a 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -6,9 +6,10 @@ 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 +from sqlalchemy import and_, or_, select, update as sa_update from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql.elements import ColumnElement @@ -29,12 +30,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.""" @@ -81,7 +115,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, @@ -165,7 +199,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, @@ -176,8 +210,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 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 + 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, @@ -204,12 +253,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( @@ -304,6 +363,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, @@ -353,12 +413,319 @@ 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 + + @staticmethod + 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 = ( + 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 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, + *, + 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 never runs the tool again; it is refused or given + the stored answer (docs/failure-semantics.md). + """ + 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, ) + @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. + + 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}"', autoescape=True + ), + ] + if after is not None: + conditions.append(created >= after[0]) + conditions.append( + or_( + created > after[0], + and_(created == after[0], record_id > after[1]), + ) + ) + factory = get_session_factory() + async with factory() as session: + return list( + ( + await session.execute( + select(IdempotencyRecordModel) + .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 + 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 def _decode_response(record: IdempotencyRecordModel) -> dict[str, Any]: try: diff --git a/gateway/app/services/signing_keys.py b/gateway/app/services/signing_keys.py index efcd56653..d12259ec7 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,10 +27,32 @@ from app.db.models import SigningKeyModel +logger = logging.getLogger(__name__) + + 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, @@ -274,6 +298,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() @@ -284,26 +333,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: @@ -320,9 +364,51 @@ 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: + """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: + # 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_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/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/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/failure-semantics.md b/gateway/docs/failure-semantics.md index 8695faab4..8d4055776 100644 --- a/gateway/docs/failure-semantics.md +++ b/gateway/docs/failure-semantics.md @@ -371,6 +371,44 @@ 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 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 +ordinary pending work item, which the operator list and retry then see; a +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 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 +`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 1. **Post-dispatch ambiguity is never resolved automatically.** No retry, no diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index 8b1898a2a..ceac84c50 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,32 @@ 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`; + 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. +- 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,29 +244,61 @@ 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. - -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 -(`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 -in [issue 280](https://github.com/agentmiddleware/agent-middleware/issues/280). +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: + +- `GET /health/ready` and `GET /health/dependencies` read the configured key's + 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 + 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`), 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 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 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. 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 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 should be the default answer to "where do the private keys live?" until the diff --git a/gateway/docs/openapi.json b/gateway/docs/openapi.json index ace858d7f..27e710fad 100644 --- a/gateway/docs/openapi.json +++ b/gateway/docs/openapi.json @@ -4357,7 +4357,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_awi_http_governance.py b/gateway/tests/test_awi_http_governance.py index f2f24a9cd..bda76e7f6 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,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 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, @@ -789,3 +792,74 @@ 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 +): + """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", + ) + 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, + "X-Permit-Id": permit["permit_id"], + "Idempotency-Key": "awi-http-signing-precharge-1", + } + debits_before = await _wallet_debits(wallet_id) + 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 + + # 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 + ) + 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_mcp_upstream_governed.py b/gateway/tests/test_mcp_upstream_governed.py index bb316bacd..75d708cd9 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, @@ -3412,3 +3415,326 @@ 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, + 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. 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"] + 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") + + 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) + 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( + 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 is recorded as one ledger entry, 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"]) + + +@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 in that retry. + """ + 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"]) diff --git a/gateway/tests/test_refund_reconciliation_contention_surface.py b/gateway/tests/test_refund_reconciliation_contention_surface.py index 8d176d2b6..527b7ef69 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,14 @@ ) 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 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 @@ -123,9 +129,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 +165,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 +183,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 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( - real_get_signing_key_service(), state, retirements + real_get_signing_key_service(), state, retirements, rotate ) monkeypatch.setattr( @@ -328,6 +356,61 @@ 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: + """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 original service is + back in place when the test ends. + """ + 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: + """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 +488,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 +514,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 +529,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 +590,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 +619,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 +635,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_refund_reconciliation_unsigned.py b/gateway/tests/test_refund_reconciliation_unsigned.py new file mode 100644 index 000000000..f7a8083b3 --- /dev/null +++ b/gateway/tests/test_refund_reconciliation_unsigned.py @@ -0,0 +1,798 @@ +"""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 + +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 event, func, select + +from app.db.database import get_engine, get_session_factory +from app.db.models import ( + IdempotencyRecordModel, + LedgerEntryModel, + ReceiptModel, + 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 +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, "lose_key": True} + + async def run() -> dict[str, Any]: + state["runs"] += 1 + if state["lose_key"]: + 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 that charged row and no additional row. + 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) + + +@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 + + +@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 + + 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) + + +@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) + + +@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 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. + """ + 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) diff --git a/gateway/tests/test_signing_key_lifecycle.py b/gateway/tests/test_signing_key_lifecycle.py index 8c04a658b..90f9a2fe5 100644 --- a/gateway/tests/test_signing_key_lifecycle.py +++ b/gateway/tests/test_signing_key_lifecycle.py @@ -422,3 +422,230 @@ 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" + + +@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 + + +@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"]} + + +@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 diff --git a/gateway/tests/test_signing_key_precharge.py b/gateway/tests/test_signing_key_precharge.py new file mode 100644 index 000000000..3976af1e1 --- /dev/null +++ b/gateway/tests/test_signing_key_precharge.py @@ -0,0 +1,553 @@ +"""A replica whose signing key cannot sign refuses before it charges. + +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 +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 import signing_keys as signing_keys_module +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_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_problem", 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 +) -> 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 + + +@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" + + +@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 + + +@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 +) -> 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] + + +@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