Skip to content

fix(billing): re-throw on core subscription UPDATE failure + relink integration tests (#3623 step 5) - #3691

Merged
bokelley merged 2 commits into
mainfrom
bokelley/webhook-catch-audit
Apr 30, 2026
Merged

bokelley merged 2 commits into
mainfrom
bokelley/webhook-catch-audit

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

Catch-block audit and customer-relink integration test (the replacement for the originally-planned stripe_events table, after expert review).

What changed

1. Core subscription UPDATE no longer silently swallowed

http.ts:3727-3957 was the highest-risk silent-swallow path the experts identified during #3681 review. The big UPDATE at line 3738 (which sets subscription_status and 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, .deleted audit/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.ts covers the hardening shipped in #3681 + the security follow-up:

  • link picks the membership sub when customer has multi-sub (the data[0] regression class — fixture has non-membership sub first)
  • link writes admin_stripe_link audit log with admin email
  • unlink clears all subscription_* columns (not just stripe_customer_id — was the original bug)
  • unlink clears Stripe customer metadata.workos_organization_id (closes the webhook re-link race the security review found)
  • unlink writes admin_stripe_unlink audit 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_events INSERT in invoice.paid
  • http.ts:4393 — failed payment INSERT
  • http.ts:4469 — refund INSERT in charge.refunded
  • http.ts:4506 — invoice cache upsert

revenue_events.stripe_invoice_id already has a UNIQUE constraint, so the right fix is ON CONFLICT (stripe_invoice_id) DO NOTHING plus re-throw on real errors. Tracked as a separate follow-up rather than expanding this PR's surface.

Test plan

  • npx tsc --noEmit clean
  • 78 unit tests pass; 4 prior integration tests still pass (admin-sync-revenue-backfill)
  • 5 new integration tests pass (admin-stripe-link-unlink)
  • Pre-commit hook (unit + dynamic imports + typecheck) passes
  • Reviewer: confirm the hoisted UPDATE pattern doesn't break any existing webhook test fixture

Refs

🤖 Generated with Claude Code

…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]>
@bokelley

Copy link
Copy Markdown
Contributor Author

Expert review pass — pushed fix commit (2d2b909)

Two findings addressed:

M1 — .deleted audit log was not in its own try/catch. The subscription_cancelled audit_log + org_activities INSERTs were awaited inside the outer try/catch that swallowed errors. If they failed transiently, the failure jumped to the swallow and no row was ever recorded — worst-of-both-worlds: subscription_status update committed (separate write earlier), audit/activity row missing forever, Stripe sees 200 and never retries. Now each has its own try/catch with notifySystemError.

M2 — admin unlink left step-3 webhook fallback open. #3681 cleared customer.metadata.workos_organization_id, but resolveOrgForStripeCustomer (webhook-helpers.ts:27-90) has three fallback paths:

  1. DB stripe_customer_id (cleared by the unlink UPDATE)
  2. customer.metadata.workos_organization_id (cleared in fix(billing): clear subscription state on unlink + filter membership sub on link (#3623 step 4) #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. 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

  • revenue_events silent-swallow at http.ts:4195/4393/4469 — should use ON CONFLICT (stripe_invoice_id) DO NOTHING + re-throw on real errors. Financial integrity issue per security review (audit-sync-revenue-backfill is a 90-day workaround).
  • demotePublicAgentsOnTierDowngrade swallow at http.ts:3782 — entitlement-class side effect. Agents stay public when tier downgrades if helper fails.
  • Anthropic-5xx flaky tests — the chronic flakes on brand-classifier / brand-enrichment / prospect-triage integration tests mask real regressions in those handlers. Quarantine to a :flaky tag.

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.

@bokelley
bokelley merged commit 3681806 into main Apr 30, 2026
12 checks passed
@bokelley
bokelley deleted the bokelley/webhook-catch-audit branch April 30, 2026 20:03
bokelley added a commit that referenced this pull request Apr 30, 2026
) (#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]>
bokelley added a commit that referenced this pull request Apr 30, 2026
…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]>
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.

1 participant