Repository navigation
fix(payment): guard stripe webhook against null metadata and missing item price lookups - #22836
Speedyzyzz wants to merge 2 commits into
Conversation
…item price lookups
Git-on-my-level
left a comment
There was a problem hiding this comment.
The production change is correct, minimal, and matches conventions already used elsewhere in this file — one note on the test file, nothing blocking.
Verified on the current head:
- backend/routers/payment.py — the core diagnosis is right: when Stripe sends
"metadata": null, the key exists with value None, sodict.get('metadata', {})returns None and the chained.get()raises AttributeError. The(x.get('metadata') or {})form is the correct fix and matches the pattern this same file already uses in its account/subscription metadata handling. All five hunks are behavior-preserving for well-formed payloads: the checkout app-payment reads, the subscriptionsub_type/uidfallback,previous_attributesextraction, theitems.dataprice-id guard, and the scheduleuidread. Thesub_itemsisinstance guard only feeds the 'unknown price ID' warning log, not any billing decision.uid = session.get('client_reference_id')is safe-equivalent since the branch is gated on that value's truthiness either way. - backend/tests/unit/test_stripe_webhook_null_metadata_crash.py — three hermetic repro tests with the right expected returns (I checked the 'No customer ID or UID in subscription event.' message against the handler). Note: the hardcoded
ENCRYPTION_SECRET/OPENAI_API_KEYvalues are the repo's long-standing test fixture constants already present verbatim in many existing unit tests, so nothing new is exposed — fine to keep, just don't introduce any real-looking values here in the future.
Security / blast radius: this is the payment webhook, so a mistake here can silently drop or mishandle billing events — that's the one reason it deserves maintainer eyes despite the fix itself being sound. This change strictly reduces crash risk (a 500 here makes Stripe retry the delivery).
USER IMPACT: none — internal reliability fix; Stripe payloads with null metadata no longer crash the webhook receiver.
Nice first contribution. Optional non-blocking follow-up: a test for checkout.session.completed with client_reference_id present but metadata null, to pin the subscription branch's fallback ordering.
Since this touches the money path, leaving final merge sign-off to a human maintainer.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
|
Thanks for the review @Git-on-my-level! We've added the pinned fallback test in commit All 4 hermetic unit tests pass clean in 1.21s with zero external network dependencies. Ready for final maintainer sign-off whenever convenient! |
Git-on-my-level
left a comment
There was a problem hiding this comment.
Since my last review: addressed (the optional test I suggested — checkout.session.completed with client_reference_id set and metadata null, pinning the subscription fallback ordering — verified on this head) · still open (nothing blocking) · newly introduced (nothing).
The new test is exactly right and closes the last gap I'd noted: backend/tests/unit/test_stripe_webhook_null_metadata_crash.py:80-97 patches users_db.get_user_profile to miss, which exercises the real user-existence guard at backend/routers/payment.py:1029 and asserts the early-return {'status': 'success'} at backend/routers/payment.py:1033 — matching the handler's actual behavior with uid resolved from client_reference_id while metadata is null. backend/routers/payment.py itself is unchanged since my last review, so my earlier verification of all five null-guard hunks stands.
Security / blast radius: unchanged from before — this is the money path, so the strict-crash-reduction-only character of the change is what makes it safe; a behavior change here could silently mishandle billing events, and I found none.
USER IMPACT: none — internal reliability fix; Stripe payloads with null metadata no longer crash the webhook receiver.
From my side this is ready; since it touches the payment webhook, final merge sign-off belongs to a human maintainer. Nothing further requested.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
|
Thanks for this fix, @Speedyzyzz! Your commits are being carried forward in #24628 (cherry-picked with your original authorship intact) so they can land with the current CI and repo conventions. Closing this in favor of that branch — your contribution is credited there and in the git history. |
|
Hey @Speedyzyzz 👋 Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request. After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:
Before your next PR, please skim:
If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing. Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out. Thank you for being part of the Omi community! |
…tadata and missing item price lookups (#24628) ## 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` (#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 <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24628?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/24628?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24628&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Problem
When Stripe webhook events arrive with
metadata: null(or whenmetadatais omitted and defaults toNone), expressions of the formsession.get('metadata', {}).get(...)evaluateNone.get(...)and immediately crash with an unhandled exception:This causes webhook processing to abort abruptly across multiple Stripe event handlers:
checkout.session.completed: crashed when checkingsession.get('metadata', {}).get('app_id')orsub_type.customer.subscription.*(created,updated,deleted): crashed onsubscription_obj.get('metadata', {}).get('uid')anditems.datalookups whenitemswas empty ordatawas missing.subscription_schedule.*: crashed onschedule_obj.get('metadata', {}).get('uid').Solution
(session.get('metadata') or {}).get(...)and(subscription_obj.get('metadata') or {}).get(...).items.dataprice lookups againstNoneand empty list payloads before indexing.previous_attributesfromevent.get('data') or {}.Tests
Added
tests/unit/test_stripe_webhook_null_metadata_crash.pycovering:test_checkout_session_completed_handles_null_metadata_gracefullytest_customer_subscription_created_handles_null_metadata_gracefullytest_subscription_schedule_completed_handles_null_metadata_gracefullyAll 3 hermetic unit tests pass in 0.00s with zero network dependencies. Pyright reports 0 errors and 0 warnings.