Skip to content

feat(billing): integrity invariants framework — Phase 1 (#3181) - #3193

Merged
bokelley merged 3 commits into
mainfrom
bokelley/integrity-invariants
Apr 25, 2026
Merged

bokelley merged 3 commits into
mainfrom
bokelley/integrity-invariants

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

Closes the immediate scope of #3181 by adding a small framework for cross-system data-integrity invariants, plus the five Phase-1 checks that would have caught the Triton/Encypher incident months before it surfaced.

The framing: WorkOS, Stripe, and AAO Postgres are three independent stores of truth. Today nothing audits whether they agree — webhooks mostly keep things current, but lost events and dashboard-edit drift go undetected. This framework gives each invariant a tiny self-contained shape (`Invariant.check(ctx) → Violation[]`) and a runner that orchestrates them, isolates failures, and produces a per-violation report.

What's in Phase 1

Module: `server/src/audit/integrity/`

  • `types.ts` — `Invariant`, `Violation`, `InvariantContext`, `InvariantRunReport`
  • `runner.ts` — `runAllInvariants(invariants, ctx)` and `runOneInvariant(invariant, ctx)`. Sequential by design; one invariant throwing becomes a meta-violation, doesn't cancel the rest.
  • `invariants/` — five Phase-1 checks (3 critical, 2 warning)
  • `README.md` — how to add an invariant

Five invariants (severity: criticals are the ones that would have caught Triton):

Invariant Severity Catches
`stripe-customer-org-metadata-bidirectional` critical Triton-shape: customer.metadata.workos_organization_id != org.workos_organization_id
`one-active-stripe-sub-per-org` critical Two simultaneous live subs on one customer (the literal Triton incident)
`stripe-customer-resolves` critical Org references a deleted or non-existent Stripe customer
`org-row-matches-live-stripe-sub` warning DB tier/amount/status drift from Stripe (webhook-miss)
`workos-membership-row-exists-in-workos` warning, sampled Stale org_memberships rows from missed delete webhooks

Admin endpoints:

  • `GET /api/admin/integrity/invariants` — list registered invariants
  • `GET /api/admin/integrity/check` — run all, return aggregate report
  • `GET /api/admin/integrity/check/:name` — run one
  • All admin-only. `?sample_size=N` and `?since=ISO8601` query params for tunables.

Tests

  • 29 unit tests across runner + 5 invariants. Each test mocks the `InvariantContext` (DB pool, Stripe, WorkOS) so invariants can be exercised in isolation.
  • Each invariant has explicit happy-path and failure-mode coverage. The Triton failure mode (`one-active-stripe-sub-per-org` with two live subs) is asserted directly.

Phase 2 (separate PR, scoped in the design doc)

  • Scheduled runs via the existing `server/src/addie/jobs/scheduler.ts` framework
  • Persisted reports in an `integrity_runs` / `integrity_violations` table
  • Slack alerting via `notifySystemError` on critical violations
  • Admin dashboard page (`/admin/integrity`)
  • Stripe Customer Portal config invariant (the original narrow Audit Stripe Customer Portal config for grandfathered-pricing safety #3181 ask — checking that grandfathered prices aren't exposed in `subscription_update.products`)

Phase 3+ (file as separate)

  • Webhook-miss detection (compare Stripe event log to local idempotency-token log)
  • Auto-quarantine for criticals (pause billing intake until violation clears)
  • Inverse walk: enumerate Stripe customers / WorkOS orgs to catch orphans (entities in external store with no AAO row)
  • One-click admin remediation for common violation shapes

Test plan

  • `npm run typecheck` — clean
  • `npm run test:server-unit` — 122/123 files pass (1 skipped, no failures)
  • Manual: run `GET /api/admin/integrity/check` against staging; confirm no critical violations on a healthy fleet
  • Manual: run `GET /api/admin/integrity/check/one-active-stripe-sub-per-org` against staging; sanity check timing (~30s for full Stripe enumeration is normal)

References

🤖 Generated with Claude Code

bokelley and others added 3 commits April 25, 2026 19:36
Adds a small framework where each invariant is a self-contained
assertion about cross-system state (WorkOS ↔ Stripe ↔ AAO Postgres).
The runner executes them sequentially, isolates failures, and produces
a per-violation report. New admin endpoints surface the report on
demand:

  GET /api/admin/integrity/invariants
  GET /api/admin/integrity/check
  GET /api/admin/integrity/check/:name

Phase 1 ships five invariants. Three are critical and would have caught
the Triton/Encypher incident months before it surfaced via Slack:

  • stripe-customer-org-metadata-bidirectional — Stripe customer's
    metadata.workos_organization_id matches the AAO org that
    references it. Catches the literal cross-contamination shape.
  • one-active-stripe-sub-per-org — at most one live (active/trialing/
    past_due) Stripe subscription per customer. Triton had two.
  • stripe-customer-resolves — every org.stripe_customer_id resolves
    to a non-deleted Stripe customer.

Two are warnings (transient drift, not active financial damage):

  • org-row-matches-live-stripe-sub — DB-mirrored fields (amount,
    lookup_key, status) match what Stripe currently reports.
  • workos-membership-row-exists-in-workos — random sample of active
    organization_memberships rows are reflected in WorkOS.

Adding new invariants is a one-file drop in
server/src/audit/integrity/invariants/ + a registry import. README
explains the contract. Tests mock the InvariantContext shape so each
invariant is unit-testable in isolation (29 new tests).

Phase 2 (separate PR) will add scheduled runs via the existing job
scheduler, persisted run reports, Slack alerts on critical violations,
and an admin dashboard page.

Closes the immediate scope of #3181; broader follow-ups remain open.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Coalesce Stripe customer fetches across invariants. Three Phase-1
  invariants call customers.retrieve for the same set of orgs; the
  runner now allocates a per-run shared Map cache. New helper
  getStripeCustomerCached() in stripe-helpers.ts reads from / writes
  to the cache; failures fall through to per-invariant warning paths
  rather than caching null. (security M2)
- Cap sample_size at 1000 (was 10_000). Each unit costs ≥1 external
  API call; 1000 is well above any realistic run while preventing a
  misclick from burning rate-limit budget. (security M1)
- Reject malformed sample_size and since query params with 400
  + a clear field/message body, instead of silently dropping the
  query and using defaults. (code-reviewer)
- Add detectEnvMismatch() guard that returns 412 when STRIPE_SECRET_KEY
  mode (test/live) and DATABASE_URL appear inconsistent. Prevents
  a staging app pointed at a live key (or vice versa) from reporting
  thousands of phantom critical violations against mismatched stores.
  (security L1)
- Symmetric error response shape on /check/:name (was missing the
  message field that /check has).  (code-reviewer)
- Extract shared isStripeNotFound() to stripe-helpers.ts; removes the
  duplicate definitions in two invariants. (code-reviewer)
- Tests: +9 new (cache sharing across invariants in one run, helper
  retry-on-error, isStripeNotFound shape detection); existing tests
  unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Semgrep `error-message-leak`: don't expose `err.message` to admin
  clients on integrity-check failures. Log the error server-side and
  return a generic "See server logs for details" message.
- CodeQL `js/incomplete-url-substring-sanitization`: replace raw
  string `.includes(...)` checks against DATABASE_URL with proper URL
  parsing + hostname inspection. The substring check would match a
  hostile URL with `agenticadvertising.org` in the path/query rather
  than the host. Now we parse the URL and check `host.endsWith(...)`
  / `host === ...` for known prod patterns. If the URL fails to
  parse, treat as non-prod (so a live key against a malformed URL is
  still refused by the env-mismatch guard).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley
bokelley force-pushed the bokelley/integrity-invariants branch from 3c0834b to 2c95854 Compare April 25, 2026 23:37
@bokelley
bokelley merged commit cfd4144 into main Apr 25, 2026
12 checks passed
@bokelley
bokelley deleted the bokelley/integrity-invariants branch April 25, 2026 23:45
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.

2 participants