Deutsch
GuideSupabase · Database

How to test your Supabase RLS policies with SQL

Test Supabase RLS policies the way an attacker would: as a visitor, as two different users and as the service role, in plain SQL and with pgTAP.

By Tim GeithnerPublished 6 min read

Short answer

The Supabase SQL Editor runs as an admin that skips row level security, so a query that works there proves nothing. To test a policy, open a transaction, switch to the anon or authenticated role, set the user ID the policy reads, run the query and roll back. Do it as a visitor, as two different users and once as the service role, check writes with RETURNING, then turn the same checks into a pgTAP file that runs with supabase test db.

Ask an AI about this page:ChatGPTClaude

On this page

Key takeaways

  • The SQL Editor and the secret key skip RLS. “It works in the dashboard” says nothing about what a user can see.
  • To test a policy, switch role inside a transaction: set local role authenticated, set the user ID, query, rollback.
  • Test every table as four identities: a visitor, the owner, a second user and the service role.
  • A blocked update or delete does not raise an error; it changes zero rows. Always check writes with returning.
  • Turn the checks into a pgTAP file in supabase/tests so the next migration can’t quietly undo them.

Why the SQL Editor can’t test your policies

When you open the SQL Editor in the Supabase dashboard, you are the postgres role. Supabase describes it as the default role with admin privileges, and in most projects it also owns your tables. Row level security does not apply to a table’s owner, so every query you run there returns every row.

The secret key behaves the same way from the outside. Supabase’s service_role is the role the Data API uses “to bypass Row Level Security”, and the sb_secret_… and legacy service_role keys switch to it. If you test with either, a broken policy looks exactly like a working one.

Your users never get those rights. A visitor’s request runs as anon, a signed-in user’s request runs as authenticated with their user ID available through auth.uid(). So that is what a test has to reproduce.

The table we test

The examples use a notes table with the four owner-only policies from our row level security guide. Replace the table and column names with your own.

The table and its policies
create table public.notes (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) on delete cascade,
  body text not null
);

alter table public.notes enable row level security;

create policy "Owners read notes" on public.notes for select
  to authenticated using ((select auth.uid()) = user_id);
create policy "Owners add notes" on public.notes for insert
  to authenticated with check ((select auth.uid()) = user_id);
create policy "Owners edit notes" on public.notes for update
  to authenticated using ((select auth.uid()) = user_id)
  with check ((select auth.uid()) = user_id);
create policy "Owners delete notes" on public.notes for delete
  to authenticated using ((select auth.uid()) = user_id);

You need two test accounts. Create them in your app or under Authentication → Users and copy their IDs. In the examples, Alice is 11111111-… and Bob is 22222222-….

Test 1: read as a signed-in user

Everything happens inside begin … rollback. set local only lasts until the transaction ends, and the rollback throws away anything the test changed.

See what Alice sees
begin;
set local role authenticated;
set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';

select auth.uid();                          -- who am I right now?
select user_id, body from public.notes;     -- expect: Alice's rows only
rollback;

The first query confirms that auth.uid() returns Alice’s ID. If it returns null, your policies see a signed-out user and every owner check fails quietly. The second query must return only rows whose user_id is Alice. If you see a single row of Bob’s, the table leaks, typically through a policy like using (true) or a second permissive policy that someone added later. Postgres combines permissive policies with OR, so one loose policy opens the whole table.

Test 2: write as the owner and as someone else

Reads are the easy half. Most real leaks are writes: changing, deleting or creating rows that belong to someone else.

Alice edits her note, then tries Bob's
begin;
set local role authenticated;
set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';

-- allowed: Alice edits her own note
update public.notes set body = 'edited'
where user_id = '11111111-1111-1111-1111-111111111111'
returning id, body;                         -- expect: 1 row

-- denied: Alice edits or deletes Bob's note
update public.notes set body = 'changed by Alice'
where user_id = '22222222-2222-2222-2222-222222222222'
returning id;                               -- expect: 0 rows
delete from public.notes
where user_id = '22222222-2222-2222-2222-222222222222'
returning id;                               -- expect: 0 rows
rollback;

Inserts behave differently. Here the with check clause decides, and a violation is a real error:

Alice tries to create a note in Bob's name
begin;
set local role authenticated;
set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';

insert into public.notes (user_id, body)
values ('22222222-2222-2222-2222-222222222222', 'planted by Alice');
-- expect: ERROR new row violates row-level security policy for table "notes"
rollback;

If this insert succeeds, any signed-in user can create rows in another user’s name. That is the missing ownership check pattern, and it is just as dangerous on tables that hold money or status values as it is on notes.

Test 3: read as a visitor

A visitor with only your public key runs as anon and has no user ID:

See what a signed-out visitor sees
begin;
set local role anon;
select count(*) from public.notes;   -- expect: 0 (or "permission denied" without an anon grant)
rollback;

Both results are fine. Zero rows means the grant exists but no policy lets anon through. permission denied for table notes means you also revoked the table grant from anon, which is a second lock. Anything above zero is a leak to the whole internet.

Test 4: confirm what the service role sees

What your secret key can do
begin;
set local role service_role;
select count(*) from public.notes;   -- expect: every row in the table
rollback;

This is not a policy test; it is a reminder. The service role sees and changes every row regardless of your policies. That is correct for a payment webhook or an admin job on the server, and it is why that key must never reach the browser.

What to test for every table

Run the same four identities against each table that holds user data. This matrix is the minimum for an owner-only table:

Whoselectinsertupdatedelete
Visitor (anon)0 rows or deniederror0 rows or denied0 rows or denied
Ownerown rowsown rows onlyown rows, 1+ returnedown rows, 1+ returned
Second usernone of the owner’serror in owner’s name0 rows on owner’s0 rows on owner’s
service_roleeverythinganythinganythinganything

For shared data, add a fifth identity: a member of the workspace who is not the owner. They should get exactly what your policies promise members, and a non-member should get nothing. The multi-tenant guide covers those policies.

Turn the checks into a pgTAP test

Manual checks catch today’s bug. A test file catches the migration that brings it back in three months. Supabase runs database tests with pgTAP through the CLI: put .sql files in supabase/tests, then run supabase test db. To use pgTAP functions, the extension must be enabled (create extension pgtap with schema extensions;). Every file is one transaction that is rolled back at the end.

supabase/tests/notes_rls_test.sql
begin;
select plan(5);

-- test data, rolled back at the end
insert into auth.users (id, email) values
  ('11111111-1111-1111-1111-111111111111', 'alice@example.test'),
  ('22222222-2222-2222-2222-222222222222', 'bob@example.test');
insert into public.notes (user_id, body) values
  ('11111111-1111-1111-1111-111111111111', 'Alice''s note'),
  ('22222222-2222-2222-2222-222222222222', 'Bob''s note');

-- as Alice
set local role authenticated;
set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';

select results_eq(
  $$ select body from public.notes $$,
  array['Alice''s note'],
  'Alice sees only her own note'
);
select throws_ok(
  $$ insert into public.notes (user_id, body)
     values ('22222222-2222-2222-2222-222222222222', 'planted') $$,
  '42501', null,
  'Alice cannot create a note in Bob''s name'
);
select is_empty(
  $$ update public.notes set body = 'changed'
     where user_id = '22222222-2222-2222-2222-222222222222' returning id $$,
  'Alice cannot change Bob''s note'
);

-- as Bob: his note is untouched
set local request.jwt.claim.sub = '22222222-2222-2222-2222-222222222222';
select results_eq(
  $$ select body from public.notes $$,
  array['Bob''s note'],
  'Bob''s note is unchanged'
);

-- as a visitor with only the public key
set local role anon;
select is_empty($$ select * from public.notes $$, 'Visitors see no notes');

select * from finish();
rollback;

A few rules make these tests trustworthy:

  • plan(n) must match the number of assertions, or the run fails.
  • throws_ok with 42501 is the error code for a denied insert or a missing grant.
  • Pair every denied write with a read of the target row, as the Bob check does. That is what proves nothing changed.
  • Never prove an allowed write with lives_ok. It also passes when the write matched zero rows. Use returning and results_eq instead.

If you write many of these files, Supabase also links a community package, basejump-supabase_test_helpers, with helpers such as tests.authenticate_as() and tests.rls_enabled('public'). It is third-party code, so pin the version you install.

A fix prompt for your AI builder

If your project has no database tests yet, let your AI tool write the first ones. Review every expectation it writes: a test that encodes a leak is worse than no test.

Write pgTAP RLS tests for every table

Add pgTAP tests for the Supabase project in supabase/tests, one file per table in the public schema that has row level security enabled, named after the table, for example notes_rls_test.sql. Each file runs in begin ... rollback, starts with select plan(n) and ends with select * from finish().

In each file, insert two test users into auth.users and test data for both. Then test four identities: anon (set local role anon), the owner and a second user (set local role authenticated plus set local request.jwt.claim.sub = ‘USER_ID’), and confirm the second user cannot read, update, delete or insert rows that belong to the owner. Prove allowed writes with returning and results_eq, never with lives_ok. Use throws_ok with ‘42501’ for denied inserts. After every denied update or delete, read the row again to prove it is unchanged.

Do not change any policy or migration. If a test fails because a policy is too open, stop and list the table and the failing check for me.

Frequently asked questions

Why does my query return every row in the Supabase SQL Editor?

The SQL Editor connects as the postgres role, which owns your tables. Row level security does not apply to a table’s owner unless you force it, so you see everything. Switch to the anon or authenticated role inside a transaction to see what your users see.

How do I pretend to be a specific user in SQL?

Inside a transaction, run set local role authenticated and set local request.jwt.claim.sub to the user’s ID. auth.uid() then returns that ID, so your policies behave as if that user had sent the request. End with rollback so nothing you change is kept.

Why did my update test pass even though the policy is wrong?

An update or delete that RLS blocks usually does not fail; it simply matches zero rows. A test that only checks ‘no error’ passes either way. Add RETURNING to the statement and check how many rows came back, then read the row again to confirm it did not change.

Can I run pgTAP tests against my hosted Supabase project?

Supabase documents pgTAP tests for the Supabase CLI: put .sql files in supabase/tests and run supabase test db, usually against your local development database. Each file runs in a transaction that is rolled back, so test data does not stay behind.

Sources

  1. 1.Row Level Security — Supabase Docs
  2. 2.Testing your database — Supabase Docs
  3. 3.pgTAP: Unit testing — Supabase Docs
  4. 4.Advanced pgTAP testing — Supabase Docs
  5. 5.Postgres Roles — Supabase Docs

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt