Short answer
In a multi-tenant app every row belongs to a tenant, such as a workspace or a company, and the database must only return rows from tenants the caller is a member of. In Supabase, give every tenant table a workspace_id, keep memberships in their own table that users cannot write to, check membership in RLS policies through a small security definer helper, pin child rows to their parent’s tenant with composite foreign keys and test everything as two users in two different tenants.
Ask an AI about this page:ChatGPTClaude
On this page
Key takeaways
- In a multi-tenant app, every row belongs to a tenant (a workspace, team or company), and the database must check that the caller is a member of that tenant on every query.
- A policy that only checks “is signed in”, such as
auth.uid() is not null, is the most common tenant leak: every customer can read every other customer’s data. - Keep memberships in their own table that users cannot write to, and check them in RLS through a
security definerhelper in a private schema. - Use composite foreign keys
(workspace_id, parent_id)so a child row can never point at a parent in another tenant. - Prove it with a two-tenant test: a user in workspace B must get zero rows from workspace A, for every table and every action.
What does multi-tenant data isolation mean?
Most SaaS apps serve many customers from one database. Each customer is a tenant: a workspace, a team, an organisation or a company account. Several users can belong to the same tenant, and one user can belong to several tenants. Multi-tenancy means all of them share the same tables, and tenant isolation means that no query ever returns or changes a row that belongs to a tenant the caller isn’t part of.
In an app built with Lovable, Bolt or Cursor on top of Supabase, the browser talks to the database directly with a public key. There is no server of yours in between that could filter the results. So isolation has to live in the database, as row level security policies that check the tenant on every row. If you only have per-user data so far, that guide is the place to start. This one is about the step after it: data that belongs to a group.
The failure is easy to describe and painful to explain to a customer: user Bob at Bob GmbH opens a link, changes the ID in it and sees Alice Inc’s project plan. Or he doesn’t even change anything, because the list endpoint returns every company’s projects and only the frontend filters them.
IDOR and BOLA: what the bug is called
Security standards have two names for the same mistake.
- IDOR (insecure direct object reference) is the classic web term. MITRE lists it as an alternate name for CWE-639 (opens in a new tab), “Authorization Bypass Through User-Controlled Key”: the system doesn’t stop one user from reaching another user’s data by changing the key that identifies a record.
- BOLA (broken object level authorization) is the first item of the OWASP API Security Top 10 (2023). OWASP’s summary is short: “The violation happens at the object level, by manipulating the ID.”
Both sit under broken access control, the category listed first in the OWASP Top 10, whose description explicitly includes viewing or editing someone else’s account by providing its identifier. In a Supabase app the pattern looks like this:
const { data: project } = await supabase
.from("projects")
.select("id, name, workspace_id")
.eq("id", projectId) // projectId comes from the URL
.single();That code is fine if the database refuses rows from other workspaces. If the policy on projects only checks that someone is signed in, any user can paste any project ID into the URL and read it.
Why AI-built apps leak across tenants
We see three patterns over and over in workspace-style apps.
1. Policies that check sign-in instead of membership. When a tool is asked for “members can view projects”, it sometimes writes a policy whose name says members while its body only says signed in. Here is the core of one of our own test apps, a small Lovable-style project tracker we built with exactly this mistake:
create table public.projects (
id uuid primary key default gen_random_uuid(),
workspace_id uuid not null references public.workspaces (id) on delete cascade,
name text not null
);
alter table public.projects enable row level security;
create policy "Members can view workspace projects"
on public.projects for select
to authenticated
using (auth.uid() is not null);RLS is on, there is a policy and the name sounds right, so nothing looks wrong at a glance. But auth.uid() is not null is true for every signed-in user. In our test, a user from a second workspace read both companies’ projects. Since anyone can usually sign up for your app, “signed in” is barely a restriction at all.
2. The frontend filters by workspace, the database doesn’t. The app shows only the current workspace’s projects because the hook adds .eq("workspace_id", currentWorkspaceId). That filter runs because your code asks for it. Someone calling the Data API with your public key simply leaves it out.
3. Server code with admin rights trusts an ID from the request. An edge function that uses the secret key and loads projectId from the request body skips every policy. If it only checks that the caller is signed in, it has the same hole as point 1, just in TypeScript. More on that further down.
The data model: tenants and memberships
Clean isolation starts with a boring, explicit data model. Two tables carry it:
create table public.workspaces (
id uuid primary key default gen_random_uuid(),
name text not null
);
create table public.workspace_members (
workspace_id uuid not null references public.workspaces (id) on delete cascade,
user_id uuid not null references auth.users (id) on delete cascade,
role text not null default 'member' check (role in ('owner', 'member')),
primary key (workspace_id, user_id)
);
create index workspace_members_user_id_idx on public.workspace_members (user_id);Three rules follow from it:
- Every tenant table gets a
workspace_idcolumn,not null, even when the tenant could be derived through a parent row. Policies then check one column on the row itself, without joins, and child rows can be pinned to their parent’s tenant (see composite foreign keys below). - Membership lives in
workspace_members, nowhere else. Not inuser_metadata, which users can edit themselves, and not in local storage. - The primary key
(workspace_id, user_id)prevents duplicate memberships, and the extra index onuser_idkeeps the lookup “which workspaces is this user in?” fast.
Check membership with a helper function
Policies on tenant tables all ask the same question: “is the current user a member of this row’s workspace?” Put that question into one function:
create schema if not exists private;
create or replace function private.is_member(ws uuid)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1 from public.workspace_members m
where m.workspace_id = ws
and m.user_id = (select auth.uid())
);
$$;
revoke all on function private.is_member(uuid) from public, anon;
grant execute on function private.is_member(uuid) to authenticated;Each line has a job:
security definerruns the lookup with the rights of the function’s owner, so it can readworkspace_memberseven though that table has its own RLS. Supabase’s RLS docs recommend this for membership lookups, and it avoids policies that recursively trigger themselves.set search_path = ''forces fully qualified names likepublic.workspace_members, so nobody can slip in a look-alike table. The Security Advisor flags functions without a fixedsearch_path(lint 0011).- The
privateschema is not exposed through the Data API. Supabase’s docs are explicit that such functions should never live in a schema listed under “Exposed schemas”. Our guide toSECURITY DEFINERfunctions goes deeper. revoke … from public, anonmeans visitors can’t call the helper at all. In our test, a visitor calling it gotpermission denied, while policies for signed-in users kept working, without any extra grant on theprivateschema.
Write policies that check the tenant, not the sign-in
Now replace the sign-in-only policy with membership checks, and lock down what signed-in users may change:
drop policy "Members can view workspace projects" on public.projects;
revoke all on table public.projects from anon;
revoke update on table public.projects from authenticated;
grant update (name) on table public.projects to authenticated;
create policy "Members can view workspace projects"
on public.projects for select
to authenticated
using (private.is_member(workspace_id));
create policy "Members can add projects to their workspaces"
on public.projects for insert
to authenticated
with check (private.is_member(workspace_id));
create policy "Members can rename workspace projects"
on public.projects for update
to authenticated
using (private.is_member(workspace_id))
with check (private.is_member(workspace_id));
create index if not exists projects_workspace_id_idx on public.projects (workspace_id);What we verified for this block, as two users in two workspaces:
- Each user sees only the projects of their own workspace. The service role, which is what the secret key uses, still sees all of them.
- Asking for another workspace’s project by its exact ID returns nothing, so the IDOR from the page component above is gone.
- Creating a project in someone else’s workspace fails with a row level security error, because
with checktests the new row. - Renaming another workspace’s project “succeeds” with zero rows changed. That is how Postgres reports an update that no policy allows.
- Moving a project to another workspace by changing
workspace_idfails withpermission denied, because the column-level grant only allowsnameto be updated. - Visitors without an account get
permission deniedinstead of an empty list.
The column grant matters more than it looks. Without it, a member of two workspaces could move a project from one to the other, and with check would allow it, because they are a member of both. If rows should never change tenant, don’t give clients the right to update the tenant column at all.
The same pattern covers deletes. Add a for delete policy with using (private.is_member(workspace_id)) if members may delete, or one that also checks an owner role. For updates and deletes that must be limited to the row’s author, see missing ownership checks.
Protect the membership table itself
The best tenant policies are worthless if users can add themselves to any workspace. In our test, before the fix, a signed-in user could insert a row into workspace_members for a workspace that wasn’t theirs, and a visitor could read the full member list. Lock both tables down:
alter table public.workspaces enable row level security;
alter table public.workspace_members enable row level security;
revoke all on table public.workspaces, public.workspace_members from anon;
revoke insert, update, delete on table public.workspaces, public.workspace_members from authenticated;
create policy "Members can view their workspaces"
on public.workspaces for select
to authenticated
using (private.is_member(id));
create policy "Members can view their workspace's members"
on public.workspace_members for select
to authenticated
using (private.is_member(workspace_id));After this, users see only their own workspaces and the members of those workspaces. Writing to either table fails with permission denied. The policy on workspace_members calls a helper that reads workspace_members again; thanks to security definer that doesn’t recurse, which we checked.
So how do memberships get created? Through code you control:
- A sign-up trigger that creates a personal workspace and the owner membership (a
security definerfunction in theprivateschema, withexecuterevoked from everyone). - An invite flow in an edge function: the inviter must be an owner of the workspace, the invitee accepts with a single-use token, and only then does the function insert the membership with admin rights.
Removing a member is equally direct: delete the row and the next query from that user returns nothing from that workspace. We tested that too.
Composite foreign keys: rows can’t point into another tenant
Here is the gap that survives even good policies. A tasks table belongs to projects, and its insert policy checks membership of the task’s own workspace_id:
create table public.tasks (
id uuid primary key default gen_random_uuid(),
workspace_id uuid not null references public.workspaces (id) on delete cascade,
project_id uuid not null references public.projects (id) on delete cascade,
title text not null
);
alter table public.tasks enable row level security;
create policy "Members can add tasks"
on public.tasks for insert
to authenticated
with check (private.is_member(workspace_id));Bob is a member of workspace B. He inserts a task with workspace_id = B, which passes the policy, and project_id = a project of workspace A, which passes the foreign key, because that project exists. The row now says “I belong to B” and “I belong to A’s project” at the same time.
Why that matters: every piece of code that loads a project’s tasks by project_id with admin rights, such as an export, a weekly e-mail digest or an AI summary, now mixes Bob’s text into Alice’s project. In our test, the service role’s query “tasks of project A” returned Bob’s planted row. That is a path for spam, for misleading data and for prompt injection into your AI features.
The fix is to let the database enforce that a child row and its parent share the tenant:
alter table public.projects
add constraint projects_workspace_id_id_key unique (workspace_id, id);
create table public.tasks (
id uuid primary key default gen_random_uuid(),
workspace_id uuid not null,
project_id uuid not null,
title text not null,
foreign key (workspace_id, project_id)
references public.projects (workspace_id, id) on delete cascade
);
alter table public.tasks enable row level security;
create policy "Members can add tasks"
on public.tasks for insert
to authenticated
with check (private.is_member(workspace_id));Now Bob’s insert fails with a foreign key violation: the pair (workspace B, project of A) doesn’t exist in projects. If he claims workspace A instead, the policy rejects him. Alice’s normal inserts keep working; the foreign key check is not blocked by the RLS on projects.
Two details from the PostgreSQL docs make this work:
- A foreign key must reference columns that are a primary key or have a unique constraint.
idalone is already unique, so the extraunique (workspace_id, id)costs little, but it is required for the composite reference. - By default, a composite foreign key isn’t checked if any of its columns is null. Keep both columns
not null, as above.
Find foreign keys that ignore the tenant
This query lists every foreign key in public that points at a table with a workspace_id column but doesn’t include workspace_id itself. Adjust the column name if your tenant column is called org_id or team_id:
select con.conrelid::regclass as child_table,
con.confrelid::regclass as parent_table,
con.conname as constraint_name
from pg_constraint con
where con.contype = 'f'
and con.connamespace = 'public'::regnamespace
and exists (
select 1 from pg_attribute a
where a.attrelid = con.confrelid and a.attname = 'workspace_id' and not a.attisdropped
)
and not exists (
select 1 from pg_attribute a
where a.attrelid = con.conrelid and a.attname = 'workspace_id'
and a.attnum = any (con.conkey)
);On the single-column version it returned tasks → projects; on the composite version it returned nothing. References to workspaces itself are not listed, because workspaces has no workspace_id column. That is the one foreign key that may stay single-column.
Edge functions and server code
Policies protect the Data API. Server code that uses the secret key is a different door: Supabase’s docs describe the secret key (and the legacy service_role key) as bypassing row level security. So every edge function that touches tenant data must answer “may this caller see this workspace?” on its own.
The broken version from our test apps loads a project by an ID from the request body with an admin client after only checking that the caller is signed in. The fixed twin does this instead (shortened, a sketch rather than a complete function):
const token = req.headers.get("Authorization")?.replace(/^Bearer\s+/i, "") ?? "";
// A client that acts as the caller: every read below goes through RLS.
const userClient = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
global: { headers: { Authorization: `Bearer ${token}` } },
});
const { data: userData } = await userClient.auth.getUser(token);
if (!userData.user) return json({ error: "Not signed in" }, 401);
const { data: project } = await userClient
.from("projects")
.select("id, workspace_id, name")
.eq("id", projectId)
.maybeSingle();
if (!project) return json({ error: "Project not found" }, 404); // also for other tenants' projects
// Only now, for the one write clients may not do themselves, use admin rights.
const admin = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
await admin.from("project_exports").insert({ workspace_id: project.workspace_id, project_id: project.id });The rule: read as the user, write as admin only after the check. Answer “not found” for other tenants’ records rather than “forbidden”, so the response doesn’t confirm that an ID exists. Two fix pages cover the variants in detail: edge function without auth check and edge function that trusts user_id from the body.
Test isolation as two tenants
Testing as yourself proves nothing in a multi-tenant app: you’re a member of your own workspace, so of course you see its data. The test that matters uses two users in two different workspaces, and checks every table from the other side.
In the SQL editor
Pick a user from workspace B and the ID of workspace A, then run:
begin;
set local role authenticated;
set local request.jwt.claims = '{"sub": "22222222-2222-2222-2222-222222222222", "role": "authenticated"}';
select count(*) as foreign_projects
from public.projects
where workspace_id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
rollback;Replace the two IDs with real ones from Authentication → Users and your workspaces table. With the sign-in-only policy this returned 1 in our test; after the fix it returns 0. Repeat it for every tenant table, and try an update and an insert in the same way. rollback at the end means nothing is saved.
In the app
Create two workspaces with two accounts
Sign up as user A in a normal browser window and as user B in a private window. Make sure they end up in different workspaces and each creates a project, a task and anything else your app stores.
Swap IDs in URLs
As B, open A’s project URL (copy it from A’s window). Then try the same with every detail page: tasks, invoices, files, settings. You should get “not found” every time, never A’s data.
Look at what the API really returns
In B’s window, open the developer tools, switch to the Network tab and reload a list page. Click the request to /rest/v1/projects (or your table) and read the response, not the screen. It may only contain B’s rows, whatever filter the frontend sends.
Repeat after every schema change
Put the SQL checks into database tests (Supabase supports pgTAP tests with supabase test db), so a later migration can’t quietly undo them. Our guide to testing RLS policies shows how.
Do this only against your own app. The point is to find your own gaps before a customer does.
Views, storage, realtime and other side doors
Tenant isolation has to hold on every path to the data, not just on tables:
- Views run with the rights of their owner by default and skip RLS. Create them with
security_invoker = true; our guide on views and RLS explains why. - Storage objects are rows with their own policies. Put files under a path that starts with the workspace ID and check membership in the storage policy. See Supabase Storage security.
- Realtime subscriptions must respect the same rules, or a client can listen to another tenant’s changes. See Supabase Realtime security.
- Database functions called through RPC that are
security definerbypass RLS like the secret key does. Each one needs its own membership check, or it should not be callable by clients. SeeSECURITY DEFINERwithout checks.
What our audit reports for this bug
We keep small, deliberately broken test apps to measure ShipRely’s audit engine. The project tracker from this guide is one of them, and it has a clean twin: the same app with membership-based policies, composite foreign keys and a caller-scoped edge function.
In our latest benchmark run (December 3, 2026), the engine reported two findings on the broken app, both rated critical: the projects select and update policies only require sign-in, and the export edge function loads any project with the service role without a membership check. On the clean twin it reported nothing. That is the balance we aim for: find the cross-tenant hole, and stay quiet about code that is correct. How we run these tests is described on our methodology page.
A fix prompt for your AI builder
If you build with Lovable, Cursor, Claude Code or Bolt, you can hand the whole pattern to your tool. Review the migration it writes before you apply it:
Audit every table in the public schema that has a workspace_id column (or my tenant column) and write one new migration that:
- Creates private.is_member(ws uuid) as a STABLE SECURITY DEFINER SQL function with SET search_path = ‘’ that checks public.workspace_members for (select auth.uid()); revoke execute from public and anon, grant execute to authenticated.
- Replaces every policy on those tables that only checks auth.uid() is not null, auth.role() = ‘authenticated’ or true with policies for the authenticated role that call private.is_member(workspace_id) in USING and WITH CHECK.
- Revokes all privileges from anon on tenant tables and limits client UPDATE to the columns users may edit, never workspace_id.
- Makes public.workspaces and public.workspace_members select-only for clients.
- Adds unique (workspace_id, id) to parent tables and changes child foreign keys to composite keys (workspace_id, parent_id).
Do not use the service role key in browser code. Afterwards, list every edge function that uses the service role key and tell me which ones read tenant data without checking membership.
Checklist before you launch
Tenant isolation checklist
0/10 done
Your progress is saved in this browser only.
Frequently asked questions
What is the difference between IDOR and BOLA?
They describe the same mistake from two angles. IDOR (insecure direct object reference) is the older web term: changing an ID in a request returns someone else’s record. BOLA (broken object level authorization) is the name the OWASP API Security Top 10 uses for the same flaw in APIs. In a Supabase app, both mean that a query by ID returns a row from a tenant the caller does not belong to.
Do random UUIDs protect me from IDOR?
No. Random IDs make guessing harder, and OWASP recommends them as an extra layer, but IDs leak through URLs, shared links, logs and screenshots. The only real protection is a check in the database or the API that the caller may access that specific row.
Should I put the tenant ID into the user’s JWT instead of using a membership table?
You can read claims from app_metadata in a policy, and Supabase documents that pattern. A membership table is easier to get right for most apps: one row per user and workspace, readable by policies, and removing the row takes effect on the next query. Never read tenant or role information from user_metadata, because users can change it themselves.
Is one Supabase project per customer safer than a workspace_id column?
It isolates more strongly, but it multiplies migrations, keys, backups and costs, and most AI-built SaaS apps don’t need it. A shared schema with a workspace_id on every tenant table, membership-based RLS and composite foreign keys is the common approach and works well when it is tested.
Does the service_role key respect my tenant policies?
No. The secret key (sb_secret_…, or the legacy service_role key) bypasses row level security entirely. Server code that uses it, such as an edge function, has to check membership itself, or better, run its reads with a client that carries the caller’s own token.
Sources
- 1.API1:2023 Broken Object Level Authorization — OWASP API Security Top 10
- 2.CWE-639: Authorization Bypass Through User-Controlled Key — MITRE
- 3.A01 Broken Access Control — OWASP Top 10
- 4.Row Level Security — Supabase Docs
- 5.Understanding API keys — Supabase Docs
- 6.Constraints (foreign keys) — PostgreSQL Documentation
- 7.Row Security Policies — PostgreSQL Documentation