Supabase RLS: Policies Without Holes, With Tests

By Updated

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:

  1. Enable RLS and revoke the extra grants from anon and authenticated.
  2. Grant back only the operations you need.
  3. Write a separate policy per operation with to authenticated and (select auth.uid()).
  4. 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

LayerQuestionWhat a denial looks like
Key and sessionwhich role the request runs asanon, authenticated or service_role
Grantsmay the role run this operation on the tableerror 42501 permission denied
RLS, usingwhich existing rows are availablezero rows, no error
RLS, with checkwhat the new row may look likeerror 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.MistakeWhat the attacker seesFix
01grant exists, RLS is offanon reads all 3 rowsenable row level security
12INSERT with with check (true)a row in Bob’s name is insertedwith check ((select auth.uid()) = user_id)
11bUPDATE with with check (true) and SELECT using (true)the row is handed to another ownera condition in with check
21a second permissive policy4 rows instead of their own, the conditions combine with ORmake the restriction as restrictive
17view without security_invokeranon reads all 5 rowswith (security_invoker = true)
24grant on a materialized viewanon reads every row (2 of 2)revoke the grant or move it out of the exposed schema
19security definer functionanon reads all 5 rowsrevoke execute ... from public, a private schema
23grant on TRUNCATEthe table is emptied, RLS didn’t stop itrevoke truncate
26unique index on a sensitive field23505 confirms that someone else’s value existsdon’t put unique on a secret, check on the server
27secret key in the clientsees everythingkey 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.SituationResult
02, 04RLS is on, no policiesselect 0 rows, update 0 rows, no errors
15UPDATE policy without a SELECT policy0 rows, no error
16INSERT with returning without a SELECT policyerror 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 every anon request and for a token without sub. Comparing with null is never true, so rows 06-07 return zero. According to the docs, an auth.uid() is null or ... branch returns everything to any request without a user, and to authenticated doesn’t fully save you.
  • Without to, a policy applies to public, which includes anon. Name the role explicitly.
  • user_metadata is no good for permissions: users can change it themselves. Keep roles and teams in app_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:

PolicyNo indexIndex on user_id
auth.uid() = user_id1,548 ms2.7 ms
(select auth.uid()) = user_id78.6 ms1.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 need private: true on 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 itWhat Postgres doesHow to test
no granterror 42501throws_ok
with check failederror 42501throws_ok
using filtered the row outzero rows, no erroris_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

  1. RLS is on, revoke all from anon and authenticated is done.
  2. Grants are issued per operation, without truncate.
  3. One policy per operation, with the role named in to.
  4. with check with the owner condition on INSERT and UPDATE.
  5. (select auth.uid()) and an index where that column comes first.
  6. Views use security_invoker, materialized views are closed.
  7. security definer in private, with search_path = '' and revoke execute.
  8. Permissions come from app_metadata or a dedicated roles table, not from user_metadata or the user’s own profile row.
  9. A test for the denial and one for the permission, with writes checked through returning.
  10. Advisors show no new warnings, pg_default_acl is checked.

Frequently Asked Questions

RLS is on and the query returns an empty result with no error. Why?
With no policies the default is deny, and a read returns zero rows. The same happens when using matches no rows, or when the request has no user and auth.uid() is null. Error 42501 on a read means something else: the role has no grant on the table.
Can I use a secret key or service_role in the browser?
No. A secret key runs as the service_role role, which has BYPASSRLS and sees every row. Supabase answers sb_secret from a browser with a 401, but a leaked key works from any other client.
Why is (select auth.uid()) better than auth.uid()?
The wrapper makes Postgres compute the value once per query instead of once per row. In the author's test on 1 million rows without an index that was 78.6 ms against 1,548 ms. With an index on the column the gap is smaller: 1.1 and 2.7 ms.
Why doesn't UPDATE work without a SELECT policy?
An UPDATE with a where clause reads rows, so SELECT policies apply to it too. Without them the query in the test affected 0 rows and raised no error. For the same reason an INSERT with returning and no SELECT policy fails with 42501.
Can a view see other users' rows?
Yes, if it was created without security_invoker. A plain view checks the owner's permissions, and in the test anon got all 5 rows of the table through it. With security_invoker = true the result was zero. A materialized view has no such option, so you close it with grants.
How do I test RLS without Supabase?
In a throwaway Postgres with anon and authenticated roles and an auth.uid() stub. That checks the policy logic. It doesn't reproduce platform grants, the Data API, Storage or Realtime: test those on a local Supabase stack with supabase test db.
When will the anon and service_role keys be turned off?
Supabase docs as of November 29, 2026 say the old keys are being deprecated in early 2027, with no exact date. They used to say the end of 2026, and the wording changed on November 25. New keys work side by side with the old ones, so you can migrate gradually.