← Blog

SaaS · Authorization · Tenant Isolation

Why Isn’t Authentication Enough to Prevent Cross-Tenant Data Leaks?

A user can be correctly signed in and still receive another customer's data. This article explains why tenant isolation is separate from authentication, and how to carry and enforce tenant context through queries, caches, jobs, tokens and admin tools.

Aashaya Aryal

February 9, 2026 · 11 min read

Updated November 17, 2026

Nighttime facade of a high-rise apartment building with hundreds of illuminated and dark windows arranged in a dense grid.

A user signs in. Their JWT is valid, their session is active, their role says they're an administrator, and they call an endpoint they're allowed to use. The application returns data belonging to another customer.

Nothing in that story requires authentication to be broken, which is what makes multi-tenant authorization bugs so dangerous: identity can be completely right while the scope of the request is wrong. This became much more concrete for me while building a multi-tenant marketplace backend. Once one application serves several organisations through shared APIs, services, caches, databases and queues, the security question changes from "who is this user?" to "which tenant is this request allowed to affect, and where is that enforced?"

Those sound similar, but they're different guarantees. Authentication establishes identity. Authorization decides what that identity may do. Tenant isolation limits whose resources the action may touch. AWS's SaaS Architecture Fundamentals puts it plainly: a tenant user being authenticated doesn't mean your system has achieved isolation; isolation is applied separately. If tenant context goes missing, goes stale, comes from the client or gets forgotten in one data path, every request can authenticate correctly and the system can still leak between organisations. That makes isolation less a feature than an invariant, and an important invariant shouldn't depend on every developer remembering one more tenant_id filter.

Three questions, not one

Take this request:

HTTP
GET /organizations/org_b/orders/order_921
Authorization: Bearer <token>

Several decisions hide inside it:

Diagram

Authenticated

No

Authorized action

No

Valid tenant membership

No

Yes

No

Incoming Request

Who is the caller?

May this caller read orders?

May this caller access org_b?

Does order_921 belong to org_b?

Return Resource

Reject

Authentication answers the first. A role or permission model answers the second. Tenant isolation depends on the third and fourth staying true along the whole request path.

OWASP calls one common version of this failure Broken Object Level Authorization (BOLA), and it's number one on their API Security Top 10. An authenticated user changes an object ID and reaches someone else's resource, because the application checked access to the endpoint but not to that specific object. UUIDs don't fix this, and neither do unguessable organisation IDs. Hard-to-guess identifiers make accidental discovery less likely, but a secret ID isn't an authorization check.

How the check drifts

Here's the dangerous version:

TS
@Get(":organizationId/orders/:orderId")
async getOrder(
  @Param("organizationId") organizationId: string,
  @Param("orderId") orderId: string,
) {
  return this.ordersService.findById(orderId);
}

The route includes an organisation ID, but it doesn't actually constrain anything; the service looks the order up by ID alone. If someone in organisation A learns the ID of an order in organisation B, the route does nothing to stop them. A first fix compares after fetching:

TS
const order = await this.ordersService.findById(orderId);

if (order.organizationId !== organizationId) {
  throw new ForbiddenException();
}

return order;

That's better, but now the guarantee depends on every caller remembering to do the same comparison. As an API grows, this is where what I call authorization drift begins: operations that should behave the same slowly pick up different security behaviour. One controller remembers the check, another forgets it, a background worker calls the repository directly, a batch job skips the controller, a new developer reasonably assumes the service is already tenant-aware, or a cache returns the object before the check runs. The failure is rarely "nobody built authentication". It's usually that tenant context could disappear in several places and eventually did in one of them. That's an architecture problem, not a missing if.

Resolve tenant context once

AWS's SaaS Lens describes binding a user to a tenant as a SaaS identity, which makes tenant context a first-class part of the authentication and authorization model so it can flow through every layer. The practical rule I follow: resolve tenant context once, validate it against trusted identity and membership data, and pass the trusted result along.

In NestJS, a guard can do that:

TS
export interface TenantContext {
  tenantId: string;
  userId: string;
  roles: string[];
}

@Injectable()
export class TenantGuard implements CanActivate {
  constructor(private readonly memberships: MembershipService) {}

  async canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();

    const userId = request.user.id;
    const requestedTenantId = request.params.organizationId;

    const membership = await this.memberships.findActiveMembership(
      userId,
      requestedTenantId,
    );

    if (!membership) {
      throw new ForbiddenException();
    }

    request.tenant = {
      tenantId: requestedTenantId,
      userId,
      roles: membership.roles,
    } satisfies TenantContext;

    return true;
  }
}

The route parameter is input, not truth. The client can ask to work in org_b, but that only becomes trusted context after the server confirms the caller belongs to org_b. The same goes for a tenant header like X-Tenant-ID: org_b; reading it in middleware doesn't make it trustworthy.

Note

The client can propose a tenant. Only the server should be able to authorize it.

Once that's explicit, downstream code never has to wonder whether a tenantId it's been handed is trusted or just came from the request.

Scope the query, not the controller

With trusted context available, the data-access layer should make unscoped access hard to write by accident. Instead of this:

TS
findOrder(orderId: string) {
  return this.orders.findOne({
    _id: orderId,
  });
}

require the scope:

TS
findOrder(
  tenant: TenantContext,
  orderId: string,
) {
  return this.orders.findOne({
    _id: orderId,
    organizationId: tenant.tenantId,
  });
}

The code change is small; the architectural change isn't. The first asks "which order has this ID?" The second asks "which order with this ID exists inside this tenant?" Isolation has moved from a convention around the repository into the repository's contract.

Writes work the same way. Put the tenant in the filter of the update itself, so the ownership check and the change happen in one database operation:

TS
const result = await orders.updateOne(
  {
    _id: orderId,
    organizationId: tenant.tenantId,
  },
  {
    $set: {
      status: "cancelled",
    },
  },
);

if (result.matchedCount !== 1) {
  throw new NotFoundException();
}

There's no gap between finding, checking and updating where a broader update could hit something else. And a foreign resource looks exactly like a missing one, so the response doesn't reveal that the ID belongs to someone.

A tenant ID on every record is necessary but not enough on its own. It tells you who owns a row; it doesn't enforce that ownership. SELECT * FROM orders WHERE id = $1 is still unsafe, and so is orders.findOne({ _id: orderId }). Multi-tenancy also changes what "correct" means for indexes and uniqueness. A tenant-leading index makes the scoped query natural:

TS
await orders.createIndex({
  organizationId: 1,
  _id: 1,
});

And if a slug only needs to be unique within an organisation, a unique index on slug alone is too broad; it should be on { organizationId: 1, slug: 1 }.

Beyond reads: caches, storage and jobs

Isolation is often summed up as "user A shouldn't see user B's row". That's necessary but much too narrow. The boundary also has to hold for updates, deletes, search, aggregations, cache entries, file storage, background jobs, webhooks, rate limits, analytics, logs, exports and notifications. Perfectly scoped MongoDB queries can still leak through Redis.

A cache key like order:${orderId} has no tenant in it. A safer one carries it explicitly:

TS
const cacheKey = `tenant:${tenant.tenantId}:order:${orderId}`;

The same applies to object storage (tenants/org_a/orders/order_921.pdf rather than orders/order_921.pdf) and sometimes to rate limits, where tenant:org_a:user:123 may need a different policy from a global user:123 when one person belongs to several organisations. Anywhere tenant-owned state is stored, derived, cached, queued, indexed or exported is another place the boundary can vanish.

Queues are a common one. HTTP middleware makes trusted context easy to reach during a request, and then the code enqueues work:

TS
await jobs.add("generate-report", {
  reportId,
});

The worker receives {"reportId": "report_123"} and nothing else. It has no route guard, no middleware context, and if it calls reports.findById(reportId), isolation disappeared the moment the work crossed the queue. Tenant identity has to travel with the job:

TS
await jobs.add("generate-report", {
  tenantId: tenant.tenantId,
  reportId,
  requestedBy: tenant.userId,
});

And the worker should still scope its own access, rather than treating the payload as unlimited authority:

TS
const report = await reports.findOne({
  _id: job.data.reportId,
  organizationId: job.data.tenantId,
});

The same failure shows up in Kafka events, scheduled jobs, webhook handlers, delayed tasks and workflow engines. A request can start out tenant-safe and become unsafe as soon as it crosses a process boundary, which is why tenant identity belongs in the execution context of the work, not just the HTTP request object.

Tokens can carry stale authority

Putting too much tenant authority in a long-lived token causes a quieter kind of drift. Suppose a JWT contains:

JSON
{
  "sub": "user_123",
  "tenant": "org_a",
  "role": "admin"
}

At 10:00 that's correct. At 10:05 the user is removed from the organisation. At 10:06 the token still says admin of org_a. Verifying the signature proves the token was issued by you and hasn't expired. It doesn't prove every claim in it is still true.

That's a trade-off between freshness and cost. Short-lived tokens shrink the stale window. Checking membership on the server gives fresher answers but adds a database or cache lookup. Revocation lists are another system to run. Different actions can reasonably get different guarantees: a low-risk dashboard might tolerate slightly old authorization data, while deleting an organisation or moving money justifies checking current membership. There's no universal answer; what matters is knowing which guarantee you're making, rather than treating a valid signature as permanently valid authority.

Making the safe path the easy one

If a security property matters enough, let the architecture or tooling enforce it rather than relying on everyone's memory. GitHub's post on how they use CodeQL to secure GitHub describes custom queries that flag REST endpoints and GraphQL mutations missing their required authorization methods. I like that because it treats missing authorization as something tooling should catch, not something code review hopefully notices.

For a smaller app, that might just mean only exposing tenant-aware repository methods. Larger systems add framework policies, static analysis, policy engines, IAM conditions or stronger infrastructure isolation. The goal is the same: the safe path should be easier to write than the unsafe one.

The database can be a second boundary. PostgreSQL's row-level security can enforce a tenant policy on every query:

SQL
CREATE POLICY tenant_isolation
ON orders
USING (
  tenant_id = current_setting('app.tenant_id')
);

Then even an accidental SELECT * FROM orders stays inside the tenant. That doesn't replace correct application authorization, but it lowers the chance that one forgotten filter becomes a cross-tenant incident. It has costs: more operational complexity, connection pools that must set and reset tenant context correctly, harder debugging, and not every datastore has an equivalent (with MongoDB, most of the enforcement usually lives in the repository layer). The question worth asking is: if someone writes an overly broad query tomorrow, is there another layer that stops it crossing tenants?

Infrastructure is the other dial. The strongest isolation gives every tenant separate databases, storage, compute and credentials. AWS calls that a silo model, as opposed to a pooled model where tenants share infrastructure and isolation is enforced logically. Google's GKE architectures for SaaS describes the same trade-off between cost and isolation at the namespace, node and cluster level.

Diagram

More efficiency

More isolation

Shared Everything

Shared App + Tenant-Scoped Data

Shared Compute + Separate Databases

Separate Tenant Stacks

Not every product needs maximum separation. A small SaaS app can reasonably run shared compute and a pooled database; a regulated or very sensitive product may justify separate databases or stacks. What matters is that the isolation properties are explicit. "Multi-tenant" says who shares the product, not how strongly they're separated.

Centralised authorization is infrastructure

Centralising authorization is usually better than copying checks across the codebase, but it creates a dependency. GitHub's November 2023 availability report describes their authorization service running out of memory after a change with a memory leak, causing failed authorization requests and 404s or errors on most pages and API calls for 38 minutes. Rolling back took longer than it should have because parts of the deployment tooling depended on the authorization service that was down.

That shows a real tension between security and availability. Failing open (allow the request when authorization is unavailable) keeps the site up but may break the boundary. Failing closed (reject it) keeps isolation intact but turns an authorization outage into an application outage. For tenant isolation, failing closed is generally the right default: being unable to evaluate access shouldn't become permission to cross customer boundaries. It also means the authorization path deserves proper production engineering: caching, latency budgets, monitoring, careful rollouts, capacity testing, and a rollback path that doesn't depend on the thing you're rolling back.

Privileged cross-tenant access

Most operations are simple: a user in tenant A works inside tenant A. Then the platform needs support tooling. Staff need to investigate several tenants, migrations run over every organisation, analytics aggregate across customers, and support engineers sometimes need to view a tenant's environment. Those are legitimate cross-tenant operations, and they're exactly where a rule like "admin bypasses tenant isolation" becomes dangerous, because it quietly gives an ordinary-looking role an enormous capability.

A safer model makes platform-wide access structurally different:

TS
type AccessScope =
  | {
      type: "tenant";
      tenantId: string;
    }
  | {
      type: "platform";
      reason: string;
    };

Now normal tenant work and deliberate platform work are separate modes, and platform access can require stronger auditing, narrower permissions, explicit elevation, time limits or approval.

Warning

"Administrator" shouldn't automatically mean "may cross every tenant boundary". Administering a tenant and administering the platform are different privileges.

The goal isn't to pretend cross-tenant access never happens, just to make sure it never happens by accident.

Logging and testing the boundary

If an isolation incident happens, you need to reconstruct the authorization decision, not just the request. Structured events help:

JSON
{
  "requestId": "req_91f",
  "actorId": "user_123",
  "tenantId": "org_a",
  "resourceType": "order",
  "resourceId": "order_921",
  "action": "read",
  "decision": "allow"
}
JSON
{
  "requestId": "req_91g",
  "actorId": "user_123",
  "requestedTenantId": "org_b",
  "action": "read_order",
  "decision": "deny",
  "reason": "no_active_membership"
}

The point isn't to dump sensitive payloads into logs. It's to keep enough context to answer later: which tenant the request resolved to, where that came from, which policy allowed it, whether the resource really belonged to that tenant, and whether it was normal tenant work or platform access. Otherwise the logs may only show that a perfectly authenticated request returned 200.

For tests, "user A can read user A's order" is the least interesting case. The one that protects the boundary is "user A can't read user B's order, even knowing its exact ID", repeated across every path:

ScenarioExpected result
Valid user, correct tenant, correct permissionAllow
Valid user, wrong tenantDeny
Valid user, correct tenant, wrong roleDeny
Valid user, another tenant's resource IDDeny
User removed from tenantDeny once authorization state refreshes
Cached object belongs to another tenantNever returned
Background job with mismatched tenant and resourceFail
Webhook referencing another tenant's resourceReject or reconcile safely
Platform admin enters tenant modeAudited explicitly
Missing tenant contextFail closed

The best tests actively try to break the boundary: substituting real IDs from another tenant, changing tenant headers while keeping valid authentication, feeding a worker a mismatched tenant and resource, and checking that cached data can't bypass repository scoping. The question is what happens when a completely valid user asks for a completely valid resource that belongs to someone else.

Putting it together

For a pooled SaaS backend, the shape I aim for looks roughly like this:

Diagram

Client

Authentication

Tenant Resolution + Membership Validation

Permission Check

Application Service

Tenant-Scoped Repository

Shared Database

Tenant-Scoped Cache

Background Queue

Worker With Tenant Context

The boxes will differ between applications. What matters is the direction of trust: a client-supplied tenant value is validated against membership, becomes trusted context, goes through a permission check, and only then reaches tenant-scoped data access. Downstream components shouldn't keep accepting organisation IDs from outside and deciding for themselves whether they're legitimate. They should consume context that has already crossed a defined boundary, and carry it into repositories, cache keys, jobs and storage paths.

If I had to put it in one rule: no operation may read or change tenant-owned state unless its trusted context authorizes that same tenant. Every design choice can be checked against it. Does the cache keep it? The queue? A webhook? Object storage? Uniqueness constraints? A bulk operation? Does an admin only cross it on purpose? Does a new endpoint inherit it by default? And does anyone have to remember to enforce it by hand?

Key takeaways

  • Authentication says who the user is; tenant isolation decides whose data they can touch. They're separate checks.
  • Treat tenant IDs from routes, headers and tokens as requests. Validate them against server-side membership once, then pass trusted context along.
  • Put the tenant in the repository contract and in every write filter, not in controller checks that can drift.
  • Carry tenant identity into cache keys, storage paths, uniqueness constraints and background jobs.
  • Decide how fresh authorization claims must be, add defence in depth where the datastore supports it, and fail closed.
  • Make platform-wide access a separate, audited mode, and test with valid users requesting other tenants' real resources.

References