Skip to content

fix(billing): refuse top-up prepare cleanly when Stripe is not configured - #382

Merged
PetrefiedThunder merged 5 commits into
mainfrom
fix/345-topup-prepare-unconfigured
Nov 25, 2026
Merged

PetrefiedThunder merged 5 commits into
mainfrom
fix/345-topup-prepare-unconfigured

Conversation

@PetrefiedThunder

@PetrefiedThunder PetrefiedThunder commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #345

Root cause

StripeIntegration.create_top_up_intent opened the client's idempotency record (and wrote the quote checkpoint) before calling stripe.PaymentIntent.create. With no STRIPE_SECRET_KEY, the SDK raised AuthenticationError locally, before any request left the machine. The route's catch-all except Exception answered 400 topup_prepare_error with the SDK's own text, and nothing completed or released the record, so every retry with the same key hit 409 idempotency_in_progress.

Fix

  • create_top_up_intent checks get_settings().STRIPE_SECRET_KEY after input, wallet and key validation and before the idempotency record is opened (same truth as /health/dependencies and discovery). It raises the new PaymentsNotConfiguredError, which the route maps to 503 payments_not_configured with a fixed message. Nothing is written, so a retry with the same key gets the same 503, and the key works once Stripe is configured. Validation refusals (unknown wallet 404, non-sponsor or bad amount or bad key 400) are unchanged and still come first.
  • Stripe SDK errors no longer echo the SDK's text:
    • InvalidRequestError / CardError (Stripe rejected the request itself, for example an amount under its minimum) stay 400 topup_prepare_error, now with Stripe's stable code as provider_code and a fixed message.
    • Other StripeErrors (auth, connection, rate limit, outage) answer 502 payment_provider_error; the error type is logged for the operator.
  • TROUBLESHOOTING.md documents the three answers.

Not changed

With a key configured, a Stripe failure after the record is opened still leaves the record in progress. That is the existing uncertain-result design: after _TOP_UP_RETRY_IDLE_SECONDS a retry resumes with the stored quote and the same Stripe idempotency key, so a request Stripe may have executed is never created twice. Releasing the record on definitive Stripe refusals would be a separate change.

Verification

  • Live gateway (uvicorn, SQLite, trust mode, ENABLE_PROOF_SURFACES=true, STRIPE_SECRET_KEY empty): sponsor wallet, then POST /v1/billing/top-up/prepare?amount_fiat=5 twice with Idempotency-Key: topup-345. Both 503 payments_not_configured; idempotency_records has 0 rows for the key; sponsor balance unchanged. The unfixed behavior (SDK text, then 409) was confirmed in-process: the new tests fail on main, matching the issue's live report.
  • New tests in tests/test_stripe_integration.py: unconfigured refusal plus same-key retry, no record, no credit, SDK never called; AuthenticationError answers 502 without the SDK text; InvalidRequestError stays 400 with provider_code and without the SDK text. The module's mocked-SDK tests (and one in test_qa_money_auth_matrix.py) now set a placeholder STRIPE_SECRET_KEY, since prepare refuses without one.
  • Full gateway suite on this branch: 6601 passed, 105 skipped. sdk/python/tests: 472 passed. Ruff check and format, mypy app/: clean.

Overlap

No open PR changes these lines. #329 and #331 edit other parts of routers/billing.py; #50, #56 and #63 are large older drafts across these files but do not touch prepare_top_up or create_top_up_intent.

🤖 Generated with Claude Code


Note

Medium Risk
Changes top-up prepare error handling and idempotency ordering on a money path; behavior is well-tested but misconfiguration could still block legitimate retries until Stripe is configured.

Overview
Top-up prepare now fails predictably when fiat payments are not set up, and Stripe failures no longer leak SDK messages to API clients.

create_top_up_intent checks for STRIPE_SECRET_KEY before opening an idempotency record and raises PaymentsNotConfiguredError, which the route maps to 503 payments_not_configured with a fixed message. Retries with the same Idempotency-Key repeat the same 503 instead of getting stuck at 409 in progress, and no ledger/idempotency state is written.

Stripe errors from prepare_top_up are split into stable API responses: InvalidRequestError / CardError stay 400 topup_prepare_error with Stripe’s provider_code; other StripeError types return 502 payment_provider_error (error type logged for operators). TROUBLESHOOTING.md documents these outcomes, and tests cover unconfigured Stripe, idempotency safety, and non-echoed provider text.

Reviewed by Cursor Bugbot for commit c55ca6b. Bugbot is set up for automated code reviews on this repo. Configure here.

…ured

With no STRIPE_SECRET_KEY, POST /v1/billing/top-up/prepare opened the
client's idempotency record, then the Stripe SDK raised locally. The
route answered 400 with the SDK's own text, and the record was left
without a response, so every retry with the same key got 409
idempotency_in_progress.

Check the key before the idempotency record is opened (same truth as
/health/dependencies and discovery) and answer 503
payments_not_configured. Nothing is written, so a retry gets the same
answer, and the key works once Stripe is configured.

Stripe SDK errors no longer echo the SDK's text. A request Stripe
rejects itself (InvalidRequestError, CardError) stays 400
topup_prepare_error with Stripe's stable code as provider_code; other
Stripe errors (auth, connection, rate limit, outage) answer 502
payment_provider_error, with the error type logged for the operator.

Fixes #345

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: CS <cs@CSs-MacBook-Pro.local>
@vercel

vercel Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
agent-middleware-web Ready Ready Preview Nov 25, 2026 10:46am UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 26 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 59f20a1 and c55ca6b.

Files selected for processing: 5

  • gateway/TROUBLESHOOTING.md
  • gateway/app/routers/billing.py
  • gateway/app/services/stripe_integration.py
  • gateway/tests/test_qa_money_auth_matrix.py
  • gateway/tests/test_stripe_integration.py
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T02:00:33.344805Z 4a1b6e4 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@PetrefiedThunder

Copy link
Copy Markdown
Collaborator Author

READY FOR QA 4a1b6e4

Fixes #345. With no STRIPE_SECRET_KEY, top-up prepare returns 503 payments_not_configured before any idempotency record exists, so the same key can be retried; raw Stripe error text is no longer returned. CI result, License result and gitleaks are green; no open review threads.

@PetrefiedThunder

Copy link
Copy Markdown
Collaborator Author

READY FOR QA 597cb6a

Fixes #345. fix(billing): refuse top-up prepare cleanly when Stripe is not configured. The branch was updated from main, so this head replaces any earlier one. CI result, License result and gitleaks are green on this commit, the PR is up to date with main, and there are no open review threads.

IntelliJ reported that PaymentsNotConfiguredError.__init__ should return
None even with an explicit None annotation. Sibling constructors in this
module omit the annotation. The exception message is unchanged.

@PetrefiedThunder PetrefiedThunder left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review (grok): PASS

Head 66710b6. Merged origin/main with a merge commit. No conflicts. No rebase.

Correctness. An empty STRIPE_SECRET_KEY is refused before any idempotency row is opened, which is the #345 failure mode (a local Stripe SDK error used to leave the client key in progress). gateway/app/services/stripe_integration.py:187 raises PaymentsNotConfiguredError. gateway/app/routers/billing.py:1058 maps that to 503 payments_not_configured and does not echo SDK text. Stripe InvalidRequestError and CardError stay 400 topup_prepare_error with provider_code (gateway/app/routers/billing.py:1066). Other StripeError values become 502 payment_provider_error, and the log records the exception type only (gateway/app/routers/billing.py:1078).

Tests cover the change. gateway/tests/test_stripe_integration.py:648 asserts 503 on the first call and the retry, PaymentIntent.create is not called, the idempotency row count stays 0, and the balance is unchanged. gateway/tests/test_stripe_integration.py:691 covers AuthenticationError as 502 with the SDK text absent. gateway/tests/test_stripe_integration.py:713 covers InvalidRequestError as 400 with provider_code amount_too_small and the SDK text absent. gateway/tests/test_qa_money_auth_matrix.py:303 sets a non-empty key so the existing sponsor success path still runs under the new guard.

Docs match the code. gateway/TROUBLESHOOTING.md:80 describes 503 payments_not_configured with nothing recorded so the same Idempotency-Key can be retried after the key is set, 502 payment_provider_error for a bad key, connection failure, rate limit, or Stripe outage with the error type in the server log, and 400 topup_prepare_error with provider_code when Stripe rejects the request. Those sentences match the handlers above. The retry-after-config claim is backed by the zero-row assertion, not by a third request after the key is filled in. That is sufficient: the key is not consumed, and configured success is already covered.

Local checks: pytest on those two modules, 71 passed; ruff 0.17.6 check and format clean; pre-commit mypy passed. CI on this head is green (gh pr checks 382 exit 0), including Python 3.11 through 3.14 gateway, lint, postgres proofs, gitleaks, and CodeQL.

IntelliJ lint_files on the four touched Python files reported one warning on a new line: PaymentsNotConfiguredError.init annotated to return None. gateway/app/services/stripe_integration.py:76 now omits that annotation, matching the other constructors in the module. The message is unchanged. Remaining warnings are pre-existing SQLModel constructor noise outside this diff and were left alone.

This branch was successfully deployed

1 active deployment
Preview — c55ca6b9 Deployed Nov 25, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Billing: top-up/prepare without Stripe configured returns the raw Stripe SDK message and wedges the idempotency key

2 participants