How one column default made strangers admins of each other's data (and the 12 tests that keep it fixed)
I work on a multi-tenant B2B SaaS built on Supabase (Postgres + row-level security). Each customer organisation is a tenant. Every row carries a tenant_slug, and RLS policies make sure you only ever see your own tenant's
I work on a multi-tenant B2B SaaS built on Supabase (Postgres + row-level security). Each customer organisation is a tenant. Every row carries a tenant_slug, and RLS policies make sure you only ever see your own tenant's records.
During a code review, I re-read our signup trigger line by line. It turned out that one signup path didn't give new users their own tenant. It made them admin of a shared legacy tenant. Nothing errored, so nothing flagged it.
This post covers how it happened, how I fixed it, and how I made sure it can't come back.
The setup
Supabase creates a row in auth.users on signup. A trigger, handle_new_user(), then creates the matching public.profiles row, which is where the tenant_slug and role live. RLS policies key off that profile.
The trigger had three branches:
- Invite token present. Join the inviting tenant with the invited role.
-
Organisation name present. Organic signup: create a fresh tenant via
provision_tenant()and make the user its admin. - Neither. The fallback.
The fallback looked harmless:
insert into public.profiles (id, email, role)
values (new.id, new.email, 'admin');
The bug: a default you forgot about
Notice what's missing: tenant_slug.
Months earlier, when I migrated the app from single-tenant to multi-tenant, I added the column like this:
alter table public.profiles
add column if not exists tenant_slug text not null default 'default';
The default was deliberate at the time. Existing rows had to land somewhere so the legacy single-tenant data kept working. 'default' was a legacy tenant holding rows from before the split.
Put the two together:
- The fallback insert omits
tenant_slug. - Postgres fills in
'default'. - The user gets
role = 'admin'.
Every signup that reached the fallback became an admin of the same tenant. Two unrelated people who signed up without an organisation name would have been co-admins, with full read/write over each other's records.
Before writing this up I checked production: the only account that ever went down the fallback path was my own test signup. No customer was affected. That's luck, not design, which is the point of this post.
RLS did exactly what it was told. The policies were correct. The identity feeding them was wrong. That's the lesson I keep coming back to: RLS is only as good as the code that assigns tenants. You can audit every policy and still be wide open.
The fix
Two changes, in one migration.
1. The fallback no longer invents a shared tenant. It now goes through the exact same function organic signup uses, so every unexplained signup gets its own fresh, isolated tenant:
-- FALLBACK: no invite, no organisation name.
perform public.provision_tenant(
new.id, new.email, _full_name,
coalesce(nullif(_full_name, ''), split_part(new.email, '@', 1))
);
The organisation name is just a placeholder (full name or the email's local part) that the user can rename later. What matters is isolation, not a good default name.
2. I closed a race I found on the way. provision_tenant() derives a slug from the organisation name and used to check whether it was free before inserting:
-- old (simplified): check, then insert
if exists (select 1 from tenants where slug = _slug) then ... end if;
insert into tenants (...) values (...) on conflict (slug) do nothing;
That's a classic check-then-insert (TOCTOU) race. Two concurrent signups with the same base slug can both pass the check. The loser's insert is silently swallowed by on conflict do nothing, and its profile then points at the winner's tenant. Routing every fallback signup through this function would have made that race more likely.
The fix is to stop trusting the pre-check and verify the insert actually won, via RETURNING:
loop
_counter := _counter + 1;
exit when _counter > 50;
insert into public.tenants (slug, ...)
values (_slug, ...)
on conflict (slug) do nothing
returning slug into _inserted_slug;
exit when _inserted_slug is not null; -- we really own this slug
_slug := _base_slug || '-' || _counter; -- someone beat us; try the next one
end loop;
if _inserted_slug is null then
raise exception 'could not allocate a unique tenant slug';
end if;
Proving it: pgTAP
A fix you can't test is a fix you'll eventually break. I wrote a pgTAP suite that reproduces the real trigger path. It inserts directly into auth.users, which is exactly what fires on_auth_user_created in a real signup, so no running auth server is needed:
begin;
select plan(12);
create or replace function pg_temp.fake_signup(p_email text, p_meta jsonb)
returns uuid language plpgsql as $$
declare _id uuid := gen_random_uuid();
begin
insert into auth.users (instance_id, id, aud, role, email, encrypted_password,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at)
values ('00000000-0000-0000-0000-000000000000', _id, 'authenticated', 'authenticated',
p_email, 'test-hash', '{"provider":"email","providers":["email"]}', p_meta, now(), now());
return _id;
end $$;
select pg_temp.fake_signup('[email protected]', '{}') as user_a \gset
select ok(
(select tenant_slug from public.profiles where id = :'user_a'::uuid) <> 'default',
'mystery signup does NOT land in a shared tenant'
);
-- ...
rollback;
The 12 assertions pin down:
- a signup with no invite and no organisation name gets a fresh tenant of its own and is admin only of that;
- two signups that derive the same base slug end up in different tenants;
-
provision_tenant()never hands out the reserveddefaultslug; - the invite path still works: invited staff land in the inviting tenant with the invited role, and the invite is marked accepted;
- a valid invite token used with the wrong email does not grant access to the invite's tenant, and leaves the real invite untouched.
It's wrapped in begin; β¦ rollback;, so it leaves nothing behind. It runs in CI on every pull request, next to the app's unit tests.
One honest caveat: the slug-collision test runs signups one after another, so it proves the retry logic and uniqueness, not true concurrency. The concurrency guarantee comes from the RETURNING check plus the unique constraint on tenants.slug, which Postgres enforces whatever the timing.
What I'd tell anyone running multi-tenant Postgres
-
Grep your schema for defaults on tenant columns. A
not null default 'something'ontenant_id/tenant_slugis a loaded gun. Prefer no default, so a missing value fails loudly. - Every branch of a signup trigger needs a test. The happy paths were fine. The bug lived in the branch nobody used on purpose.
-
Never trust check-then-insert for allocation. Insert, then verify with
RETURNING(or catch the unique violation). -
RLS reviews must include identity assignment. Policies are half the system. The trigger that writes
tenant_slugandroleis the other half.
I'm William, a full-stack engineer in Accra building multi-tenant SaaS on React, TypeScript and Postgres/Supabase. I also review Supabase apps for this class of bug: RLS policies, signup triggers, security-definer functions and webhooks, with pgTAP tests you keep. If you'd like a second pair of eyes on yours, reach me via GitHub or LinkedIn. GitHub Β· LinkedIn
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.