Broken tenant isolation¶
When is it relevant¶
The app serves several tenants (organizations, companies, workspaces, projects) from shared code or data, and the change adds or modifies something that touches tenant-owned data or tenant membership: an entry point, query, background job, cache or file path.
Attack¶
A member of tenant A reaches tenant B's data or actions. Typical ways in:
- Passing one of B's resource IDs to a route that checks only the caller's role or account type, not the resource's tenant.
- Switching tenants with a header or parameter that isn't checked against membership.
- A query, job or cache key that is missing the tenant filter.
- A query that is scoped to the caller's tenant, but merges caller-supplied filters in after the scope, so a
tenantIdfilter in the request replaces it. Allowlists of filterable fields built from the model's columns let the tenant key through. - Obtaining a credential or token that acts inside B.
Mitigation¶
- Derive the tenants a caller may act in from their authenticated identity (membership), never from client input alone.
- On every lookup of a tenant-owned resource, check that the resource's tenant is one the caller belongs to, before reading or acting.
- Apply the tenant filter centrally (repository or query helper), including keys, tokens, files, jobs and caches.
- Add the tenant condition last, so caller-supplied filters can't replace it, and allowlist filterable fields explicitly rather than deriving them from the model.
- Bind issued credentials to the tenant they were created in.
Test¶
- Point-in-time: with users in two tenants, have tenant B's user reach tenant A's resources by ID, by switching the tenant header or parameter, and through exports, jobs and file paths.
- Continuous: a two-tenant integration test in CI, and a lint or code-review rule that every query on a tenant-owned table goes through the tenant-scoped helper.
Examples¶
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
| Tenant in every query filter | Small codebases; explicit at each call site | Mongoose queries |
| Tenant-scoped repository or Mongoose plugin | Many handlers; one place to get it right | Mongoose plugins |
| Database row-level security | Postgres, and you want the DB to enforce it | node-postgres |
Vulnerable — tenant taken from the request
router.get('/invoices', requireAuth, async (req, res) => {
const tenantId = req.headers['x-tenant-id'] || req.query.tenantId
res.json(await Invoice.find({ tenantId })) // caller picks the tenant
})
Vulnerable — object ID trusted once authenticated
router.get('/invoices/:id', requireAuth, async (req, res) => {
res.json(await Invoice.findById(req.params.id)) // any tenant's invoice
})
Vulnerable — tenant-scoped, then overridden by a filter
// filterable fields derived from the model: tenantId is a path, so it's "allowed"
const FILTERABLE = new Set(Object.keys(Recipe.schema.paths))
router.get('/kitchens/:kitchenId/recipes', requireAuth, requireMember, async (req, res) => {
const filters = {}
for (const [key, value] of Object.entries(req.query)) {
if (!FILTERABLE.has(key)) return res.status(400).json({ error: `Unknown filter ${key}` })
filters[key] = String(value)
}
const where = { kitchenId: req.params.kitchenId, ...filters } // later key wins
res.json(await Recipe.find(where))
})
requireMember checks the path's kitchen, and the query starts scoped to it,
so the obvious IDOR (/kitchens/1/recipes) is blocked. But
/kitchens/2/recipes?kitchenId=1 passes the allowlist, and in an object
literal the later kitchenId replaces the trusted one. The guard authorizes
one tenant and the query reads another. Neither defect leaks on its own: a
model-derived allowlist always includes the tenant, ownership and audit
fields, and the spread order decides whether that matters. The same happens
with Object.assign(where, filters), a TypeORM { kitchenId, ...columns },
or a list derived from repo.metadata.columns.
Mitigated — filter on the server's copy of the tenant
function tenantContext(req, res, next) {
req.tenantId = req.user.tenantId // from the session, never the request
if (!req.tenantId) return res.sendStatus(403)
next()
}
router.get('/invoices/:id', requireAuth, tenantContext, async (req, res) => {
const invoice = await Invoice.findOne({ _id: req.params.id, tenantId: req.tenantId })
if (!invoice) return res.sendStatus(404)
res.json(invoice)
})
Mitigated — scoped repository
export function invoicesFor(tenantId) {
const scope = { tenantId }
return {
list: (q = {}) => Invoice.find({ ...q, ...scope }), // scope wins over q
byId: (id) => Invoice.findOne({ _id: id, ...scope }),
update: (id, u) => Invoice.updateOne({ _id: id, ...scope }, u),
}
}
Spreading the scope last matters: { ...scope, ...q } would let a caller
pass tenantId in q and override it. Allowlist the filterable fields
explicitly too (['name', 'category', 'createdBy']), so tenantId is
rejected with a 400 before it reaches the repository.
Docs: Mongoose queries
Mitigated — row-level security
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::uuid);
Docs: PostgreSQL row security policies · node-postgres
Bypasses to check
- Tenant read from anything the caller controls: header, query, body, subdomain
taken from the
Hostheader, or a JWT claim that isn't verified. - A query that filters by ID only, on the assumption that IDs are unique and unguessable (UUIDs leak through exports, webhooks and error messages).
- Aggregations,
populate(),JOINs, counts, search indexes and report queries that drop the tenant filter the simple finder has. - Bulk and admin paths:
updateMany,deleteMany, CSV export, background jobs that iterate all rows. - Caches keyed without the tenant, so one tenant's response is served to another.
- Check then change: membership verified for the tenant in the session,
then the write uses
req.body.tenantId. - Scope then override: the tenant key is set first and caller filters are
merged after it (
{ tenantId, ...filters },Object.assign), with the filter allowlist built from the model (schema.paths,metadata.columns,PartialType(Entity)). Send?tenantId=<other>on a list or search route in your own tenant. - Cross-tenant references accepted as input: moving a record into another tenant's project, or inviting by an ID that belongs elsewhere.
What to grep for
tenantId,orgId,workspaceId,accountId,x-tenantfind(,findOne(,aggregate(,updateMany(,deleteMany(,populate(req.headers[,req.query.,req.body.next to a tenant field...filters,...req.query,Object.assign(in a query object;schema.paths,metadata.columnsused as an allowlist
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
Tenant in every repository method (findByIdAndTenantId) |
Small codebases; explicit at each call site | Spring Data query methods |
| Tenant-scoped service or repository wrapper | Many controllers; one place to get it right | Spring Data MongoDB Criteria |
Hibernate @TenantId (discriminator multi-tenancy) |
JPA with Hibernate 6; the ORM adds the filter | Hibernate multi-tenancy |
| Database row-level security | PostgreSQL, and you want the database to enforce it | PostgreSQL row security |
The tenant may be an organization, workspace or project. Derive the set of tenants the caller belongs to from the authenticated user (a membership lookup, or a verified token claim), never from a header or parameter alone.
Vulnerable — tenant taken from the request
@GetMapping("/api/invoices")
public List<Invoice> list(@RequestHeader("X-Tenant-Id") String tenantId) {
return invoices.findByTenantId(tenantId); // caller picks the tenant
}
Vulnerable — object ID trusted once authenticated
@GetMapping("/api/invoices/{id}")
public Invoice get(@PathVariable String id) {
return invoices.findById(id).orElseThrow(); // any tenant's invoice
}
Vulnerable — tenant-scoped, then overridden by a filter
// filterable fields derived from the model: tenantId is a property, so it's "allowed"
private static final Set<String> FILTERABLE = Arrays.stream(Recipe.class.getDeclaredFields())
.map(Field::getName).collect(Collectors.toSet());
@GetMapping("/api/kitchens/{kitchenId}/recipes")
public List<Recipe> list(@PathVariable String kitchenId, @RequestParam Map<String, String> params) {
kitchens.requireMember(kitchenId, CurrentUser.id()); // checks the path's kitchen
if (!FILTERABLE.containsAll(params.keySet())) throw new ApiException(BAD_REQUEST, "Unknown filter");
Document filter = new Document("kitchenId", kitchenId);
filter.putAll(params); // ?kitchenId=<other> replaces it
return mongo.find(new BasicQuery(filter), Recipe.class);
}
The guard authorizes one tenant and the query reads another.
/api/kitchens/1/recipes as an outsider is correctly refused, which is why
this survives testing; /api/kitchens/<mine>/recipes?kitchenId=1 isn't. Any
map that starts with the tenant key and then merges caller input behaves the
same: HashMap.putAll, Document.putAll, or an Example.of(probe) whose
probe is bound from request parameters after the tenant was set on it. A model-derived allowlist (getDeclaredFields(), JPA
Metamodel, MongoPersistentEntity properties) always contains the tenant,
ownership and audit fields.
Mitigated — the server's copy of the tenant, in the query
interface InvoiceRepository extends MongoRepository<Invoice, String> {
Optional<Invoice> findByIdAndTenantId(String id, String tenantId);
List<Invoice> findByTenantId(String tenantId);
}
@GetMapping("/api/orgs/{orgId}/invoices/{id}")
public Invoice get(@PathVariable String orgId, @PathVariable String id) {
memberships.require(orgId, CurrentUser.id()); // from the identity
return invoices.findByIdAndTenantId(id, orgId).orElseThrow(NotFound::new);
}
Docs: Spring Data MongoDB repositories
Mitigated — scoped query builder, tenant applied last
private static final Set<String> FILTERABLE = Set.of("name", "category", "createdBy"); // explicit
public List<Recipe> list(String kitchenId, Map<String, String> params) {
Criteria criteria = new Criteria();
params.forEach((key, value) -> {
if (!FILTERABLE.contains(key)) throw new ApiException(BAD_REQUEST, "Unknown filter " + key);
criteria.and(key).is(value);
});
criteria.and("kitchenId").is(kitchenId); // trusted key, set by the server
return mongo.find(Query.query(criteria), Recipe.class);
}
Two layers: the allowlist rejects kitchenId outright, and the tenant
condition is added by the server after the caller's filters. With Criteria,
a second condition on the same key throws instead of replacing the first,
which also fails safe.
Docs: Criteria and Query
Mitigated — Hibernate @TenantId
@Entity
public class Invoice {
@Id Long id;
@TenantId String tenantId; // Hibernate adds "tenant_id = ?" to every query
}
@Component
class TenantResolver implements CurrentTenantIdentifierResolver<String> {
public String resolveCurrentTenantIdentifier() {
return TenantContext.current(); // set from the authenticated user, per request
}
public boolean validateExistingCurrentSessions() { return true; }
}
Docs: Hibernate @TenantId
Mitigated — row-level security
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::uuid);
Run it inside the request's transaction (true makes it transaction-local), so
a pooled connection can't carry one tenant's setting into another request.
Docs: PostgreSQL row security policies · JdbcTemplate
Bypasses to check
- Tenant read from anything the caller controls:
@RequestHeader,@RequestParam, a body field, theHostsubdomain, or a JWT claim the filter didn't verify. - Scope then override: the tenant key set first and request parameters
merged after it (
putAll,Document.putAll, a probe bound from@ModelAttribute), with the filter allowlist derived from the model. Send?tenantId=<other>on list, search and export routes in your own tenant. CrudRepository.findById/deleteByIdused next to scoped finders. Hibernate@Filterdoesn't apply tofindById(EntityManager.find) or native queries.@Query(nativeQuery = true),JdbcTemplate, aggregations (mongo.aggregate),$lookup, counts and report queries that drop the tenant condition the simple finder has.- A
ThreadLocaltenant context that isn't cleared in afinally, or isn't propagated to@Async,CompletableFutureand scheduled jobs, so one tenant's ID leaks into another request on the same thread. - Caches (
@Cacheable) keyed without the tenant. - Check then change: membership checked for the path's tenant, then the
write uses
body.getTenantId()orentity.setTenantId(request…). - Cross-tenant references accepted as input: assigning a task to a user in another project, or moving a record by setting its parent ID.
What to grep for
tenantId,orgId,workspaceId,projectId,X-TenantfindById(,deleteById(,nativeQuery = true,aggregate(,@CacheableputAll(,new Document(,BasicQuery(,Example.of(,@RequestParam MapgetDeclaredFields(),getMetamodel(),getPersistentEntity(used to build an allowlist@TenantId,@Filter,CurrentTenantIdentifierResolver,ThreadLocal
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
| Tenant ID from the session, added to every query | Shared collections or tables with a tenant_id field |
Flask g |
| A store layer whose methods all require the tenant | Many routes; makes an unscoped query hard to write | Flask application structure |
SQLAlchemy with_loader_criteria / PostgreSQL row-level security |
SQL databases; the filter applies to every query | with_loader_criteria, PostgreSQL RLS |
Vulnerable — tenant taken from the request
@app.get('/api/invoices')
@require_token
def invoices():
org = request.args['org_id'] # any org the caller names
return jsonify([serialize(i) for i in db.invoices.find({'org_id': org})])
Vulnerable — the tenant is checked, then a bulk query drops it
org = require_member(g.user, org_slug)
ids = request.args.getlist('id')
return jsonify([serialize(i) for i in db.invoices.find({'_id': {'$in': [ObjectId(x) for x in ids]}})])
Mitigated — every store method takes the tenant
class InvoiceStore:
def __init__(self, db): self.col = db.invoices
def list(self, org_id, ids=None):
criteria = {'org_id': org_id}
if ids:
criteria['_id'] = {'$in': [o for o in map(to_object_id, ids) if o]}
return [serialize(d) for d in self.col.find(criteria)]
@app.get('/api/orgs/<slug>/invoices')
@require_token
def invoices(slug):
org = require_member(g.user, slug) # 404 unless the caller belongs to it
return jsonify(invoice_store.list(org['id'], request.args.getlist('id')))
Docs: PyMongo find
Bypasses to check
- Aggregation pipelines,
count_documents,distinctand exports that build their own filter. - Background jobs and webhooks that run outside a request and so have no
g.user. They must carry the tenant explicitly. - Cache keys without the tenant, such as
cache.get(f'invoice:{id}'). - Files stored under paths that don't include the tenant.
What to grep for
org_id,tenant_id,account_id,request.args.get('org,getlist(find(,aggregate(,count_documents(,distinct(,$in