Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
638ea21
fix(trust): refuse before the charge when the signing key cannot sign
claude Nov 5, 2026
a573f96
fix(refunds): record a pending refund even when its receipt cannot be…
claude Nov 5, 2026
4ccfc1b
Merge remote-tracking branch 'origin/claude/pending-refund-unsigned' …
claude Nov 5, 2026
c7abc3d
fix(trust): a retired signing key refuses to sign instead of reactiva…
claude Nov 5, 2026
b054b54
test(awi): swap the module's signing service instead of patching the …
claude Nov 5, 2026
6280e23
Merge remote-tracking branch 'origin/claude/signing-key-precharge-che…
claude Nov 5, 2026
d5b9441
test(refunds): run rotations and redeploys on separate signing services
claude Nov 5, 2026
9943006
test(refunds): a tampered stored payload is never signed
claude Nov 5, 2026
6c4f8a7
Merge remote-tracking branch 'origin/claude/pending-refund-unsigned' …
claude Nov 5, 2026
d5e8369
test(trust): pin signing_key_status_invalid and document it
claude Nov 5, 2026
d44aa9e
fix(keys): answer 503 signing_key_unavailable on the active-key route
claude Nov 5, 2026
1b7cc37
fix(refunds): give an unsigned pending refund a single owner
claude Nov 5, 2026
11ed397
fix(billing): refuse a charge before the debit when the signing key c…
claude Nov 5, 2026
0768bb8
fix(trust): log the underlying reason when a key cannot sign
claude Nov 5, 2026
9c3714d
Merge remote-tracking branch 'origin/claude/signing-key-precharge-che…
claude Nov 5, 2026
98331da
Merge remote-tracking branch 'origin/claude/pending-refund-unsigned' …
claude Nov 5, 2026
55b42ac
fix(health): judge the signing key by the rule signing uses
claude Nov 5, 2026
1e2af9b
docs(keys): say exactly which in-flight paths a mid-call retirement c…
claude Nov 5, 2026
8a1c6d7
test(trust): pin rotation back to a retired key id as the one reactiv…
claude Nov 5, 2026
881028a
fix(refunds): sign an unsigned item whose refund landed but was never…
claude Nov 5, 2026
00c0b0f
fix(billing): check the signing key before the wallet lookup on charge
claude Nov 5, 2026
8dd9593
fix(health): log a failed signing key row read at warning
claude Nov 5, 2026
5f8619c
test(health): pin the key material mismatch and the logged row read f…
claude Nov 5, 2026
86e3ab5
docs(health): readiness checks the signing key; billing replays get 5…
claude Nov 5, 2026
b1200c3
Merge branch 'claude/signing-key-precharge-check' into claude/signing…
claude Nov 5, 2026
3a81e11
Merge branch 'claude/pending-refund-unsigned' into claude/signing-key…
claude Nov 5, 2026
7a924f9
refactor(trust): drop configured_key_status; list every readiness reason
claude Nov 5, 2026
9baa043
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 18, 2026
3f0c052
Merge branch 'main' into claude/signing-key-precharge-check
PetrefiedThunder Nov 18, 2026
73e759f
Merge branch 'main' into claude/signing-key-retired-refuses
PetrefiedThunder Nov 18, 2026
eef58b5
test(refunds): pin the later-signed receipt's fields and the cleanup …
claude Nov 19, 2026
10f834c
Merge remote-tracking branch 'origin/main' into claude/signing-key-pr…
claude Nov 19, 2026
87bf982
Merge branch 'claude/signing-key-precharge-check' into claude/signing…
claude Nov 19, 2026
008ee3a
Merge remote-tracking branch 'origin/main' into claude/pending-refund…
claude Nov 19, 2026
364645e
Merge branch 'claude/pending-refund-unsigned' into claude/signing-key…
claude Nov 19, 2026
9da448c
fix(refunds): scan every unsigned pending refund once per pass
claude Nov 19, 2026
90d9ad3
Merge branch 'claude/pending-refund-unsigned' into claude/signing-key…
claude Nov 19, 2026
dc47c68
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 24, 2026
e26ff6f
Merge branch 'main' into claude/signing-key-retired-refuses
PetrefiedThunder Nov 24, 2026
a31694f
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 25, 2026
ec50507
Merge branch 'main' into claude/signing-key-retired-refuses
PetrefiedThunder Nov 25, 2026
5d913c5
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 25, 2026
862715d
Merge branch 'main' into claude/signing-key-retired-refuses
PetrefiedThunder Nov 25, 2026
bdfd925
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 25, 2026
b4930f8
Merge branch 'main' into claude/signing-key-retired-refuses
PetrefiedThunder Nov 25, 2026
7ef97d7
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 26, 2026
7ab50e8
Merge branch 'main' into claude/signing-key-retired-refuses
PetrefiedThunder Nov 26, 2026
18d785e
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 26, 2026
d890a1d
Merge branch 'main' into claude/signing-key-retired-refuses
PetrefiedThunder Nov 26, 2026
0c00379
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 26, 2026
f46d7f4
Merge origin/main into claude/signing-key-retired-refuses
PetrefiedThunder Nov 26, 2026
0c3790a
fix(refunds): only a charged record is an unsigned pending refund
claude Nov 27, 2026
dd414ea
Merge branch 'claude/pending-refund-unsigned' into claude/signing-key…
claude Nov 27, 2026
c820074
docs: say receipt ID and drop exactly-once claims
PetrefiedThunder Nov 27, 2026
6af0442
docs(refunds): do not promise the refund of an unsigned pending item
claude Nov 30, 2026
000f974
Merge branch 'main' into claude/signing-key-retired-refuses
PetrefiedThunder Dec 1, 2026
3ccfb09
Merge branch 'main' into claude/signing-key-retired-refuses
PetrefiedThunder Dec 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion gateway/SECURITY_LIMITATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions gateway/app/core/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand Down Expand Up @@ -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",
Expand All @@ -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
Comment thread
PetrefiedThunder marked this conversation as resolved.
Resolved


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)
Expand Down
21 changes: 21 additions & 0 deletions gateway/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
build_public_dependency_report,
check_redis_liveness,
check_database_readiness,
check_signing_key_readiness,
check_mqtt_readiness,
gather_dependency_report,
)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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={
Expand Down
21 changes: 21 additions & 0 deletions gateway/app/routers/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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(
Expand Down
24 changes: 20 additions & 4 deletions gateway/app/routers/keys.py
Original file line number Diff line number Diff line change
@@ -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"])

Expand All @@ -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)


Expand Down
46 changes: 43 additions & 3 deletions gateway/app/routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@
PermitError,
PolicyDecision,
ReceiptWriteContendedError,
SigningKeyUnavailableError,
evaluate_tool_invocation,
evaluate_wallet_policy,
get_agent_money,
Expand All @@ -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,
Expand Down Expand Up @@ -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",
)
}
Expand All @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Comment thread
PetrefiedThunder marked this conversation as resolved.
Resolved
Comment thread
PetrefiedThunder marked this conversation as resolved.
Resolved
owned_record: dict[str, Any] = {}
try:
return await _execute_registered_tool_inner(
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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,
Expand Down
17 changes: 17 additions & 0 deletions gateway/app/routers/mcp_standard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
24 changes: 23 additions & 1 deletion gateway/app/services/awi_http_governance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -448,6 +453,23 @@ async def _admit_awi_http_governed(ctx: AwiHttpGovernedContext) -> None:

permits = get_permit_service()
idem = get_idempotency_service()
# Refuse before the reservation and the charge when this replica's signing
# key cannot sign: the receipt written after the callback needs it, and
# finding out there would leave a debited wallet with no receipt. Nothing
# is reserved yet, so the begun record is released for a retry.
try:
await get_signing_key_service().assert_ready_to_sign()
Comment thread
PetrefiedThunder marked this conversation as resolved.
Resolved
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
Comment thread
PetrefiedThunder marked this conversation as resolved.
Resolved
try:
await permits.reserve_budget(
ctx.permit_id,
Expand Down
Loading
Loading