Skip to content

Supersedes #22836: fix(payment): guard stripe webhook against null metadata and missing item price lookups - #24628

Merged
Git-on-my-level merged 2 commits into
mainfrom
community/revive-22836
Nov 9, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
community/revive-22836

Conversation

@omiagent

@omiagent omiagent Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

What this does, in plain terms

Omi's payment webhook (the endpoint Stripe calls whenever a checkout, subscription or schedule changes) reads event fields like session['metadata']['app_id'] to decide what to do with the payment. When Stripe sends "metadata": null — which its API does in realistic payloads — the code's session.get('metadata', {}) idiom returns None instead of the intended empty dict (the key exists, with a null value), so the next .get(...) crashes with AttributeError: 'NoneType' object has no attribute 'get'. The webhook answers HTTP 500 and Stripe retries the delivery; meanwhile the event is never processed, so subscription state in Omi can go stale. This PR makes every such read null-safe ((x.get('metadata') or {})), guards the subscription items.data price-id lookup, and adds four deterministic reproduction tests. For well-formed payloads nothing changes — this strictly reduces crash risk on the payment path.

What this carries

Supersedes #22836 — "fix(payment): guard stripe webhook against null metadata and missing item price lookups" by @Speedyzyzz (Balavignesh). Both commits are cherry-picked with original authorship intact (he is the git author on both); the revive run added no commits of its own. The original sat reviewed-but-unmerged for 14 days while main moved underneath it (held-recovery work reshaped backend/routers/payment.py); this branch carries it onto current main so it can run today's CI.

The production change was already verified on the original PR by its maintainer review: "the core diagnosis is right … the (x.get('metadata') or {}) form is the correct fix and matches the pattern this same file already uses", all five hunks behavior-preserving, sub_items isinstance guard "only feeds the 'unknown price ID' warning log, not any billing decision". From its side the review found the PR ready; final merge sign-off stays with the human maintainer, as on the original.

Credit: all of the code in this PR is @Speedyzyzz's (git author on both commits).

Product invariants affected

none

