Imagine a small SaaS app for invoicing. A user from Acme logs in, opens an invoice at /invoices/123, and out of curiosity changes the number to 124. The page loads. It's an invoice for a completely different company, with that company's customer names, amounts, and addresses.
Nothing was wrong with authentication. The user was who they said they were. What failed was the check that this particular record belongs to the company the user works for. That gap has a name, broken object level authorization (BOLA), and it's one of the most common ways APIs leak data.
The fix is a habit, not a single check:
- Derive the tenant from the verified identity, never from a value the client sends as proof.
- Scope every query by tenant, so the database only returns rows the caller is allowed to see.
- Back it with PostgreSQL row-level security, so one missed filter doesn't become a breach.
- Cover every entry point, including Server Actions, background jobs, caches, and file storage.
- Prove it with tests that use two tenants and try to cross between them.
This article focuses on scoping data to the right customer. If you're deciding how roles and permissions fit together in NestJS, that's a related but separate question about route-level guards versus resource-level checks. Library behavior below reflects the NestJS, Prisma, TypeORM, PostgreSQL 18, and Next.js documentation as of November 2026.
What this bug is called, and why it's so common
OWASP ranks broken object level authorization first in its API Security Top 10. The 2023 edition is still the latest as of November 2026. OWASP's advice is to use an authorization mechanism to check whether the logged-in user "has access to perform the requested action on the record" in "every function that uses an input from the client to access a record in the database."
You'll also see it called an insecure direct object reference (IDOR). MITRE tracks it as CWE-639, "Authorization Bypass Through User-Controlled Key," and lists both IDOR and BOLA as alternate terms. In MITRE's 2025 CWE Top 25, Missing Authorization (CWE-862) ranks fourth, and CWE-639 entered the list at 24th.
Government agencies have warned about it directly. In July 2023, CISA, the NSA, and Australia's ACSC published a joint advisory on IDOR, saying these vulnerabilities "are frequently exploited by malicious actors in data breach incidents." A well-known example: in 2018, KrebsOnSecurity reported that a USPS API let any logged-in usps.com user query account details for other users, affecting about 60 million accounts.
It's common because the object ID comes from the client by design. Every endpoint that takes an ID needs a matching check, and it only takes one forgotten function for the check to be missing.
Unguessable IDs aren't authorization
A common first reaction is to switch from sequential integers to UUIDs so nobody can guess 124. That makes guessing harder, but it doesn't make access safe.
RFC 9562, the current UUID standard, says "Implementations SHOULD NOT assume that UUIDs are hard to guess" and that UUIDs "MUST NOT be used as security capabilities (identifiers whose mere possession grants access)." OWASP's IDOR Prevention Cheat Sheet says the same thing from the other side: complex identifiers can make guessing impractical, but "even with complex identifiers, access control checks are essential."
IDs also leak in ordinary ways: shared links, screenshots, support tickets, logs, exports, and other users who legitimately saw the record. Choose your ID type for reasons like indexing and URL design. Note that UUIDv7 embeds a timestamp, which RFC 9562 says poses a small attack surface. Either way, treat the ID as a lookup key, never as proof of access.
Where the tenant comes from
Every scoped query needs a tenant value it can trust. OWASP's Multi-Tenant Application Security Cheat Sheet puts it directly: "Treat client-supplied tenant identifiers as selectors only." Bind the tenant "to a server-verified identity and current tenant membership."
In a NestJS API, that usually means:
- Authentication puts the verified user on the request. The NestJS guards docs describe it as "common practice to attach the authorized user to the request object."
- The tenant comes from that identity. A user who belongs to one organization gets that organization's ID from the token or session lookup.
- If users can switch between organizations, a header or route parameter can select one, but the server must confirm the user is currently a member before using it. The header chooses; the membership check authorizes.
- Clients never set tenant or owner fields directly. Strip
tenantIdandownerIdfrom create and update DTOs, and set them on the server from the request context. Otherwise, a client can create or move a record into another tenant by including the field in the body. OWASP's API3 (broken object property level authorization) covers this kind of mass assignment.
Scope the query, don't fetch and compare
There are two ways to check that a record belongs to the caller.
Fetch, then compare: load the invoice by ID, then check that invoice.tenantId matches the caller's tenant before returning it. This works if every function remembers to compare, and if nothing between the check and the action uses only the ID.
Scope the query: include the tenant in the lookup itself, the equivalent of WHERE id = $1 AND tenant_id = $2. If the invoice belongs to another tenant, the query finds nothing, and the API returns 404 the same way it would for an ID that doesn't exist.
For reads, updates, and deletes, scoping the query is the safer default. It removes the separate comparison step that can be forgotten, and an update or delete scoped by both ID and tenant can't touch another tenant's row even if earlier code made a mistake. OWASP's IDOR cheat sheet shows this pattern with repository methods like findByIdAndOwnerId.
Lists follow the same rule. The current NestJS authorization docs, which as of November 2026 use an official @nestjs/authorization package with policy classes, put it simply: "Filter lists in the query; policies check one record at a time." They also say "Checks that need a record belong in the service," so every caller of that service gets the same rule. Many older tutorials follow an earlier CASL-based recipe, so their code won't match the current docs.
Carry the tenant through the request
The tenant needs to reach the code that builds queries without being passed through every function by hand. NestJS gives you two options.
Request-scoped providers create a new instance per request, so a provider can read the tenant from the request directly. The injection scopes docs note that scope "bubbles up": "A controller that depends on a request-scoped provider is itself request-scoped." The docs say a well-designed app "should not see latency increase by more than ~5%," but the scope spreads through your dependency graph.
AsyncLocalStorage keeps per-request state without changing scopes. The NestJS AsyncLocalStorage recipe wraps each request in als.run from a middleware, and describes it as an alternative to request-scoped providers that avoids some of their limitations. The docs also warn that it "inherently obscures the code flow" by creating implicit context. The nestjs-cls library packages this pattern, though the NestJS docs note it's a third-party package.
Whichever you use, two rules matter:
- Fail closed. If the tenant context is missing, the data layer should throw, not run an unscoped query. OWASP's multi-tenant cheat sheet says to "Fail closed if the tenant context is missing or invalid."
- Set the context explicitly outside HTTP. Queue consumers, scheduled jobs, and websocket handlers don't go through the HTTP middleware. They need to establish the tenant themselves from the job or connection data, after validating it.
What your ORM will and won't do for you
It's tempting to add the tenant filter once, globally, and stop thinking about it. ORMs help, but each has gaps.
TypeORM documents where as "simple conditions by which entity should be queried," and its find options don't include global scopes; the only default filter is for soft-deleted rows. A common approach is a tenant-aware repository wrapper that adds the tenant to every query, plus code review rules for query builder and raw SQL usage, which the wrapper won't see.
Prisma query extensions let you "modify an incoming query," for example by adding the tenant to args.where. The docs list limits that matter here:
- You "cannot mutate include or select." Related records loaded through
includearen't filtered by your extension'swherechange. - Raw queries bypass model logic. "In the event a raw query is invoked, the model argument passed to the callback will be undefined."
- Nested operations may not be covered. The Prisma v6 docs say "The query extension type does not support nested read and write operations." Check the current docs for your version.
OWASP's multi-tenant cheat sheet describes ORM-level filters as "defense in depth, not complete enforcement." Use them to catch mistakes, not as the only line of defense.
Row-level security as a backstop
PostgreSQL row-level security (RLS) moves the tenant filter into the database, so even a query that forgets the filter only sees the current tenant's rows. Microsoft's multitenant data guidance says RLS "can provide security isolation for specific tenants' data in a shared multitenant database," and also notes that "Many multitenant solutions don't use row-level security because of those complexities." It's a trade-off worth making deliberately, not an automatic win.
How it works. Enable it with ALTER TABLE invoices ENABLE ROW LEVEL SECURITY, then add a policy whose USING expression compares the row's tenant_id to the current tenant, for example one read with current_setting('app.tenant_id'). CREATE POLICY also takes a WITH CHECK expression for inserts and updates; if it returns false or null, the write fails, which stops a request from writing a row into another tenant. If RLS is enabled with no policy, the PostgreSQL docs say "a default-deny policy is used."
The traps are mostly about roles and connections:
- Some roles bypass RLS entirely. "Superusers and roles with the BYPASSRLS attribute always bypass the row security system." Table owners also bypass it unless you set
ALTER TABLE ... FORCE ROW LEVEL SECURITY. Run the application as a separate role that doesn't own the tables, and keep a different role for migrations. - Set the tenant per transaction, not per connection. Use
SET LOCAL app.tenant_idorset_config('app.tenant_id', $1, true)inside the transaction. The PostgreSQL docs saySET LOCALlasts "only till the end of the current transaction" and, outside a transaction block, "emits a warning and otherwise has no effect." A plainSETstays on the connection, and with a pooler such as PgBouncer in transaction mode, which doesn't supportSET, the next request on that connection could inherit the previous tenant. OWASP's cheat sheet warns that "session-scoped tenant state can therefore be inherited by the next request." - Fail closed when the setting is missing.
current_settingthrows an error for a missing setting unless you passmissing_ok, in which case it returns NULL. Write the policy so that a missing tenant matches no rows, and test it. - Some checks bypass policies. PostgreSQL says referential integrity checks "always bypass row security," and warns about "covert channel" leaks through them. Keep foreign keys within a tenant where you can.
If you already use set_config to pass the current user into audit triggers, the same transaction-scoping rules apply. Prisma publishes an RLS example extension built on this pattern, but it says it's "not intended to be used in production environments," so treat it as a reference.
The other doors: Next.js, caches, queues, and files
The API isn't the only path to tenant data.
Next.js Server Actions are public endpoints. The Next.js data security guide says to "treat Server Actions as reachable via direct POST requests and verify authentication and authorization inside each one," and adds that "A page-level authentication check does not extend to the Server Actions defined within it." Checks in middleware (now proxy.ts in current Next.js docs) aren't enough on their own either. In March 2025, CVE-2025-29927 let attackers bypass authorization checks that ran in Next.js middleware; it was fixed in versions 12.3.5, 13.5.9, 14.2.25, and 15.2.3. Hiding a button in React is a usability choice, not authorization.
Caches need the tenant in the key. OWASP's cheat sheet says to "Include the tenant identifier in every cache key whose value or authorization varies by tenant" and to "Authorize the request before reading a protected cached value." A cache key of invoice:124 serves whoever asks first.
Queues aren't boundaries. OWASP notes that "A shared queue or topic is not itself a tenant-isolation boundary." Put the tenant in the message, and have the worker re-establish and validate it before touching data.
File paths aren't permissions. Storing files under a tenant prefix is good organization, but OWASP says "Object naming or prefixes alone are not authorization boundaries." Issue download links only after the same tenant check you'd use for the database record.
404 or 403, and watching for probing
When a caller asks for another tenant's record, should the API say "not found" or "forbidden"? RFC 9110 allows a server that wants to hide a forbidden resource's existence to "instead respond with a status code of 404 (Not Found)." A scoped query gives you that behavior naturally.
OWASP's multi-tenant cheat sheet example draws a useful line: return 404 for a record that belongs to another tenant, so you don't confirm it exists, and return 403 when a user selects a tenant they aren't a member of. Whichever you choose, be consistent across endpoints.
Log these denials. CISA's advisory notes that spikes in 404 and 403 responses can indicate someone enumerating IDs, which is exactly what this bug invites.
Prove it with two-tenant tests
Authorization code that isn't tested drifts. OWASP API1 is direct: "Write tests to evaluate the vulnerability of the authorization mechanism. Do not deploy changes that make the tests fail."
A practical setup:
- Seed two tenants, A and B, each with a user and a few records of every type.
- For every endpoint that takes an ID, log in as a user from A and call it with B's ID: read, update, delete, and any nested routes. Expect 404 (or your chosen response), and confirm B's record is unchanged.
- For every list endpoint, confirm A's results contain none of B's records, including through filters, search, and exports.
- For create and update, send
tenantIdorownerIdin the body and confirm the server ignores it. - For RLS, run a test as the application's database role, through the same pooler and pooling mode the app uses. OWASP recommends testing "through the same role, connection path, and pooling mode used by the application," and checking that a second request "cannot observe the first request's tenant context."
Add a test with the same shape whenever you add an endpoint. It's the cheapest way to catch the one function that forgot the filter.
Regulation and disclosure
This isn't legal advice, but cross-tenant exposure is usually a personal data breach. In the EU, GDPR Article 32 requires "appropriate technical and organisational measures" and a process for regularly testing them, and Article 33 generally requires notifying the supervisory authority within 72 hours of becoming aware of a breach unless it's unlikely to result in a risk to people. In the US, breach notification is governed by state laws and sector rules. Ask your legal or privacy team what applies before you need it.
A tenant isolation checklist
- The tenant comes from the verified identity and membership, never from a client value alone.
- Clients can't set
tenantIdorownerId; the server sets them. - Reads, updates, and deletes are scoped by ID and tenant in one query.
- Lists are filtered by tenant in the query, including search and exports.
- The data layer fails closed when tenant context is missing.
- Jobs, consumers, and websockets set and validate tenant context explicitly.
- ORM-level filters are treated as defense in depth, with raw queries and nested operations reviewed separately.
- RLS, if used, runs as a non-owner role without BYPASSRLS, with
FORCE ROW LEVEL SECURITYwhere owners connect, andWITH CHECKon writes. - Tenant settings use
SET LOCALorset_config(..., true)inside a transaction, never plainSETbehind a pooler. - Server Actions and route handlers authorize inside each one, not only in middleware.
- Cache keys, queue messages, and file access include and check the tenant.
- Cross-tenant requests return a consistent 404, and denials are logged and monitored.
- Two-tenant tests cover every endpoint and run on every change.
Changing a number in the URL should only ever lead to "not found." Getting there takes a scoped query in every function, a database that refuses to cooperate when one is missed, and tests that try the attack before someone else does.



