← Blog
December 5, 202611 min readAppSecMethodologySecurity Engineering

How to hunt cross-tenant data leaks in a multi-tenant SaaS app

Authenticated and authorized users can still reach another customer’s data. A two-tenant method with canary data for finding cross-tenant leaks in SSO and invites, API keys, background jobs, caches, search, webhooks and PostgreSQL row-level security.

By The Xalgorix Team

AWS's SaaS architecture guidance has a sentence worth pinning above every multi-tenant test plan: “a user could be authenticated and authorized, and still access the resources of another tenant.” Login works, roles work, the obvious GET /api/invoices/:id check works, and data still crosses from one customer to another through a path nobody thought of as an API: an export job, a search index, an SSO login, a database view.

This is a working method for finding those paths. It assumes you control two tenants, either as the team that builds the product or as a researcher with two accounts you own. It goes past the single-endpoint, two-user swap (covered in our IDOR and BOLA walkthrough) and looks at the places where tenant context gets created, carried and dropped.

Set up two tenants and plant canaries

Create Tenant A (the attacker's seat) and Tenant B (the victim). Give each an admin and a low-privilege member, so you can tell a cross-tenant leak apart from an in-tenant privilege bug. Then seed Tenant B with data you can search for later: an invoice numbered CANARY-B-7F3A, a contact called canary-b-7f3a@example.test, a file named canary-b-7f3a.pdf, a project description containing the same marker.

The marker is the point. Cross-tenant leaks often show up somewhere other than the request you sent: in a CSV export, an autocomplete dropdown, a notification email, a webhook body. A unique string that only exists in Tenant B lets you grep every response, download and inbox in Tenant A for one thing. Write down every object ID Tenant B creates; you will replay them all from Tenant A.

Seed Tenant B
unique canary marker
Harvest B's IDs
objects, invites, keys
Replay as Tenant A
every credential type
Grep A's outputs
responses, files, mail
Classify the hit
exists · reads · writes
The loop repeats for every surface: replay B's identifiers with A's credentials, then search everything A can see for B's canary.

Find out where the app gets the tenant from

Every request has to resolve “which tenant is this?” before it can filter anything. Map where that answer comes from, because it decides what you can tamper with:

  • From the credential. A session or token that carries the tenant, set server-side at login. This is the strong design; your tests then target places where the credential is ignored or replaced.
  • From the request. An X-Tenant-ID header, a ?org= parameter, a path segment like /orgs/acme/, a subdomain, or a field in the JSON body. Each one is attacker-controlled. Keep Tenant A's session and change only the tenant selector to Tenant B's value. If the app checks that the user belongs to the selected tenant on some routes but not others, you have found the gap.
  • From the object. The handler loads a record by ID and uses its tenant for everything after. That is safe only if the load itself was filtered by the caller's tenant.

The most useful single test here is the mismatch: a valid credential for A, a tenant selector for B, an object ID from B. Then permute which of the three comes from which tenant. A handler that authorizes against one source and queries with another will give itself away on one of the combinations.

Seven surfaces the request path misses

Tenant-scoped API routes get most of the testing because they are the easiest to see. These are the places where isolation tends to depend on someone remembering to add a filter.

1. Identity joins: SSO, invites and domain auto-join

How does a user end up inside a tenant? Every answer is an isolation boundary. The nOAuth issue that Descope disclosed with Microsoft on 2023-06-20 is the classic case: Azure AD's email claim was mutable and unverified, so an attacker could set a victim's address on an account in their own Azure AD tenant, use “Log in with Microsoft”, and land in the victim's account on apps that linked users by email. Descope's advice was to key users on the immutable sub claim; Microsoft added the xms_edov optional claim to signal a domain-verified email.

Test the same idea in your own product. Can an invite token issued by Tenant B be redeemed by a user already in Tenant A, and does it still work after B revokes it? If the app auto-joins anyone with a @b-corp.test address, can A's IdP assert that address without owning the domain? Does SSO configuration for B accept assertions from A's identity provider? Our Entra ID actor-token teardown shows how far a single missing tenant check in token validation can reach.

2. API keys and service tokens

API keys are often resolved to a tenant once, at lookup, and then forgotten. Mint a key in Tenant A and use it against Tenant B's object IDs on every endpoint the key can reach, including the “integration” and bulk endpoints that the web UI never calls. Check whether a key's tenant binding survives key rotation, and whether a key created by a member who is later moved to another tenant still works in the old one.

3. Background jobs, exports and reports

A web request carries its tenant in the session. A queued job carries whatever the developer put in the payload, often just { exportId: 9182 }. The worker then loads export 9182, and the rows it pulls depend on how that worker filters. Workers also tend to run with a stronger database role than the web tier. In PostgreSQL, superusers and roles with BYPASSRLS always bypass row security, and table owners normally do too unless the table uses FORCE ROW LEVEL SECURITY. A job that connects as the migration role ignores every policy you wrote.

Test by starting exports, scheduled reports, PDF renders and bulk imports from Tenant A with Tenant B's IDs in every parameter the job accepts, then grep the output for the canary. Race a job against a tenant switch too: start an export, change the active organisation in the UI, and see which tenant the finished file belongs to.

4. Caches

A cache key built from the route and the object ID, but not the tenant, will serve one customer's response to another as soon as the IDs collide or the route has no ID at all (/api/dashboard/summary). Load a cached page as Tenant B, then immediately as Tenant A, and compare. At the edge, check that authenticated responses carry Cache-Control: private or no-store and are not served from a shared CDN cache.

5. Search, autocomplete and analytics

Search clusters are commonly shared, with the tenant filter added at query time. Typeahead endpoints, “recent items”, global search and reporting dashboards are written later than the core CRUD and get less review. Type the first few characters of the canary into every search box in Tenant A. Facet counts and “did you mean” suggestions can leak existence even when results are filtered.

6. Webhooks and integrations

Register a webhook endpoint in Tenant A, then trigger events in Tenant B. If the dispatcher selects subscribers by event type and forgets the tenant, A receives B's events. For OAuth-based integrations (Slack, GitHub, Google Drive), check that the callback binds the connected account to the tenant that started the flow, and that Tenant A cannot complete a flow that Tenant B started.

7. The database layer itself

Row-level security is a strong backstop, and it has sharp edges that only show up in the database. Three are worth checking directly:

  • Views run as their owner. Per the CREATE VIEW reference, a view applies the view owner's permissions and RLS policies unless it is created with security_invoker. Supabase's linter flags this as security definer views.
  • Tenant context on pooled connections. Policies often read current_setting('app.tenant_id'). A session-level SET stays on the server connection. Under PgBouncer transaction pooling, which lists SET/RESET as never supported, that connection goes back to the pool and can serve another client with the previous tenant still set. Use set_config('app.tenant_id', $1, true) or SET LOCAL inside each transaction.
  • Constraints cross tenants. The PostgreSQL docs warn that unique, primary key and foreign key checks always bypass row security, and can leak information as a covert channel. A globally unique invoice number or slug tells Tenant A whether Tenant B already uses a value. Scope uniqueness to (tenant_id, number).

We reproduced the first two on PostgreSQL 16 with a two-tenant invoices table. Under an app role with the tenant set to A, the table returned only A's row, a plain view created by the table's (non-superuser) owner returned both tenants' rows, and the same view created WITH (security_invoker = on) returned only A's. An insert of B's canary invoice number from Tenant A failed with a duplicate-key error, which tells A that the value exists. If you own the database, these catalog queries find the risky objects directly:

-- Tables with RLS off, or on but not forced for the owner
SELECT n.nspname, c.relname, c.relrowsecurity, c.relforcerowsecurity
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
  AND (NOT c.relrowsecurity OR NOT c.relforcerowsecurity);

-- Roles that skip every policy
SELECT rolname FROM pg_roles WHERE rolsuper OR rolbypassrls;

-- Views that run with the owner's rights (no security_invoker)
SELECT n.nspname, c.relname
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'v'
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
  AND NOT EXISTS (
    SELECT 1 FROM unnest(coalesce(c.reloptions, '{}')) AS o
    WHERE lower(o) IN ('security_invoker=on', 'security_invoker=true',
                       'security_invoker=1', 'security_invoker=yes'));

Not every result is a bug. Lookup tables with no tenant data do not need RLS, and an unforced table is fine if the app never connects as its owner. The output is a review list, and each entry needs a reason.

Grade what you found

A cross-tenant hit is not one severity. Grade it by what Tenant A actually got:

Tenant A used B's identifier or context
Existence
A learns a value or ID exists in B (409, different error, count, timing)
Read
B's canary shows up in a response, file, email or webhook A receives
Write or join
A changes B's data, or becomes a member of B
Report the strongest outcome you reached with your own two tenants. Do not escalate against real customer data to find out.

Existence leaks are usually low severity alone, but they matter when the leaked value is sensitive (an email address on a security product) or when they let an attacker enumerate IDs for a read bug elsewhere. Reads and writes across tenants are the findings customers ask about in security questionnaires, and they are often treated as high or critical because one bug affects every customer at once.

Keep the test inside tenants you own. In a bug bounty, that means two accounts you registered yourself; once B's canary shows up in A's view, stop and report rather than probing for real customers' data to show scale.

Keep the sweep running after the fix

The two-tenant setup is cheap to keep. Run the canary sweep in CI against a seeded environment so a new export format or search endpoint cannot quietly skip the tenant filter. A minimal version replays a list of Tenant B resources with Tenant A's credentials and fails if any response contains the canary:

// cross-tenant.test.ts (vitest); BASE, TOKEN_A and B_PATHS come from a seeded env
import { expect, test } from "vitest";

const CANARY = "CANARY-B-7F3A";
const B_PATHS = JSON.parse(process.env.B_PATHS ?? "[]") as string[];

test.each(B_PATHS)("tenant A cannot read %s", async (path) => {
  const res = await fetch(new URL(path, process.env.BASE), {
    headers: { authorization: "Bearer " + process.env.TOKEN_A },
  });
  const body = await res.text();
  expect(body).not.toContain(CANARY);
  expect([401, 403, 404]).toContain(res.status);
});

Extend the list whenever a feature adds a new place where data leaves the request path: an export, a report, a webhook event type. The same approach, applied to individual vulnerability fixes, is in our guide to turning a fixed vulnerability into a regression test.

What automated testing can and cannot cover here

Automated tools, Xalgorix included, are good at the mechanical half of this method once you hand them two tenants: replaying every harvested ID with the other tenant's credential, permuting tenant selectors, and grepping responses for a canary, at a volume no manual tester will match. They are weaker at the half that needs knowledge of the system. A crawler sees the CSV download button. It does not know that the file is built by a worker running as the table owner, or that the webhook dispatcher selects subscribers by event type. The surface inventory in this article is the part a human, or a design review, has to supply.

For a framework view of the same problem at the infrastructure level, Wiz's PEACH model rates tenant isolation across privilege, encryption, authentication, connectivity and hygiene. For application teams, the shorter version is this: list every way data leaves the request path, and test each one from the wrong tenant.

Sources

Ready to see it prove a bug?

Start scanning on Cloud →