Supabase RLS: Policies Without Holes, With Tests
What is RLS in Supabase?
Row Level Security (RLS) is a Postgres mechanism where a policy adds a condition to every query against a table: which rows a role may read and which it may write. In Supabase a request arrives as the anon or authenticated role, while a secret key runs as service_role, which bypasses policies. Access to the table itself is decided by grants, so you need both layers.
TL;DR
- -There are two layers: grants decide whether a role can touch the table, RLS decides which rows. A policy doesn't revoke grants.
- -RLS with no policies fails silently: in the author's test select returned 0 rows, update affected 0 rows, and only insert raised error 42501.
- -The holes in the test came from with check (true) on INSERT, select using (true) paired with a loose UPDATE, a view without security_invoker, a materialized view, a security definer function with EXECUTE left to PUBLIC, and a grant on TRUNCATE.
- -On 1 million rows, auth.uid() with no wrapper and no index took 1,548 ms, (select auth.uid()) 78.6 ms, and with an index 1.1 ms. That is Postgres 17.12 with an auth stub, not Supabase.
- -A denial looks different each time: a missing grant or a failed with check raises 42501, while a row filtered by using gives zero rows and no error. A test has to tell these cases apart.
Supabase RLS is a set of Postgres policies that add a condition to every query: which rows a role can see and which it can write. A protected table takes four steps:
- Enable RLS and revoke the extra grants from
anonandauthenticated. - Grant back only the operations you need.
- Write a separate policy per operation with
to authenticatedand(select auth.uid()). - Test both what is allowed and what is denied.
Almost every hole appears at step three, and you only see it at step four.
Where the numbers come from. The matrix of 28 checks was run on November 29, 2026 in a throwaway container with plain PostgreSQL 17.12, not on Supabase. The anon, authenticated and service_role roles were created by hand, and auth.uid() is a stub that reads request.jwt.claims. One run. The Data API, Storage, Realtime and platform grants weren’t part of it: everything about them comes from the documentation as of the same date. The short script in this article, and the examples that say so, were run separately on PostgreSQL 17.11.
How a request reaches a policy
| Layer | Question | What a denial looks like |
|---|---|---|
| Key and session | which role the request runs as | anon, authenticated or service_role |
| Grants | may the role run this operation on the table | error 42501 permission denied |
RLS, using | which existing rows are available | zero rows, no error |
RLS, with check | what the new row may look like | error 42501 ... row-level security policy |
A sb_publishable_... key gives the anon role when nobody is signed in and authenticated with a user token. A sb_secret_... key gives service_role, which has the BYPASSRLS attribute. It has one non-obvious property: if a user token arrives together with the secret key, the request runs under that user’s RLS. Anonymous sign-in through Supabase Auth also gives the authenticated role; you tell it apart by the is_anonymous claim.
About the old keys: as of November 29, 2026 the documentation says anon and service_role are being deprecated in early 2027. Until November 25 it said the end of 2026.
Grants: what was announced and what is in place
On April 28, 2026 Supabase announced that new tables in public would stop being exposed to the Data API automatically: from May 30 for new projects, from October 30 for all of them. The dates in the announcement are unchanged as of November 29. Other Supabase sources contradict them:
- A CLI pull request merged on August 26: the cloud default change “never landed”.
- A reply from a member of the Supabase organization on October 27: “The cloud default hasn’t changed yet”, with an update on the new timeline promised.
- The documentation as of November 29: on existing projects new objects get grants, and “Supabase is changing the platform default”. It gives no date.
In the announcement discussion users wrote after October 30 that the change was already live; there is no confirmation from Supabase there. You can’t rely on either “everything is closed” or “everything is open”. Ask your own database. The query is shortened from the docs:
select d.defaclobjtype as type, a.grantee::regrole as role,
string_agg(a.privilege_type, ', ' order by a.privilege_type) as privileges
from pg_default_acl d
cross join lateral aclexplode(d.defaclacl) a
where d.defaclrole = 'postgres'::regrole
and d.defaclnamespace = 'public'::regnamespace
and a.grantee in ('anon'::regrole, 'authenticated'::regrole, 'service_role'::regrole)
group by 1, 2 order by 1, 2;
An empty result means new objects are closed until you issue a grant. If rows come back, every new table is open and RLS is the only thing holding it. Existing tables aren’t affected by the change either way.
Protecting a table: the recipe
alter table public.notes enable row level security;
revoke all on table public.notes from anon, authenticated;
grant select, insert, update, delete on table public.notes to authenticated;
create policy "read own" on public.notes for select to authenticated
using ((select auth.uid()) = user_id);
create policy "insert own" on public.notes for insert to authenticated
with check ((select auth.uid()) = user_id);
create policy "update own" on public.notes for update to authenticated
using ((select auth.uid()) = user_id)
with check ((select auth.uid()) = user_id);
create policy "delete own" on public.notes for delete to authenticated
using ((select auth.uid()) = user_id);
create index on public.notes (user_id);
revoke all also removes the privileges people forget about: truncate, references, trigger. Keep grants and RLS in the same migration, otherwise a recreated table ends up either open or unreachable. The wider platform picture is in the Supabase guide.
Common RLS mistakes: what the attacker sees and the fix
The numbers in the first column are rows of the matrix. The attacker is either anon or a signed-in user, Alice, who wants Bob’s rows.
| No. | Mistake | What the attacker sees | Fix |
|---|---|---|---|
| 01 | grant exists, RLS is off | anon reads all 3 rows | enable row level security |
| 12 | INSERT with with check (true) | a row in Bob’s name is inserted | with check ((select auth.uid()) = user_id) |
| 11b | UPDATE with with check (true) and SELECT using (true) | the row is handed to another owner | a condition in with check |
| 21 | a second permissive policy | 4 rows instead of their own, the conditions combine with OR | make the restriction as restrictive |
| 17 | view without security_invoker | anon reads all 5 rows | with (security_invoker = true) |
| 24 | grant on a materialized view | anon reads every row (2 of 2) | revoke the grant or move it out of the exposed schema |
| 19 | security definer function | anon reads all 5 rows | revoke execute ... from public, a private schema |
| 23 | grant on TRUNCATE | the table is emptied, RLS didn’t stop it | revoke truncate |
| 26 | unique index on a sensitive field | 23505 confirms that someone else’s value exists | don’t put unique on a secret, check on the server |
| 27 | secret key in the client | sees everything | key on the server only |
Read row 23 with care: TRUNCATE always reports a row count of 0, and the matrix itself doesn’t print that the table was emptied. You can tell from the rows that follow, and the short script checks it separately: 0 rows were left after TRUNCATE.
Three more cases aren’t holes, but they do confuse people:
| No. | Situation | Result |
|---|---|---|
| 02, 04 | RLS is on, no policies | select 0 rows, update 0 rows, no errors |
| 15 | UPDATE policy without a SELECT policy | 0 rows, no error |
| 16 | INSERT with returning without a SELECT policy | error 42501 |
USING and WITH CHECK: why UPDATE depends on SELECT
using selects existing rows, with check tests what the row becomes. If an UPDATE policy has no with check, Postgres applies using to both. That’s why UPDATE without with check didn’t let Alice give her row to Bob (row 09).
Rows 11 and 11b are more interesting. A policy with with check (true) looks like an obvious hole, yet the row couldn’t be handed over while SELECT showed only the user’s own rows. update ... where reads the table, and the new row has to pass the SELECT policy as well. Once SELECT was changed to using (true), say for a public feed, the row went to another owner. An edit to a neighboring policy opened the hole in UPDATE. Hence the rule: always put the owner condition in with check, even if something else protects you right now.
Permissive policies combine with OR, restrictive ones with AND. Adding “one more small” permissive policy widens access. Express a requirement like MFA as as restrictive: in row 22 a user without aal2 saw 0 rows. A restrictive policy with no permissive one gives access to nobody.
auth.uid(), roles and JWT
- Empty user.
auth.uid()is null for everyanonrequest and for a token withoutsub. Comparing with null is never true, so rows 06-07 return zero. According to the docs, anauth.uid() is null or ...branch returns everything to any request without a user, andto authenticateddoesn’t fully save you. - Without
to, a policy applies topublic, which includesanon. Name the role explicitly. user_metadatais no good for permissions: users can change it themselves. Keep roles and teams inapp_metadata.- A role in the user’s own row. An “edit only your own profile” policy also lets
role = 'admin'through: RLS filters rows, not columns. In a separate run on 17.11 such an UPDATE succeeded. The docs recommend keeping roles in a dedicated table that users can’t write to. - The JWT lags behind. A user has been removed from a team, but the old token still carries the previous claim. If a third-party provider issues the token, this matters twice as much.
RLS performance: the index and the select wrapper
A table of 1 million rows, 1,000 of them the user’s own, median of five select count(*) queries, parallelism off:
| Policy | No index | Index on user_id |
|---|---|---|
auth.uid() = user_id | 1,548 ms | 2.7 ms |
(select auth.uid()) = user_id | 78.6 ms | 1.1 ms |
These numbers use an auth.uid() stub on plain Postgres: absolute values on Supabase will differ, the order of work stays the same. First the index, then the wrapper. An index only counts if the column comes first in it: a primary key on (team_id, user_id) doesn’t help a condition on user_id. For teams the docs recommend team_id in (select team_id from team_user where user_id = (select auth.uid())) without a join to the row.
Functions and infinite recursion
A policy on a members table that reads the same table failed in row 25 with 42P17 infinite recursion. The way out from the documentation is a security definer function in a closed schema:
create schema if not exists private;
create function private.my_team_ids() returns setof int
language sql stable security definer set search_path = '' as $$
select team_id from public.members where user_id = (select auth.uid())
$$;
revoke execute on function private.my_team_ids() from public;
grant usage on schema private to authenticated;
grant execute on function private.my_team_ids() to authenticated;
create policy "members read team" on public.members for select to authenticated
using (team_id in (select private.my_team_ids()));
The function owner has to bypass RLS; on Supabase that is postgres. set search_path = '' is mandatory, otherwise the caller can substitute their own table. The fixed version wasn’t part of the matrix. In a separate run on PostgreSQL 17.11 Alice saw two rows of her team out of three in the table, with no 42P17 error. Don’t keep such functions in a schema exposed to the Data API: a client can call them.
Storage and Realtime: according to the docs
- Storage. Without policies on
storage.objects, uploads are denied. Policies aren’t checked on a download through the public URL of a public bucket, or when a signed URL that was already issued is used. Upsert also needs SELECT and UPDATE. - Realtime channels. Access to Broadcast and Presence is set by policies on
realtime.messages. You needprivate: trueon the channel and “Allow public access” turned off. The decision is cached for the duration of the connection, until a new JWT. - Postgres Changes. Each event is checked for each subscriber, and RLS isn’t applied to DELETE.
A test script you can run yourself
This is a shortened version of the matrix with 14 lines of output. The file is rls-check.sql. Part one: roles, the stub, and a function that runs a query as another role.
create role anon nologin;
create role authenticated nologin;
create schema auth;
grant usage on schema auth, public to anon, authenticated;
create function auth.uid() returns uuid language sql stable as $$
select (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')::uuid
$$;
-- t(): run query q as role r on behalf of user who
create function t(label text, who text, q text, r text default 'authenticated')
returns text language plpgsql as $f$
declare n bigint; res text;
begin
perform set_config('request.jwt.claims',
case when who = '' then '' else json_build_object('sub', who)::text end, true);
execute format('set local role %I', r);
begin
if q ~* '^\s*select' then
execute format('select count(*) from (%s) x', q) into n; res := 'rows=' || n;
else
execute q; get diagnostics n = row_count; res := 'affected=' || n;
end if;
exception when others then res := sqlstate || ' ' || sqlerrm; end;
reset role;
return rpad(label, 34) || res;
end $f$;
Part two: reading and inserting.
\set a '''aaaaaaaa-0000-0000-0000-000000000001'''
\set b '''bbbbbbbb-0000-0000-0000-000000000002'''
create table notes(id int generated always as identity, user_id uuid not null, body text);
insert into notes(user_id, body) values (:a,'a1'), (:a,'a2'), (:b,'b1');
grant select, insert, update, delete on notes to anon, authenticated;
select t('1 RLS off, anon', '', 'select * from notes', 'anon');
alter table notes enable row level security;
select t('2 RLS on, no policies: select', :a, 'select * from notes');
select t('3 RLS on, no policies: update', :a, $$update notes set body='x'$$);
create policy sel on notes for select to authenticated using ((select auth.uid()) = user_id);
create policy ins on notes for insert to authenticated with check (true);
select t('4 insert check(true): as bob', :a,
$$insert into notes(user_id, body) values ('bbbbbbbb-0000-0000-0000-000000000002','fake')$$);
alter policy ins on notes with check ((select auth.uid()) = user_id);
select t('5 insert own check: as bob', :a,
$$insert into notes(user_id, body) values ('bbbbbbbb-0000-0000-0000-000000000002','fake')$$);
Part three: UPDATE, views, the function, TRUNCATE.
create policy upd on notes for update to authenticated
using ((select auth.uid()) = user_id) with check (true);
\set give '$$update notes set user_id=''bbbbbbbb-0000-0000-0000-000000000002'' where body=''a1''$$'
select t('6 check(true), select own', :a, :give);
alter policy sel on notes using (true);
select t('7 check(true), select true', :a, :give);
\set give2 '$$update notes set user_id=''bbbbbbbb-0000-0000-0000-000000000002'' where body=''a2''$$'
drop policy upd on notes;
create policy upd on notes for update to authenticated using ((select auth.uid()) = user_id);
select t('8 no check, select true', :a, :give2);
alter policy sel on notes using ((select auth.uid()) = user_id);
create view v_plain as select * from notes;
create view v_inv with (security_invoker = true) as select * from notes;
grant select on v_plain, v_inv to anon;
select t('9 view default, anon', '', 'select * from v_plain', 'anon');
select t('10 view security_invoker, anon', '', 'select * from v_inv', 'anon');
create function all_notes() returns setof notes language sql security definer
set search_path = '' as 'select * from public.notes';
select t('11 definer function, anon', '', 'select * from all_notes()', 'anon');
revoke execute on function all_notes() from public;
select t('12 after revoke, anon', '', 'select * from all_notes()', 'anon');
grant truncate on notes to authenticated;
select t('13 truncate', :a, 'truncate notes');
select '14 rows left: ' || count(*) from notes;
Run it in a container with no network (the author didn’t start the container itself for this check; the script ran in a temporary local cluster). Don’t run the script on a working database: it creates roles and tables.
docker run -d --rm --name rls --network none -e POSTGRES_PASSWORD=x postgres:17-alpine
until docker exec rls pg_isready -q -h 127.0.0.1 -U postgres; do sleep 1; done
docker exec -i rls psql -U postgres -qAt < rls-check.sql
docker stop rls
Expected output:
1 RLS off, anon rows=3
2 RLS on, no policies: select rows=0
3 RLS on, no policies: update affected=0
4 insert check(true): as bob affected=1
5 insert own check: as bob 42501 new row violates row-level security policy for table "notes"
6 check(true), select own 42501 new row violates row-level security policy for table "notes"
7 check(true), select true affected=1
8 no check, select true 42501 new row violates row-level security policy for table "notes"
9 view default, anon rows=4
10 view security_invoker, anon rows=0
11 definer function, anon rows=4
12 after revoke, anon 42501 permission denied for function all_notes
13 truncate affected=0
14 rows left: 0
Lines 1, 4, 7, 9, 11 and 14 are holes. Line 8 separates two mechanisms: SELECT is open, but using acted as with check.
Tests in a project: supabase test db
On Supabase, pgTAP does the same job. The recipe from the docs: one file per table in supabase/tests/, the role through set local role, the user through set local request.jwt.claim.sub, and supabase test db to run it. The stub in the script above doesn’t read that parameter, so you can’t copy the files over as they are.
| What denied it | What Postgres does | How to test |
|---|---|---|
| no grant | error 42501 | throws_ok |
with check failed | error 42501 | throws_ok |
using filtered the row out | zero rows, no error | is_empty with returning, then read the intact row |
Don’t prove an allowed write with lives_ok: it passes even when zero rows were affected. Full test files are in the RLS guide; the author hasn’t run them. Edge Functions code is tested separately, for example with supabase-edge-toolkit.
The second safety net is advisors: the Dashboard, supabase db advisors, or get_advisors in MCP (for that server’s permissions, see the MCP security guide). Judging by the lint code, they catch a table without RLS (0013), auth.uid() without select (0003), a view without security_invoker (0010), a materialized view in the API (0016), with check (true) on writes (0024) and open security definer functions (0028, 0029). Lint 0024 skips SELECT with using (true) on purpose. Advisors also can’t tell that a policy compares the wrong column.
Checklist for each table
- RLS is on,
revoke allfromanonandauthenticatedis done. - Grants are issued per operation, without
truncate. - One policy per operation, with the role named in
to. with checkwith the owner condition on INSERT and UPDATE.(select auth.uid())and an index where that column comes first.- Views use
security_invoker, materialized views are closed. security definerinprivate, withsearch_path = ''andrevoke execute.- Permissions come from
app_metadataor a dedicated roles table, not fromuser_metadataor the user’s own profile row. - A test for the denial and one for the permission, with writes checked through
returning. - Advisors show no new warnings,
pg_default_aclis checked.