Repository navigation
fix(billing): re-throw on core subscription UPDATE failure + relink integration tests (#3623 step 5) - #3691
Conversation
…p 5) The customer.subscription.* webhook handler in http.ts wrapped the core column UPDATE plus all downstream side effects in a single try/catch that returned 200 on any error. If the UPDATE itself failed (DB outage, constraint violation, race), Stripe never retried and the org row was left silently stale — the silent-swallow path js-protocol-expert and security-reviewer warned about during the #3681 review. Hoists the core UPDATE outside the swallow-on-error block. UPDATE on a single row by primary key is idempotent — exception now propagates so Stripe retries. Downstream side effects (tier-change enforcement, welcome DMs, autopublish, .deleted audit/activities) keep their existing log+continue pattern because they're non-idempotent and a Stripe retry would refire them. Adds server/tests/integration/admin-stripe-link-unlink.test.ts (5 tests) covering the link/unlink hardening from #3681 + #3692: - link picks the membership sub when customer has multi-sub - link writes admin_stripe_link audit log - unlink clears all subscription_* columns - unlink clears Stripe customer metadata.workos_organization_id (closes the webhook re-link race) - unlink writes admin_stripe_unlink audit log with prior state Out-of-scope follow-up identified: the same silent-swallow pattern exists at http.ts:4195 (revenue_events INSERT in invoice.paid) and lines 4393, 4469, 4506. revenue_events.stripe_invoice_id already has a UNIQUE constraint so retries are safe; the right fix is ON CONFLICT (stripe_invoice_id) DO NOTHING plus re-throw on real errors. Tracked separately rather than expanding this PR. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
| import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'; | ||
| import { HTTPServer } from '../../src/http.js'; | ||
| import request from 'supertest'; | ||
| import { getPool, initializeDatabase, closeDatabase } from '../../src/db/client.js'; |
…atch (#3691 review fix) Two issues from expert review of #3691: M1 — .deleted audit log was not in its own try/catch. The subscription_cancelled audit_log + org_activities INSERTs at http.ts:3939+3956 were `await`ed inside the outer try/catch which swallowed errors. If those INSERTs failed transiently (DB blip, race), the failure jumped to the outer swallow and no row was ever recorded — worst-of-both-worlds: subscription_status update committed (separate write earlier), audit/activity row missing, Stripe sees 200 and never retries. Wraps each in its own try/catch with notifySystemError so the gap is observable. The outer swallow stays for the rest of the non-idempotent side effects. M2 — admin unlink left step-3 webhook fallback open. #3681 cleared customer.metadata.workos_organization_id on unlink, but resolveOrgForStripeCustomer has THREE fallback paths: 1. DB stripe_customer_id (cleared by the unlink UPDATE) 2. customer.metadata.workos_organization_id (cleared in #3681) 3. subscription.metadata.workos_organization_id ← still open A webhook for one of the customer's subs would walk to step 3 and silently re-link the org. Unlink now lists active subs and clears their workos_organization_id metadata too — only the subs that have the key set, so we don't burn Stripe API calls on subs without it. Adds an integration test that asserts the metadata-clear is called on the right subs (and skipped on subs without the key), proving the wire-up not just for customer.metadata but also subscription.metadata. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Expert review pass — pushed fix commit (2d2b909)Two findings addressed: M1 — M2 — admin unlink left step-3 webhook fallback open. #3681 cleared
A webhook for one of the customer's subs would walk to step 3 and silently re-link. Unlink now lists active subs and clears their metadata too. Test asserts both metadata-clear paths fire (and skips Stripe writes on subs without the key, so we don't burn API calls). Other expert findings — filing as separate issues, not in this PR
These three follow-ups are bounded in scope per js-protocol-expert's rule (re-throw on entitlement/revenue/audit writes; swallow on notifications/cache). Stop point reached. |
) (#3697) Two webhook handlers were swallowing all errors when inserting into revenue_events and returning 200 — Stripe never retried, so transient DB errors (statement timeout, connection blip, brief contention) silently lost paid revenue. The UNIQUE constraint on stripe_invoice_id makes the legitimate-retry case safe (PG code 23505 = duplicate Stripe re-fire), but the swallow was also masking real transient failures. Now distinguishes by error code: - 23505 (unique_violation): swallow — Stripe re-fired the same invoice.paid event, the row already exists - Anything else: re-throw — let Stripe retry with backoff Applied at: - http.ts:4180-4239 — invoice.paid revenue_events INSERT - http.ts:4400-4458 — invoice.payment_failed revenue_events INSERT The third site (charge.refunded at http.ts:4480) uses stripe_charge_id which is NOT a UNIQUE column on revenue_events. The 23505 pattern is unsafe there until a schema migration adds the constraint. Kept the swallow with a comment explaining the gap and pointing at the follow-up scope (add UNIQUE (stripe_charge_id) WHERE revenue_type = 'refund' partial index, then apply the same pattern). Per security-reviewer's framing on #3691: "audit-sync-revenue-backfill is a 90-day workaround that requires running it; refunds older than that window never reconcile." This closes the gap for invoice-based revenue events; refund-side gap remains in the follow-up. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…3694) (#3698) When a Stripe webhook flips an org from a tier with API access to one without, demotePublicAgentsOnTierDowngrade must demote any public-marked agents to members_only and strip them from the org's brand.json — otherwise they stay publicly listed on a tier that doesn't allow public agents (silent entitlement leak). The call site at http.ts:3792 was wrapped in a try/catch that logged and continued. A transient DB error during demotion would silently leave stale public agents until the next tier change. Per js-protocol-expert review on #3691: "you've got an org row claiming the new tier with stale public agents — exactly the silent-swallow class you're trying to retire, just one layer down." Hoists the demote call outside the swallow-on-error block, alongside the core subscription UPDATE. They're a pair: UPDATE writes the new tier; demote enforces the corresponding agent visibility. Idempotent on retry (the helper takes FOR UPDATE on member_profiles, no-ops if no public agents remain) so a Stripe retry that re-fires the tier-downgrade webhook does the right thing. Closes the second of the three triage follow-ups from #3691. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Catch-block audit and customer-relink integration test (the replacement for the originally-planned
stripe_eventstable, after expert review).What changed
1. Core subscription UPDATE no longer silently swallowed
http.ts:3727-3957was the highest-risk silent-swallow path the experts identified during #3681 review. The big UPDATE at line 3738 (which setssubscription_statusand drives entitlement) was wrapped in an outer try/catch that swallowed all errors and returned 200. If that UPDATE failed (DB outage, constraint violation, race), Stripe never retried, the org row was left silently stale, and a paying customer could be denied entitlement until a human noticed.Fix: hoist the core UPDATE outside the swallow-on-error block. UPDATE on a single row by primary key is idempotent — exception now propagates so Stripe retries. Downstream side effects (tier-change enforcement, welcome DMs, autopublish,
.deletedaudit/activities) keep their existing log+continue pattern because they're non-idempotent and a Stripe retry would refire them.2. Integration test for admin link/unlink (was missing)
server/tests/integration/admin-stripe-link-unlink.test.tscovers the hardening shipped in #3681 + the security follow-up:linkpicks the membership sub when customer has multi-sub (thedata[0]regression class — fixture has non-membership sub first)linkwritesadmin_stripe_linkaudit log with admin emailunlinkclears allsubscription_*columns (not juststripe_customer_id— was the original bug)unlinkclears Stripe customermetadata.workos_organization_id(closes the webhook re-link race the security review found)unlinkwritesadmin_stripe_unlinkaudit log with prior state (prior_subscription_status,prior_membership_tier,prior_stripe_subscription_id)5/5 tests pass against the local sandbox + dev DB.
Out of scope (identified, not done)
The same silent-swallow pattern exists at:
http.ts:4195—revenue_eventsINSERT ininvoice.paidhttp.ts:4393— failed payment INSERThttp.ts:4469— refund INSERT incharge.refundedhttp.ts:4506— invoice cache upsertrevenue_events.stripe_invoice_idalready has a UNIQUE constraint, so the right fix isON CONFLICT (stripe_invoice_id) DO NOTHINGplus re-throw on real errors. Tracked as a separate follow-up rather than expanding this PR's surface.Test plan
npx tsc --noEmitcleanadmin-sync-revenue-backfill)admin-stripe-link-unlink)Refs
stripe_eventstable)data[0]fix in /sync), feat(billing): lazy reconcile on certification paywall hit (#3623 step 3) #3663 (lazy reconcile on paywall), fix(billing): clear subscription state on unlink + filter membership sub on link (#3623 step 4) #3681 (admin link/unlink)🤖 Generated with Claude Code