TENANT ISOLATION
Every handler checks the tenant; the cache does not
Every handler in your API scopes its database query to the caller's tenant; an IDOR test against every endpoint passes. The dashboard caches its monthly summary under the key summary:2026-11 for 60 seconds. Acme loads the dashboard, then Globex loads it ten seconds later. What does Globex see?
The IDOR lesson puts the tenant into every query a handler makes. That is necessary and not sufficient. A multi-tenant system shares other things between customers: a cache, a job queue, a search index, a connection pool, an export bucket. Each is a lookup by key, and if the tenant is not part of the key, the lookup crosses tenants. The handler that filled it was correct; the one that reads it never runs the query at all.
The fix is to make the tenant impossible to leave out. Handlers and jobs never touch the raw clients. They get a repository bound to one tenant that adds the tenant to every key and every query, and refuses to run without one. Row-level security in the database is the same rule one layer lower.
// Each handler scopes its own query. The shared pieces do not.
const key = `summary:${month}`; // same key for every tenant
const hit = await cache.get(key);
await queue.add('export-overdue', { requestedBy: user.id }); // no tenant
// worker:
const rows = await db.invoice.findMany({ where: { status: 'overdue' } });
const hits = await index.search({ text: q }); // whole index// One way in: a repository bound to a tenant. Handlers and jobs never see the raw clients.
function forTenant(tenantId: string) {
if (!tenantId) throw new Error('no tenant: refusing to run unscoped');
return {
key: (...parts: string[]) => ['t', tenantId, ...parts].join(':'),
find: (where: object) => db.invoice.findMany({ where: { ...where, tenantId } }), // tenant last: cannot be overridden
search: (text: string) => index.search({ text, filter: { tenantId } }),
};
}
await queue.add('export-overdue', { tenantId: user.tenantId }); // the job carries its tenant
// Below that: Postgres row-level security policies on tenant_id, so a forgotten filter returns no foreign rows.
// Table owners bypass RLS unless the table has FORCE ROW LEVEL SECURITY; superusers always bypass it. Watch the SHARED box. In CACHE, the key turns red as soon as alice fills it, before anyone has seen a leak; the first invariant fails when mallory reads it. In EXPORT JOB the job’s tenantId is empty and the email holds both tenants’ invoices. In FIX every key starts with its tenant, the job carries one, and both invariants stay green.
The cache key is "summary:2026-11" for everyone, and adding an invoice invalidates it. Each handler computes its summary from its own tenant's rows. Order the three steps so that mallory sees acme's numbers.
GOAL: mallory receives acme's summary
Every handler and background job reaches shared infrastructure only through forTenant(tenantId, infra). Write it. key(...parts) builds a cache key; find(filter) queries invoices; search(text) queries the shared search index. The grader interleaves two tenants through a dashboard cache, a search, an export job and a list endpoint that passes the caller's filter through, and checks that no response ever holds the other tenant's rows, that the cache still hits for the same tenant, and that a job with no tenant returns nothing.
Multi-tenant SaaS: Redis or CDN caches keyed by path or month, nightly exports and report emails, webhooks fanned out by a worker, Elasticsearch or OpenSearch indexes shared across customers, vector stores behind an AI feature, analytics warehouses. PostgreSQL row-level security policies give default-deny per table, but table owners bypass them unless the table is set to FORCE ROW LEVEL SECURITY, and superusers always do, so the application must not connect as either.
“How do you guarantee one customer never sees another's data?” Go beyond the handler: list the shared resources (cache, jobs, search, files), say how the tenant gets into each key and payload, describe a scoped repository or row-level security so the check cannot be forgotten, and say how you would test it: two tenants interleaved through every path, asserting that no response holds the other tenant's ids.
USED IN
Chapters that build on this lesson.
- Authentication and authorisation for a multi-tenant SaaS and its public APISecurity
- Kubernetes and edge security: clusters, containers, CDN and WAFSecurity
- Running a security incident: command, customer updates, postmortems and tabletopsSecurity
- Security review when AI agents write the codeSecurity
- Triaging researcher reports: running a disclosure programme day to daySecurity
- Security testing: fuzzing, scanners and abuse casesSoftware Testing and Quality