Repository navigation
feat(billing): integrity invariants framework — Phase 1 (#3181) - #3193
Merged
Merged
Conversation
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
force-pushed
the
bokelley/integrity-invariants
branch
from
April 25, 2026 23:37
3c0834b to
2c95854
Compare
3 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/`
Five invariants (severity: criticals are the ones that would have caught Triton):
Admin endpoints:
Tests
Phase 2 (separate PR, scoped in the design doc)
Phase 3+ (file as separate)
Test plan
References
🤖 Generated with Claude Code