Skip to content

Webhook-side dedup: refuse customer.subscription.created when org already has one #3184

Closed

Description

@bokelley

Problem

PR #3183 closed the millisecond intake race for the two routes that directly mint a Stripe subscription (`POST /api/invoice-request` and `POST /api/invite/:token/accept`) by wrapping them in a per-org Postgres advisory lock.

`POST /api/checkout-session` was deliberately left out because the actual subscription doesn't get created until the user completes Stripe's hosted checkout page. Two concurrent calls produce two session URLs, not two subscriptions. The duplicate-sub case only materializes if the user pays on both sessions.

That's a real (if narrow) gap. The cross-path version is also real:

T+0:    user opens dashboard, clicks "Pay by card"          → checkout-session #1 minted, no sub yet on Stripe
T+10ms: admin pastes invite-accept link in Slack, user clicks it
T+11ms: invite-accept route takes advisory lock, runs blockIfActiveSubscription
        → Stripe still has no sub (session #1 incomplete)
        → guard passes, mints invoice-driven sub via createAndSendInvoice
T+20ms: user goes back to first tab, completes Stripe Checkout #1 → second sub created

The advisory lock can't see this because the in-flight checkout-session has no Stripe-side state to read until the user pays.

Fix: webhook-side dedup

The right place to close this is in the `customer.subscription.created` webhook handler. By the time the webhook fires, Stripe has already created the second sub on the customer — so we can detect it and act.

`server/src/http.ts:3450` is where the subscription-created event is processed. Add:

case 'customer.subscription.created': {
  const subscription = event.data.object as Stripe.Subscription;
  const customerId = subscription.customer as string;

  // Reject if the customer already has another active subscription. Stripe
  // already accepted this one, so we cancel it and refund any charge.
  const existing = await stripe.subscriptions.list({
    customer: customerId,
    status: 'active',
    limit: 10,
  });
  const otherActive = existing.data.filter(s => s.id !== subscription.id);
  if (otherActive.length > 0) {
    logger.error({
      newSubId: subscription.id,
      existingSubIds: otherActive.map(s => s.id),
      customerId,
    }, 'Refusing duplicate subscription on customer that already has active sub');
    await stripe.subscriptions.cancel(subscription.id, { prorate: true });
    notifySystemError({
      source: 'stripe-subscription-dedup',
      errorMessage: \`Duplicate subscription \${subscription.id} canceled; existing: \${otherActive.map(s => s.id).join(', ')}\`,
    });
    return res.status(200).send('ok'); // ack the webhook
  }
  // ... existing handler logic
}

Why this isn't a blocker for #3183

Acceptance criteria

  • `customer.subscription.created` webhook detects when the customer has another active subscription, cancels the new one with proration refund, and logs/alerts.
  • The cancellation respects Stripe's webhook retry semantics (idempotent: re-firing the webhook produces the same outcome).
  • Test case: simulate two webhook events arriving for the same customer in quick succession; assert second one is canceled.
  • Logged + alerted (notifySystemError) so operators know a duplicate was caught.

References

Activity

  1. added
    enhancement
    claude-triaging
    on Apr 25, 2026
  2. bokelley commented on Apr 25, 2026

    @bokelley
    ContributorAuthor

    Triage

    Classification: Bug (gap in subscription dedup after advisory lock)
    Bucket(s): admin / ops tools (server/src/http.ts webhook handler)
    Status: ready-for-human

    What the experts said:

    • code-reviewer: 6 blockers — status filter covers only active (should be TIER_PRESERVING_STATUSES), idempotency gap on webhook retry, wrong placement (new case would shadow the existing 3-event handler), prorate: true deprecated in SDK v10, res.send('ok') breaks response contract, no tests
    • security-reviewer: 1 blocker — auto-cancel cascades to customer.subscription.deleted, which the existing DB-update block processes unconditionally, overwriting organizations.subscription_status → canceled and stripe_subscription_id → duplicate and corrupting the legitimate record. External subscription creation on our Stripe customer (customer ID isn't secret) amplifies the attack surface.

    My take: Approach is sound, two architectural decisions need your call. Subscriptions our server creates do carry workos_organization_id metadata (stripe-client.ts:1129), so an ownership check is viable — but the DB-update guard and the cancel-with-no-proration tradeoff need an explicit choice before a PR can be written cleanly.

    The DB corruption path: dedup cancels sub_B → Stripe fires customer.subscription.deleted for sub_B → existing handler runs unconditionally → UPDATE organizations SET subscription_status='canceled', stripe_subscription_id='sub_B' → org appears dead even though sub_A is still active on Stripe.

    Option A — Full safe fix: ownership check + DB-update guard

     // customer.subscription.created handler — before handleSubscriptionCreated:
    +const subOrgId = (subscription.metadata as Record<string,string>)?.workos_organization_id;
    +if (!subOrgId || subOrgId !== org.workos_organization_id) {
    +  logger.warn({ subscriptionId: subscription.id }, 'External subscription on our customer — alerting, not canceling');
    +  notifySystemError({ source: 'stripe-external-sub', errorMessage: `Unexpected sub ${subscription.id} on ${customerId}` });
    +  break;
    +}
    +const otherLive = (await stripe.subscriptions.list({ customer: customerId, status: 'all', limit: 100 }))
    +  .data.filter(s => s.id !== subscription.id && (TIER_PRESERVING_STATUSES as readonly string[]).includes(s.status));
    +if (otherLive.length > 0) {
    +  try { await stripe.subscriptions.cancel(subscription.id); } catch { /* already canceled on retry */ }
    +  notifySystemError({ source: 'stripe-subscription-dedup', errorMessage: `Duplicate ${subscription.id} canceled` });
    +  break;
    +}
    
     // shared DB-update block — all three event types — add before UPDATE:
    +if (event.type === 'customer.subscription.deleted'
    +    && org.stripe_subscription_id
    +    && subscription.id !== org.stripe_subscription_id) {
    +  break; // skip overwrite for a non-current subscription (e.g., the just-canceled duplicate)
    +}

    Closes the external-sub and DB-corruption paths. Four files touched + tests.

    Option B — Alert-only: detect but do not cancel

    +if (otherLive.length > 0) {
    +  logger.warn({ newSubId: subscription.id, existingSubIds: otherLive.map(s => s.id) },
    +    'Duplicate subscription detected — alerting, manual cancel required');
    +  notifySystemError({ source: 'stripe-subscription-dedup', errorMessage: `Duplicate sub ${subscription.id} needs manual cancel` });
    +  break;
    +}

    Gap stays open; finance catches via alert and cancels manually. No DB corruption risk. Simpler to ship, but leaves the cross-path race partially unresolved.

    @bokelley, your call: Option A (full fix — safe to auto-execute once you confirm) or Option B (alert-only, faster to ship)?


    Triaged by Claude Code. Session: https://claude.ai/code/cse_01XQiHh6mgiqqwWHGq6yS67q


    Generated by Claude Code

  3. added
    claude-triaged
    and removed
    claude-triaging
    on Apr 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    claude-triagedenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions