Skip to content

audit: detect Stripe→DB drift (Lina-class missed-webhook) (closes detect path of #3623) - #3627

Merged
bokelley merged 1 commit into
mainfrom
bokelley/stripe-db-detect
Apr 30, 2026
Merged

bokelley merged 1 commit into
mainfrom
bokelley/stripe-db-detect

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

Adds a new integrity invariant stripe-sub-reflected-in-org-row that walks Stripe (active + trialing membership subs) and flags orgs whose row doesn't reflect the live Stripe state. The inverse direction of the existing org-row-matches-live-stripe-sub.

This is Path A of #3623 — detect-only. Path B (auto-remediation via webhook-equivalent code path) is a separate follow-up that needs to fix subscriptions.data[0] in /sync and add agreement-attestation/audit writes before it's safe to ship.

Why

A real paying member ("Lina"/[email protected], org org_01KM5NSVM6JECGPJNK1HZM1KNT, Stripe customer cus_UF4bVR6XyNSeSk) paid $250 for Professional on 2026-03-30. Stripe recorded the subscription as active. Customer was correctly linked to her org. But customer.subscription.created never updated the org row — subscription_status stayed NULL for ~40 days while she was being billed. She was blocked from paid certification content (S2 Creative Specialist) the whole time. Resolved manually by calling POST /api/admin/accounts/:orgId/sync once.

The existing invariant only checks orgs we already think are subscribed (subscription_status IN ('active','trialing','past_due')). Lina's row had subscription_status = NULL, so the existing invariant was structurally blind to her case.

What it does

For each Stripe subscription with status active or trialing whose price lookup_key starts with aao_membership_ or aao_invoice_:

  • Org row reflects entitlement (subscription_status in active/trialing/past_due) → no-op.
  • Org row exists but doesn't reflect entitlement → critical violation. Paying member is being denied access. Remediation hint points at POST /api/admin/accounts/:orgId/sync.
  • No AAO org linked to the customer → warning, subject customer. Deliberately NOT auto-linked: that path inherits the email-dedup vulnerability in createStripeCustomer and would be a Stripe-customer-hijack-to-membership vector if automated.

Two Stripe API calls (subscriptions.list({status:'active'}), subscriptions.list({status:'trialing'})), one DB query, regardless of customer count.

What it deliberately doesn't do

  • Auto-remediate. Phase 1 of the audit framework is detect-only. Path B / Phase 2 will add safe auto-remediation that goes through a webhook-equivalent code path (so agreement attestation, audit log, and activity records are written — the /sync endpoint skips those).
  • Auto-link orphan Stripe customers. Hijack vector. Humans link via the existing admin tooling.
  • Reverse remediation (downgrade access). Never. The invariant only flags entitlement gaps, not entitlement excess.
  • Filter by subscription_status='canceled' direction. Out of scope for Path A. The existing invariant catches some of this; Path B will rationalize.

Expert review pushback applied

  • adtech / javascript-protocol-expert: don't reuse customers.list + invoice lookups (3N calls); use subscriptions.list({status:'active'|'trialing'}) (2 calls). Done.
  • security-reviewer: never auto-link orphan customers; the /sync endpoint skips agreement-attestation, so any auto-remediation must use a webhook-equivalent path (deferred to Path B). Done.
  • data-analyst: at AAO scale (1,659 orgs, 146 active subs), single-shot run is ~7s with this shape; no cursor needed.

Severity model: critical | warning | info. The original issue text said error, which doesn't exist — corrected to critical.

Test plan

  • Unit tests added covering: happy path, Lina shape (NULL DB row), trialing subs, orphan customer, non-membership filter, missing lookup_key, past_due-as-still-entitled, drift to canceled
  • npx vitest run tests/unit/integrity/ → 46 passed
  • npx tsc --noEmit → clean
  • Pre-commit hook ran full unit + typecheck successfully
  • Once merged + deployed: trigger GET /api/admin/integrity/check/stripe-sub-reflected-in-org-row against prod to surface any other Lina-class members currently being silently denied access (first-run discovery)

Closes / refs

🤖 Generated with Claude Code

…ect)

Walks Stripe (active + trialing membership subs), flags orgs whose row
doesn't reflect the live Stripe state. Inverse direction of the existing
org-row-matches-live-stripe-sub: that one starts at orgs we already
think are subscribed; this starts at Stripe and checks the DB caught up.

Motivating incident: a member paid Professional, Stripe recorded the
sub as active, customer was correctly linked to her org — but
customer.subscription.created never updated the org row. She had
subscription_status=NULL for ~40 days while Stripe billed her, and was
blocked from paid certification content the whole time.

Detect-only by design. Severity 'critical' for orgs whose paid member
is being denied entitlement; 'warning' for orphan Stripe customers
(paid sub, no AAO org link). Orphans are deliberately not auto-linked —
that path inherits a known dedup vulnerability in createStripeCustomer
and would be a Stripe-customer-hijack-to-membership vector if automated.

Filtered to membership lookup_keys (aao_membership_*, aao_invoice_*) so
non-membership subs (one-off events, future products) don't flag.

Tests cover: happy path, Lina shape (NULL DB row), trialing subs,
orphan customer, non-membership filter, missing lookup_key,
past_due-as-still-entitled, drift to canceled.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley
bokelley merged commit fee59f0 into main Apr 30, 2026
13 checks passed
@bokelley
bokelley deleted the bokelley/stripe-db-detect branch April 30, 2026 03:32
bokelley added a commit that referenced this pull request Apr 30, 2026
…rep) (#3643)

Idempotent setup that creates a 6-fixture matrix in Stripe test mode +
local Postgres covering the failure modes the cron auto-remediator must
handle: Lina-class missed-webhook, multi-sub data[0] bug, email mismatch,
orphan customer, WorkOS no-resolution, and a healthy control.

setup-sandbox.ts is idempotent (Stripe customers tagged via
metadata.aao_sandbox_id; DB rows by org-id prefix). Refuses to run unless
STRIPE_SECRET_KEY is sk_test_* and DATABASE_URL is local — protects prod
from accidental sandbox writes.

verify-sandbox.ts runs the stripe-sub-reflected-in-org-row invariant
(merged in #3627) against the local sandbox and prints the violations.
Lets reconciliation work be observed end-to-end without exercising real
member accounts.

Companion infrastructure for #3623. No production code touched; pure
dev tooling. Also serves as the substrate for future billing-flow work
that needs reproducible cross-system fixtures.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
bokelley added a commit that referenced this pull request Apr 30, 2026
…3623 step 2) (#3646)

* fix(billing): /sync picks membership sub, not subscriptions.data[0] (#3623 step 2)

POST /api/admin/accounts/:orgId/sync was reading
customer.subscriptions.data[0] to derive the org's subscription state.
Stripe doesn't guarantee subscription ordering — when a customer has a
non-membership sub (one-off product, future ancillary sub) stacked
alongside a real membership, the wrong sub could win and the org row
would be overwritten with the non-membership sub's state, including
its lookup_key, amount, and status.

Verified against the sandbox multi_sub fixture: Stripe returns the
non-membership (aao_sandbox_event_ticket) sub first in
customer.subscriptions.data; old data[0] picks it; new pickMembershipSub
picks aao_membership_explorer_50 regardless of order.

Extracts pickMembershipSub + isMembershipLookupKey into
server/src/billing/membership-prices.ts so the integrity invariant
(stripe-sub-reflected-in-org-row, merged in #3627) and /sync now share
one predicate. Future cron auto-remediator will reuse the same module.

Tests: 21-case unit test on the helper covering
isMembershipLookupKey predicate (including null/empty),
isMembershipSub on Stripe.Subscription shape, and pickMembershipSub
order-independence + active-over-trialing tiebreak.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(billing): add membership lookup_key to /sync integration fixture

The fixture's mock subscription was missing `lookup_key` on its price.
Now that /sync filters subs by membership lookup_key prefix (#3623 step 2),
a sub without one falls through to the invoice-fallback branch — which
the existing test scenarios don't exercise. Real Stripe membership
prices always carry a lookup_key (the checkout flow creates them via
products with `aao_membership_*` keys), so the fixture was under-spec.

Adds `lookup_key: 'aao_membership_professional_250'` so the four
revenue_events backfill tests reach the subscription-update branch the
fixture was originally written for. No behavior change to /sync.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

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