How it was verified (this branch, current main @ b9ef1e3)

  • Red proof (plain origin/main + the author's new test file): python -m pytest tests/unit/test_stripe_webhook_null_metadata_crash.py → 4 failed in 1.67s — every test hits the unguarded chained lookup, exactly the crash the PR describes.
  • Green (this branch): same 4 tests pass; the full stripe/payment unit set — test_stripe_webhook_null_metadata_crash.py, test_stripe_webhook_none_guard.py (desktop-backend: Stripe webhook 500s and stale URL 503s #7282, a different failure mode: FirestoreNotFound/builder-None, so no overlap), test_stripe_webhook_behavioral.py, test_stripe_event_ledger.py, test_stripe_subscription_terminal_status.py, test_billing_webhook_delivery.py, test_subscription_ingestion_characterization.py, test_delete_account_stripe_cancel.py, test_finops_stripe_book.py, test_finops_stripe_fees.py → junit tests=407 failures=0 errors=0 skipped=0 (3.26s).
  • Typecheck lane: backend/scripts/typecheck.sh (pyright) on this branch → 3355 errors, 91503 warnings; plain origin/main control → identical 3355 errors, and the path-normalized per-error diff is empty. Zero branch delta.
  • Pinned formatter: bash scripts/backend-python-format --check backend/routers/payment.py backend/tests/unit/test_stripe_webhook_null_metadata_crash.py → clean (2 files would be left unchanged).
  • Not run: live Stripe/Firestore paths (the carried tests are hermetic — mocked handler calls only, same rationale as the original PR).

Tests

Four regression tests in backend/tests/unit/test_stripe_webhook_null_metadata_crash.py (authored in #22836, carried unchanged):

  • test_checkout_session_completed_handles_null_metadata_gracefully — metadata: None checkout must not raise and returns {'status': 'success'}.
  • test_customer_subscription_created_handles_null_metadata_gracefully — null-metadata subscription event returns the handler's real No customer ID or UID message.
  • test_subscription_schedule_completed_handles_null_metadata_gracefully — null-metadata schedule completion proceeds without AttributeError.
  • test_checkout_session_completed_with_client_reference_id_and_null_metadata — pins the fallback ordering: client_reference_id resolves uid when metadata is null.

UI evidence

UI-Evidence: none -- backend-only change

Failure class

Failure-Class: none

Line-Count-Exception: backend/routers/payment.py | 1980 -> 1982 | carried #22836: five null-metadata guard hunks for the Stripe webhook (net +2 lines), cherry-picked unchanged from the reviewed original

Supersedes #22836

View guided diff Turn on auto-fix

@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the production change is correct, minimal, and behavior-preserving — formal sign-off stays with a human maintainer because this is the Stripe payment webhook. Credit to @Speedyzyzz for the original diagnosis and fix in #22836; both commits carry the original authorship, and the payment hunks here are verified line-for-line identical to the original, now carried onto current main.

backend/routers/payment.py — all five hunks are sound null-safety rewrites. (x.get('metadata') or {}) is the correct idiom for Stripe "metadata": null payloads, where .get('metadata', {}) returns None because the key exists with a null value; for well-formed payloads every rewrite is equivalent. The hoisted session_metadata (~L1173) also removes repeated lookups, and uid = session.get('client_reference_id') (~L1177) turns a missing-key KeyError (HTTP 500) into the existing Invalid-client 400 path. The sub_items isinstance guard (~L1498) only feeds the unknown-price-ID warning log — it never influences a billing decision. The pattern matches null-safe idioms already used elsewhere in this file.

backend/tests/unit/test_stripe_webhook_null_metadata_crash.py — four deterministic repro tests (checkout.session.completed, customer.subscription.created, subscription_schedule.completed, each with metadata: None, plus the client_reference_id fallback ordering), with narrow mocks (record_subscription_event, users_db.get_user_profile). The env-var preamble uses the same dummy values and shared ENCRYPTION_SECRET test fixture already used across the backend unit suite — nothing new is exposed.

Security: strictly reduces crash surface on /v1/payments/stripe/webhook — no change to signature verification, no new external calls, no billing-logic change. Blast radius: none for well-formed payloads; null-metadata events that previously 500'd (with Stripe retries and stale subscription state) now process or return the intended 400.

USER IMPACT: paying users whose Stripe events carry null metadata get them processed instead of a server error; everyone else sees no difference.

Non-blocking nice-to-have: the diff also guards data.previous_attributes and non-list items.data, but no test exercises those two paths yet — one small test each would pin them.

Payment-path changes keep formal approval with the human maintainers — leaving this ready for maintainer sign-off before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added security-review Touches auth, provider routing, secrets, or security-sensitive surfaces backend Backend Task (python) labels Nov 4, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the production change is correct, tightly scoped, and well-tested — nothing blocking from my side; final merge sign-off stays with a human maintainer because this is the Stripe billing webhook path.

Verified on head de9bc73:

  • backend/routers/payment.py:1172 — session_metadata = session.get('metadata') or {} is the right fix: when Stripe sends "metadata": null, dict.get('metadata', {}) returns None (the key exists), so every chained .get(...) below could raise AttributeError and 500 the webhook. All five conversions (session metadata, previous_attributes, subscription uid, schedule uid, sub_items) are behavior-preserving for well-formed payloads.
  • backend/routers/payment.py:1178 — session.get('client_reference_id') in place of session['client_reference_id'] routes a missing ref id into the existing len(uid) < 4 guard (HTTP 400) instead of a KeyError 500. Good.
  • backend/routers/payment.py:1496-1499 — the sub_items guard is safe: price_id = 'unknown' is initialized before the branch, so the isinstance checks can't leave the warning log with an unbound name, and the lookup only feeds the "unknown price ID" warning, not any billing decision.
  • backend/tests/unit/test_stripe_webhook_null_metadata_crash.py — four deterministic reproductions calling _handle_stripe_event directly with real return-shape assertions, including a fallback-ordering pin (client_reference_id present + null metadata). The env-var defaults match the existing unit-test fixture convention.

Security: no new data flows, webhook signature verification untouched; this strictly reduces crash/retry-loop surface on an authenticated Stripe callback. CodeQL, the backend unit suite, and both hermetic backend gates are green on this head. Supersession is clean — #22836 is closed and @Speedyzyzz's authorship is preserved on both commits.

Performance: pure lookup-shape changes on an already-loaded dict — no added queries or per-call cost.
Blast radius: payment webhook handler only; for well-formed payloads behavior is unchanged.

USER IMPACT: payments arriving with null metadata no longer fail webhook processing — subscription state updates land instead of silently going stale while Stripe retries into 500s.

Still wanted (non-blocking): a direct test for the new missing-client_reference_id → 400 branch at line 1178, and one for the sub_items non-list/non-dict shape at 1496 — both are new guards without direct coverage.

Because this touches entitlement-affecting billing code, the final go should come from a human maintainer despite the clean review.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level
Git-on-my-level merged commit b0bf179 into main Nov 9, 2026
73 of 74 checks passed
@Git-on-my-level
Git-on-my-level deleted the community/revive-22836 branch November 9, 2026 10:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants