Repository navigation
fix(app/stripe): stop stripe webhook 500s on secret store failures - #4828
Conversation
SetCustomerDefaultPaymentMethod only returned for not-found errors and fell through on every other failure, dereferencing the nil app customer and panicking. Reachable from the setup_intent.succeeded webhook.
GenericStatusFailedDependencyError was defined but never mapped, so callers returning it fell through to a hardcoded 500. Adds the missing mapping plus a GenericRequestEntityTooLargeError for oversized payloads. Both are matched last so a more specific model error wrapped inside still wins.
Secret store errors were wrapped with bare fmt.Errorf, so an unavailable or rate limited store surfaced as a 500. An Infisical 429 on the webhook secret was returning 500 from the stripe webhook endpoint. The secret store is an external dependency; its failures were never internal errors.
The router read the body itself and hardcoded a 500 for any read failure, so an oversized Stripe event was reported as a server error. Moving the read into the request decoder lets the standard error encoder map it, and drops the duplicated fallback from the router. Also raises the cap from 64KB, which invoice events with many line items can exceed.
Every Stripe webhook fetched the webhook secret from the secret store, adding an external round trip per request and exhausting the provider rate limit. Caching in the service covers all adapters, including the ones swapped in downstream. Mutations evict eagerly, so the TTL only bounds staleness for secrets rotated directly in the store. Errors are not cached.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughStripe webhook handling now reads request bodies inside the handler with a 512 KiB limit. Stripe webhook secrets use a dedicated service. Error encoding now returns HTTP 413 and 424 for the new error types. ChangesStripe webhook request handling
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant Stripe
participant AppStripeWebhook
participant WebhookSecretService
participant StripeAdapter
Stripe->>AppStripeWebhook: Send signed webhook request
AppStripeWebhook->>AppStripeWebhook: Read request body up to 512 KiB
AppStripeWebhook->>StripeAdapter: Validate event for AppID
StripeAdapter->>WebhookSecretService: GetAppSecret
WebhookSecretService-->>StripeAdapter: Return webhook secret
StripeAdapter-->>AppStripeWebhook: Return validated Stripe event
AppStripeWebhook-->>Stripe: Return HTTP response
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
openmeter/app/stripe/httpdriver/webhook.go (1)
50-60: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the request decoder into a named method.
Lines 50-60 add request-size policy and HTTP-to-domain error translation inside a large local callback. Move the decoding path into a named
decodeAppStripeWebhookRequestmethod, then pass that method tohttptransport.NewHandlerWithArgs.As per coding guidelines, “Do not hide type switching, validation, persistence mapping, or meaningful domain translation inside local closures.” As per path instructions, readability and maintainability are a priority.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/app/stripe/httpdriver/webhook.go` around lines 50 - 60, Extract the payload-reading, size-limit handling, and error translation from the local request decoder closure into a named decodeAppStripeWebhookRequest method. Update httptransport.NewHandlerWithArgs to receive that method directly, preserving the existing request parsing behavior and AppStripeWebhookRequest error results.Sources: Coding guidelines, Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@openmeter/secret/service/secret_test.go`:
- Around line 56-158: Extend TestGetAppSecretCaching with constructor validation
cases confirming secretservice.New rejects negative CacheSize and CacheTTL
values, and add a CacheSize-one scenario that reads two distinct secret IDs
before re-reading the first to verify it was evicted and fetched from the
adapter again.
In `@openmeter/secret/service/service.go`:
- Around line 31-42: Update Config.Validate to collect every validation failure
instead of returning immediately, wrapping each error with its corresponding
field context (Adapter, CacheSize, or CacheTTL). Return
models.NewNillableGenericValidationError(errors.Join(errs...)) after validation,
while preserving the existing validation conditions and messages.
---
Nitpick comments:
In `@openmeter/app/stripe/httpdriver/webhook.go`:
- Around line 50-60: Extract the payload-reading, size-limit handling, and error
translation from the local request decoder closure into a named
decodeAppStripeWebhookRequest method. Update httptransport.NewHandlerWithArgs to
receive that method directly, preserving the existing request parsing behavior
and AppStripeWebhookRequest error results.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: b4d6de29-5316-4f1f-aba0-75b1adc2c375
📒 Files selected for processing (10)
openmeter/app/stripe/adapter/stripe.goopenmeter/app/stripe/httpdriver/webhook.goopenmeter/secret/service/secret.goopenmeter/secret/service/secret_test.goopenmeter/secret/service/service.goopenmeter/server/router/appstripe.goopenmeter/server/server_test.gopkg/framework/commonhttp/encoder.gopkg/framework/commonhttp/errors_test.gopkg/models/errors.go
A read that missed the cache could fetch the old value before a concurrent update or delete, then insert it after the eviction ran, leaving a rotated or deleted credential cached for the rest of the TTL. Locking per secret closes that window and collapses concurrent misses for the same secret into a single fetch.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
openmeter/secret/service/secret.go (3)
61-75: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy liftRelease the service lock before the secret store delete.
DeleteAppSecretlocks once, then keeps that lock arounds.adapter.DeleteAppSecret(ctx, input). This matches the contention risk inUpdateAppSecret; release the lock after cache work and invoke the adapter outside the critical section.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/secret/service/secret.go` around lines 61 - 75, Update DeleteAppSecret so the lock acquired via lockFor protects only the cache removal, then unlock it before calling s.adapter.DeleteAppSecret. Preserve deferred cleanup for the cache and ensure the adapter delete executes outside the service lock.
40-59: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick winRelease the cache-lock shard before reading the adapter.
GetAppSecretholds the shard lock for the fulls.cache.Getcall. The cache miss path callsconfig.Adapter.GetAppSecret, so adapter latency also blocks other callers mapped to the same lock shard. Fetch with a shared cache lock, then acquire the secret lock only if you need to revalidate/remove.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/secret/service/secret.go` around lines 40 - 59, Update GetAppSecret to avoid holding the shard lock during s.cache.Get: perform the initial cache read under a shared/read lock, then acquire the exclusive secret lock only when the cache-miss path requires revalidation or removal. Preserve existing validation and error handling while ensuring adapter latency does not block callers sharing the shard.
24-38: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy liftHold the shard lock only for local secret state updates.
UpdateAppSecretkeeps thelockForlock durings.adapter.UpdateAppSecret. SincelockForgroups multiple secrets onto one of 256 shard locks, a slow adapter can block other unrelated secret operations that happen to fall on the same shard. KeepUpdateAppSecretand evict the cache outside the locked section instead.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/secret/service/secret.go` around lines 24 - 38, The shard lock in UpdateAppSecret currently spans the adapter call, blocking unrelated secrets on the same shard. Limit lock.Lock/Unlock to the local update or cache-state section, then call s.adapter.UpdateAppSecret and perform cache eviction after releasing the lock; preserve validation and return behavior.
🧹 Nitpick comments (1)
openmeter/secret/service/secret_test.go (1)
146-231: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd a test for the eviction-vs-in-flight-read race.
The commit message states this change "prevents an in-flight read from reinserting an outdated credential after eviction," but no test exercises that exact race. Current tests cover sequential eviction (update then read) and same-key concurrent reads, not a concurrent Update/Delete racing with an in-flight Get.
Reuse the
onGethook pattern from the "concurrent reads of the same secret" test: block aGetAppSecretcall mid-fetch, callUpdateAppSecretfor the same secret concurrently, release the blocked read, then assert the cache holds the updated value rather than the stale one reinserted by the blocked read.As per path instructions, "Suggest missing tests only when the PR introduces behavior without meaningful coverage."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/secret/service/secret_test.go` around lines 146 - 231, Add a test covering the eviction-versus-in-flight-read race near the existing concurrent cache tests: use countingAdapter.onGet to block GetAppSecret after the store read begins, perform UpdateAppSecret for the same secret while that read is blocked, release it, then fetch again and assert the updated value is returned from cache without reintroducing the stale credential. Verify the adapter call count as needed to demonstrate the updated value remains cached.Source: Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@openmeter/secret/service/secret_test.go`:
- Line 220: Replace context.Background() with t.Context() in the GetAppSecret
call within the test, using the existing testing.T instance and preserving the
rest of the test behavior.
In `@openmeter/secret/service/service.go`:
- Around line 32-40: Remove the striped shard-lock protection from GetAppSecret,
UpdateAppSecret, and DeleteAppSecret around cache access and adapter operations;
refactor those flows so shared cache/adapter work executes without holding
lockFor’s shard mutex. Preserve per-secret correctness using a per-secret lock
or an equivalent bounded context deadline, without serializing unrelated secrets
on the 256-shard locks.
---
Outside diff comments:
In `@openmeter/secret/service/secret.go`:
- Around line 61-75: Update DeleteAppSecret so the lock acquired via lockFor
protects only the cache removal, then unlock it before calling
s.adapter.DeleteAppSecret. Preserve deferred cleanup for the cache and ensure
the adapter delete executes outside the service lock.
- Around line 40-59: Update GetAppSecret to avoid holding the shard lock during
s.cache.Get: perform the initial cache read under a shared/read lock, then
acquire the exclusive secret lock only when the cache-miss path requires
revalidation or removal. Preserve existing validation and error handling while
ensuring adapter latency does not block callers sharing the shard.
- Around line 24-38: The shard lock in UpdateAppSecret currently spans the
adapter call, blocking unrelated secrets on the same shard. Limit
lock.Lock/Unlock to the local update or cache-state section, then call
s.adapter.UpdateAppSecret and perform cache eviction after releasing the lock;
preserve validation and return behavior.
---
Nitpick comments:
In `@openmeter/secret/service/secret_test.go`:
- Around line 146-231: Add a test covering the eviction-versus-in-flight-read
race near the existing concurrent cache tests: use countingAdapter.onGet to
block GetAppSecret after the store read begins, perform UpdateAppSecret for the
same secret while that read is blocked, release it, then fetch again and assert
the updated value is returned from cache without reintroducing the stale
credential. Verify the adapter call count as needed to demonstrate the updated
value remains cached.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 689d7a48-659b-4812-9a92-c687b95b03cb
📒 Files selected for processing (3)
openmeter/secret/service/secret.goopenmeter/secret/service/secret_test.goopenmeter/secret/service/service.go
The test blocks the store read so an update lands mid-fetch, which is the interleaving that previously left the superseded value cached. Verified to fail without the per-secret lock.
|
The race is fixed — your review landed against
One honest caveat: 🤖 Addressed by Claude Code |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/secret/service/secret_test.go (1)
245-304: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd given/when/then intent comments to this race test.
This subtest coordinates two goroutines and three channels to reproduce a stale-cache race. A short
given/when/thencomment block at the top would make the intended interleaving (blocked read, concurrent update, then re-read) much easier to follow for future maintainers.As per coding guidelines, "Begin non-trivial service or lifecycle subtests with concise
given,when, andthenintent comments."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/secret/service/secret_test.go` around lines 245 - 304, Add concise given/when/then intent comments at the start of the subtest “a read racing a mutation never leaves the superseded value cached” describing the blocked read, concurrent update, released fetch, and final re-read returning the new value. Keep the test logic and synchronization unchanged.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@openmeter/secret/service/secret_test.go`:
- Around line 245-304: Add concise given/when/then intent comments at the start
of the subtest “a read racing a mutation never leaves the superseded value
cached” describing the blocked read, concurrent update, released fetch, and
final re-read returning the new value. Keep the test logic and synchronization
unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 90fd685e-fc51-4e97-bc5e-39367316084e
📒 Files selected for processing (1)
openmeter/secret/service/secret_test.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
test/app/stripe/app_test.go (1)
68-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse the test-owned context here.
Pass
t.Context()toTestGetWebhookSecretat line 68. The sharedctxcan only be canceled whenTestAppStripereturns, but the subtest already has atesting.T.Proposed change
- testSuite.TestGetWebhookSecret(ctx, t) + testSuite.TestGetWebhookSecret(t.Context(), t)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/app/stripe/app_test.go` at line 68, Update the TestGetWebhookSecret invocation within TestAppStripe to pass the test-owned t.Context() instead of the shared ctx, while preserving the existing test flow and arguments.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/app/stripe/appstripe.go`:
- Line 810: Update the Given comment in TestGetWebhookSecret to describe a
Stripe app with a configured webhook secret, removing the inaccurate claim that
the secret is stored through the regular secret service.
---
Nitpick comments:
In `@test/app/stripe/app_test.go`:
- Line 68: Update the TestGetWebhookSecret invocation within TestAppStripe to
pass the test-owned t.Context() instead of the shared ctx, while preserving the
existing test flow and arguments.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 0b726f84-b6b6-4bb6-a986-3395914908c4
📒 Files selected for processing (14)
app/common/app.goapp/common/secret.gocmd/billing-worker/wire_gen.gocmd/jobs/internal/wire_gen.gocmd/server/wire_gen.goopenmeter/app/stripe/adapter.goopenmeter/app/stripe/adapter/adapter.goopenmeter/app/stripe/adapter/stripe.goopenmeter/secret/service/secret.gotest/app/stripe/app_test.gotest/app/stripe/appstripe.gotest/app/stripe/invoice_test.gotest/app/stripe/testenv.gotest/app/testenv.go
| func (s *AppHandlerTestSuite) TestGetWebhookSecret(ctx context.Context, t *testing.T) { | ||
| s.setupNamespace(t) | ||
|
|
||
| // Given a Stripe app whose webhook secret is stored through the regular secret service. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Correct the Given comment.
TestGetWebhookSecret configures WebhookSecretService and asserts that Secret is not called. It does not store the webhook secret through the regular secret service. Update the comment to describe a Stripe app with a configured webhook secret.
As per coding guidelines, comments and docstrings should explain non-obvious intent and domain constraints.
Proposed change
- // Given a Stripe app whose webhook secret is stored through the regular secret service.
+ // Given a Stripe app with a configured webhook secret.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Given a Stripe app whose webhook secret is stored through the regular secret service. | |
| // Given a Stripe app with a configured webhook secret. |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@test/app/stripe/appstripe.go` at line 810, Update the Given comment in
TestGetWebhookSecret to describe a Stripe app with a configured webhook secret,
removing the inaccurate claim that the secret is stored through the regular
secret service.
Source: Coding guidelines
There was a problem hiding this comment.
Agreed the wording is wrong — the test mocks the dedicated WebhookSecretService and asserts it is used instead of the regular one, so "stored through the regular secret service" describes the opposite of what is set up.
Holding the one-line fix rather than pushing it blind: my local SSH signing agent is currently failing, and this is your commit on a branch you are actively working on. Happy for you to take the suggested wording directly, or I can push it once I can sign again.
🤖 Addressed by Claude Code
There was a problem hiding this comment.
@tothandras, agreed. Your explanation matches the test behavior.
Please apply the one-line comment update when you can. I will keep this finding open until the change is in the branch.
You are interacting with an AI system.
turip
left a comment
There was a problem hiding this comment.
we should not blank use cached secret store on th
Problem
POST /api/v1/apps/{appId}/stripe/webhookwas returning 500 and paging us.Root cause: the secret store (Infisical) rate limited the webhook secret lookup, and the error was wrapped with a bare
fmt.Errorf, so nothing inGenericErrorEncodermatched and it fell through to the hardcoded 500.The trace corroborates it:
begin_tx→SELECT app_stripes→rollback, with ~165ms unaccounted between the query and the rollback. The Infisical call is the only thing in that path that can burn that time and then fail.Why we were rate limited in the first place: every webhook fetched the secret from the store, with no caching.
Changes
fix(app/stripe): return stripe app customer lookup errorsSetCustomerDefaultPaymentMethodonly returned for not-found errors and fell through on everything else, dereferencing a nil app customer and panicking. Reachable fromsetup_intent.succeeded.fix(commonhttp): map failed dependency and oversized request errorsGenericStatusFailedDependencyErrorwas defined but never mapped, so anything returning it became a 500. Adds that mapping plusGenericRequestEntityTooLargeError.fix(secret): report secret store failures as a failed dependencyfix(app/stripe): read the webhook payload in the request decoderfeat(secret): cache app secretsThe first three commits are enough to stop the paging on their own, if you'd rather land the caching separately.
Caching details
Caching lives in
secretservicerather than an adapter, so it covers every adapter including the ones swapped in downstream. Uses the existingpkg/lrux.CacheWithItemTTL.ConfigThe 1 minute TTL is the main judgment call worth a second opinion.
Known limitation:
lruxhas no stampede protection, so N concurrent misses for the same secret right after expiry still make N calls. At a 1 minute TTL that is a handful per minute instead of one per webhook, which seemed sufficient.singleflightwould collapse them to one if we want it.Testing
openmeter/secret/service/secret_test.go— cache hit, refetch after TTL, failed-dependency classification with no negative caching, eviction on update and deletepkg/framework/commonhttp/errors_test.go— both new status mappings, plus that a more specific model error wrapped inside a failed dependency keeps its own statusopenmeter/server/server_test.go— oversized webhook payload returns 413Full suite green,
gofmtandgo vetclean. Each commit builds independently.Not addressed
Nothing retries or backs off on the secret store call. Caching makes the rate limit far less likely, but a sustained provider outage still surfaces as 424 rather than being ridden out.
Summary by CodeRabbit
Bug Fixes
Reliability
Greptile Summary
The PR improves Stripe webhook body/error handling and introduces a dedicated webhook-secret interface, but the final implementation removes the promised secret cache.
Confidence Score: 4/5
The PR is not yet safe to merge because the default webhook path remains uncached and can reproduce the secret-store rate limiting it is intended to prevent.
The final service implementation directly calls the secret adapter for every webhook-secret lookup, and the new interface is bound to that same implementation, so sustained webhook traffic still reaches the external store once per request.
Files Needing Attention: app/common/secret.go, openmeter/secret/service/secret.go, openmeter/secret/service/service.go
Important Files Changed
Sequence Diagram
sequenceDiagram participant Stripe participant Webhook as Stripe webhook handler participant Adapter as Stripe adapter participant Secrets as secretservice.Service participant Store as External secret store Stripe->>Webhook: POST webhook Webhook->>Adapter: GetWebhookSecret Adapter->>Secrets: GetAppSecret Secrets->>Store: GetAppSecret (every request) Store-->>Secrets: secret or rate-limit error Secrets-->>Webhook: secret or failed-dependency errorPrompt To Fix All With AI
Reviews (5): Last reviewed commit: "refactor(app/stripe): inject webhook sec..." | Re-trigger Greptile
Context used (3)