diff --git a/gateway/TROUBLESHOOTING.md b/gateway/TROUBLESHOOTING.md index ba262b7fa..49d653099 100644 --- a/gateway/TROUBLESHOOTING.md +++ b/gateway/TROUBLESHOOTING.md @@ -77,6 +77,9 @@ These are **proof surfaces**. Start the API with `ENABLE_PROOF_SURFACES=true` to ### `410 Gone` on `POST /v1/billing/top-up` Direct top-ups are disabled by design. Use `POST /v1/billing/top-up/prepare` to create a Stripe PaymentIntent instead. See README.md "Core API surfaces" and [docs/settlement-rails.md](docs/settlement-rails.md). +### `503 payments_not_configured` on `POST /v1/billing/top-up/prepare` +No `STRIPE_SECRET_KEY` is set, so the gateway cannot create a PaymentIntent. Nothing is recorded, so once the key is set the same `Idempotency-Key` can be retried. A `502 payment_provider_error` means the gateway could not complete the call to Stripe (bad key, connection failure, rate limit, or a Stripe outage); the server log names the Stripe error type. A `400 topup_prepare_error` with a `provider_code` means Stripe rejected the request itself, for example an amount below its minimum. + ### `401 Unauthorized` or `403 Forbidden` - Check that `X-API-Key` header is present and matches a valid wallet-scoped or bootstrap key. - Bootstrap keys go in `VALID_API_KEYS` (comma-separated). Wallet keys are created via `POST /v1/api-keys`. diff --git a/gateway/app/routers/billing.py b/gateway/app/routers/billing.py index 67d450c45..9b6b3202e 100644 --- a/gateway/app/routers/billing.py +++ b/gateway/app/routers/billing.py @@ -11,8 +11,11 @@ router, charges a Stripe Shared Payment Token and mints no credits. """ +import logging from decimal import Decimal from typing import ClassVar, cast + +import stripe from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, status from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse @@ -43,7 +46,10 @@ from ..services.policies import evaluate_wallet_policy from ..services.velocity_monitor import WalletFrozenError from ..services.wallet_engine import CrossTenantTransferError, WalletExpiredError -from ..services.stripe_integration import get_stripe_integration +from ..services.stripe_integration import ( + PaymentsNotConfiguredError, + get_stripe_integration, +) from ..services.shadow_ledger import SimulatedChargeResult, get_shadow_ledger from ..services.acp_bridge import ( ACPBridgeError, @@ -214,6 +220,8 @@ async def _enforce_billing_policy( return estimated_cost, policy.policy_id, policy.evaluated_constraints +logger = logging.getLogger(__name__) + router = APIRouter( prefix="/v1/billing", tags=["Agent Financial Gateways"], @@ -1047,6 +1055,42 @@ async def prepare_top_up( status_code=status.HTTP_409_CONFLICT, detail={"error": str(e), "message": str(e)}, ) from e + except PaymentsNotConfiguredError as e: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail={ + "error": "payments_not_configured", + "message": "Fiat top-ups are not available on this deployment.", + }, + ) from e + except (stripe.InvalidRequestError, stripe.CardError) as e: + # Stripe refused the request itself (for example an amount under its + # minimum): a caller error, so keep 400. Pass Stripe's stable code + # rather than the SDK's text, which is written for the key holder. + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={ + "error": "topup_prepare_error", + "message": "The payment provider rejected the top-up request.", + "provider_code": e.code, + }, + ) from e + except stripe.StripeError as e: + # Authentication, connection, rate limit, or provider failures. The + # SDK's text is for the operator holding the Stripe key, not for the + # API caller; log the error type and answer with a stable code. + logger.warning( + "top-up prepare failed at the payment provider for wallet %s: %s", + wallet_id, + type(e).__name__, + ) + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail={ + "error": "payment_provider_error", + "message": "The payment provider did not accept the request.", + }, + ) from e except Exception as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, diff --git a/gateway/app/services/stripe_integration.py b/gateway/app/services/stripe_integration.py index e7825d759..c7ba08f4b 100644 --- a/gateway/app/services/stripe_integration.py +++ b/gateway/app/services/stripe_integration.py @@ -70,6 +70,13 @@ _TOP_UP_RETRY_IDLE_SECONDS = 5 * 60 +class PaymentsNotConfiguredError(RuntimeError): + """No Stripe secret key is configured, so no fiat payment can be created.""" + + def __init__(self): + super().__init__("payments_not_configured") + + class StripeSettlementError(ValueError): """A verified Stripe event does not prove an acceptable top-up settlement.""" @@ -173,6 +180,13 @@ async def create_top_up_intent( idempotency_key, source=IDEMPOTENCY_KEY_HEADER_SOURCE ) + # Refuse before an idempotency record exists. Without a key the Stripe + # SDK raises locally, after the record was opened and before it could + # be completed, which left the client's key stuck in progress. Same + # truth as /health/dependencies and discovery. + if not get_settings().STRIPE_SECRET_KEY: + raise PaymentsNotConfiguredError() + replay_service = ( get_idempotency_service() if validated_key is not None else None ) diff --git a/gateway/tests/test_qa_money_auth_matrix.py b/gateway/tests/test_qa_money_auth_matrix.py index fd68981fd..ef3ec1169 100644 --- a/gateway/tests/test_qa_money_auth_matrix.py +++ b/gateway/tests/test_qa_money_auth_matrix.py @@ -294,7 +294,13 @@ async def test_top_up_prepare_denies_foreign_wallet_key(client, api_headers): @pytest.mark.anyio -async def test_top_up_prepare_scoped_key_succeeds_for_own_sponsor(client, api_headers): +async def test_top_up_prepare_scoped_key_succeeds_for_own_sponsor( + client, api_headers, monkeypatch +): + from app.core.config import get_settings + + # The SDK is mocked below; any non-empty key marks payments as configured. + monkeypatch.setattr(get_settings(), "STRIPE_SECRET_KEY", "configured-in-tests") sponsor = await client.post( "/v1/billing/wallets/sponsor", json={ diff --git a/gateway/tests/test_stripe_integration.py b/gateway/tests/test_stripe_integration.py index 775bb867e..d8fa28004 100644 --- a/gateway/tests/test_stripe_integration.py +++ b/gateway/tests/test_stripe_integration.py @@ -51,6 +51,19 @@ def _configured_webhook_secret(monkeypatch): monkeypatch.setattr(get_settings(), "STRIPE_WEBHOOK_SECRET", "whsec_test_stripe") +@pytest.fixture(autouse=True) +def _configured_stripe_secret(monkeypatch): + """Mark Stripe as configured for this module's mocked-SDK tests. + + Top-up prepare refuses with payments_not_configured when no secret key is + set. These tests mock stripe.PaymentIntent, so any non-empty value works; + the unconfigured refusal is pinned by its own test, which clears it. + """ + from app.core.config import get_settings + + monkeypatch.setattr(get_settings(), "STRIPE_SECRET_KEY", "configured-in-tests") + + @pytest.fixture async def sponsor_wallet(client, api_headers): """Create a sponsor wallet for testing.""" @@ -631,6 +644,98 @@ async def test_prepare_top_up_rejects_unusable_idempotency_key_before_stripe( mock_create.assert_not_called() +@pytest.mark.anyio +async def test_prepare_top_up_without_stripe_key_refuses_and_leaves_key_free( + client, sponsor_wallet, api_headers, monkeypatch +): + """No Stripe key is a stable refusal, not the SDK's text (#345). + + The refusal comes before the idempotency record is opened, so a retry + with the same key gets the same answer instead of 409 in progress, and + nothing is credited. + """ + from sqlalchemy import func, select + + from app.core.config import get_settings + + monkeypatch.setattr(get_settings(), "STRIPE_SECRET_KEY", "") + wallet_id = sponsor_wallet["wallet_id"] + url = f"/v1/billing/top-up/prepare?wallet_id={wallet_id}&amount_fiat=5.0" + headers = {**api_headers, "Idempotency-Key": "topup-unconfigured-1"} + + with patch( + "app.services.stripe_integration.stripe.PaymentIntent.create" + ) as mock_create: + first = await client.post(url, headers=headers) + retry = await client.post(url, headers=headers) + + for response in (first, retry): + assert response.status_code == 503, response.text + detail = response.json()["detail"] + assert detail["error"] == "payments_not_configured" + assert "stripe.com" not in detail["message"].lower() + mock_create.assert_not_called() + + async with get_session_factory()() as session: + records = await session.scalar( + select(func.count()) + .select_from(IdempotencyRecordModel) + .where(IdempotencyRecordModel.idempotency_key == "topup-unconfigured-1") + ) + assert records == 0 + wallet = await client.get(f"/v1/billing/wallets/{wallet_id}", headers=api_headers) + assert wallet.json()["balance"] == sponsor_wallet["balance"] + + +@pytest.mark.anyio +async def test_prepare_top_up_stripe_error_does_not_echo_provider_text( + client, sponsor_wallet, api_headers +): + """A Stripe SDK error answers with a stable code, not the SDK message.""" + wallet_id = sponsor_wallet["wallet_id"] + provider_text = "provider-side detail meant for the operator" + + with patch( + "app.services.stripe_integration.stripe.PaymentIntent.create" + ) as mock_create: + mock_create.side_effect = stripe.AuthenticationError(provider_text) + response = await client.post( + f"/v1/billing/top-up/prepare?wallet_id={wallet_id}&amount_fiat=5.0", + headers=api_headers, + ) + + assert response.status_code == 502, response.text + assert response.json()["detail"]["error"] == "payment_provider_error" + assert provider_text not in response.text + + +@pytest.mark.anyio +async def test_prepare_top_up_stripe_request_error_stays_400_without_sdk_text( + client, sponsor_wallet, api_headers +): + """Stripe refusing the request itself is a caller error: 400, Stripe's + stable code, and not the SDK's message.""" + wallet_id = sponsor_wallet["wallet_id"] + provider_text = "provider-side detail about the amount" + + with patch( + "app.services.stripe_integration.stripe.PaymentIntent.create" + ) as mock_create: + mock_create.side_effect = stripe.InvalidRequestError( + provider_text, param="amount", code="amount_too_small" + ) + response = await client.post( + f"/v1/billing/top-up/prepare?wallet_id={wallet_id}&amount_fiat=0.01", + headers=api_headers, + ) + + assert response.status_code == 400, response.text + detail = response.json()["detail"] + assert detail["error"] == "topup_prepare_error" + assert detail["provider_code"] == "amount_too_small" + assert provider_text not in response.text + + @pytest.mark.anyio async def test_prepare_top_up_rejects_non_usd_in_api_and_service( client, sponsor_wallet, api_headers