Files
supabase-vercel-tedd[bot] 74cb5aa97a docs(rls): warn that an auth.uid() is null branch exposes every row (#53995)
## Problem

The RLS guide explains that `auth.uid()` is `null` for a request without
a user, but not what happens when a policy tests for `null` on purpose.
A condition such as `auth.uid() is null or auth.uid() = user_id` returns
every row to such a request. The guide also never says which roles a
policy with no `to` clause applies to.

Related to
[FDBKIN-31059](https://linear.app/supabase/issue/FDBKIN-31059/update-rls-documentation-to-warn-against-common-anon-leak-policy)
Closes
[DOCS-1798](https://linear.app/supabase/issue/DOCS-1798/warn-that-an-authuid-is-null-or-policy-condition-exposes-every-row)

## Solution

The `auth.uid()` section of the RLS guide now states in body text when
`auth.uid()` is `null` and what an owner comparison returns then. A
`danger` admonition replaces the old caution: it shows the insecure `is
null` branch, explains why `to authenticated` alone doesn't fix it, and
gives a safe owner-only policy to copy. "Specify roles in your policies"
now says that a policy with no `to` clause applies to `public`, which
includes `anon`. The old advice to add `auth.uid() IS NOT NULL AND` is
removed, because the plain comparison already returns no rows for such
requests.

## How to verify

1. Open
https://docs-git-tedd-docs-1798-supabase.vercel.app/docs/guides/database/postgres/row-level-security#authuid
and
https://docs-git-tedd-docs-1798-supabase.vercel.app/docs/guides/database/postgres/row-level-security#specify-roles-in-your-policies.
2. The `auth.uid()` section says it returns `null` for any request whose
JWT has no `sub`, including every `anon` request.
3. A danger admonition warns that an `auth.uid() is null` branch returns
every row to such requests, and that `to authenticated` doesn't remove
the risk.
4. The admonition ends with a copyable policy that uses `to
authenticated` and `(select auth.uid()) = user_id`, with no `is null`
branch.
5. "Specify roles in your policies" says a policy with no `to` clause
applies to `public`, which every role, including `anon`, is a member of.
6. The new link from "Specify roles in your policies" (`#authuid`) jumps
to the `auth.uid()` section.

## Checks

Ran `pnpm exec oxfmt --check` on the changed page. ESLint ignores MDX
files. Ran both SQL snippets in PGlite 0.4.5 with `anon` and
`authenticated` roles, Supabase's `auth.uid()` definition, a two-row
table with `select` granted to both roles, and RLS on. With the insecure
policy and no `to`, `anon` reads both rows. With `to authenticated`, a
request with no `sub` reads both rows. With the safe policy, a user
reads only their own row and a request with no `sub` reads none. A
policy with no `to` lists `public` in `pg_policies.roles`, which matches
the Postgres `CREATE POLICY` docs. `pnpm build:guides-markdown` was not
run, because its federated-content step needs GitHub credentials.

## Checklist

- [x] I have read the [Contributing
Guidelines](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] I have checked that the change works in the preview deployment

## Feedback for Tedd

To ask Tedd for a change to this PR, reply in Tedd's session on
[DOCS-1798](https://linear.app/supabase/issue/DOCS-1798/warn-that-an-authuid-is-null-or-policy-condition-exposes-every-row).
Tedd doesn't read comments on this PR.

---------

Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
2026-11-24 20:02:38 -07:00

857 lines
35 KiB
Plaintext

---
id: 'row-level-security'
title: 'Row Level Security'
description: 'Secure your data using Postgres Row Level Security.'
subtitle: 'Secure your data using Postgres Row Level Security.'
---
Postgres [Row Level Security (RLS)](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) gives you granular authorization rules that run inside the database.
<Admonition type="danger">
A table in an exposed schema without RLS is readable and writable by any role with a grant on it. Enable RLS on every table in an exposed schema. On projects that still grant `anon` and `authenticated` by default, revoke those grants. Adding policies doesn't remove them.
</Admonition>
<Admonition type="tip">
To control which tables, columns, and schemas the Data API exposes at all, refer to [Securing your API](/docs/guides/api/securing-your-api). To write policies based on roles in JWT claims, refer to [Custom claims and role-based access control (RBAC)](/docs/guides/api/custom-claims-and-role-based-access-control-rbac).
</Admonition>
Use the guide in three parts:
- [Understand Row Level Security](#understand-row-level-security) explains how grants and policies combine to control access.
- [Secure a table with RLS](#secure-a-table-with-rls) is the procedure to follow for every table in an exposed schema: grants, policies, and `supabase test db`.
- [RLS reference](#rls-reference) documents the helper functions and patterns you use inside a policy expression.
Read the first section when you're deciding how to model access. Go directly to the second section when you're ready to secure a table.
## Understand Row Level Security
### What a policy does
[Policies](https://www.postgresql.org/docs/current/sql-createpolicy.html) are Postgres's rule engine. Each policy is attached to a table, and the policy is executed every time a table is accessed.
Think of a policy as adding a `WHERE` clause to every query. A policy like this:
```sql
create policy "Individuals can view their own todos."
on todos for select
to authenticated
using ( (select auth.uid()) = user_id );
```
That policy translates to this whenever a user selects from the todos table:
```sql
select *
from todos
where auth.uid() = todos.user_id;
-- Policy is implicitly added.
```
You write RLS rules in SQL, so a rule can express whatever access logic your app needs. Because RLS is a Postgres primitive, it also protects your data when it is reached through third-party tooling, which is what makes it "[defense in depth](<https://en.wikipedia.org/wiki/Defense_in_depth_(computing)>)". Combine RLS with [Supabase Auth](/docs/guides/auth) for end-to-end user security from the browser to the database.
### Grants and policies
Postgres runs two checks before a client touches a table. Grants decide whether a role can run an operation on the table at all. Policies decide which rows that operation applies to. Set both for every table you expose.
On existing projects, a new table in `public` starts with every privilege already granted to all three roles. The default grants include `select`, `insert`, `update`, `delete`, `truncate`, `references`, `trigger`, and, on Postgres 17, `maintain`:
| Role | Granted automatically | What it should keep |
| --------------- | --------------------- | ------------------------------------------------------- |
| `anon` | Every privilege | Only what signed-out visitors are meant to read |
| `authenticated` | Every privilege | Only the operations your app exposes to signed-in users |
| `service_role` | Every privilege | Full access. It bypasses RLS, so keep it server-side |
Adding policies doesn't take those grants back. A table protected only by policies still hands `anon` an insert path if you never revoke the grant.
Not every project grants these automatically. See [Default privileges](/docs/guides/api/securing-your-api#default-privileges). Grant each role only the operations it needs.
A [missing grant](/kb/troubleshooting/database-api-42501-errors) raises a `42501` error before any policy runs. When a request fails that your policy should allow, check the grants before you change the policy. To set them, see [Enable RLS and set the grants](#enable-rls-and-set-the-grants).
### Authenticated and unauthenticated roles
Supabase maps every request to one of the roles:
- `anon`: an unauthenticated request (the user is not signed in)
- `authenticated`: an authenticated request (the user is signed in)
These are [Postgres Roles](/docs/guides/database/postgres/roles). You can use these roles within your Policies using the `TO` clause:
```sql
create policy "Profiles are viewable by everyone"
on profiles for select
to authenticated, anon
using ( true );
-- OR
create policy "Public profiles are viewable only by authenticated users"
on profiles for select
to authenticated
using ( true );
```
<Admonition type="note" title="Anonymous user vs the anon key">
Using the `anon` Postgres role is different from an [anonymous user](/docs/guides/auth/auth-anonymous) in Supabase Auth. An anonymous user assumes the `authenticated` role to access the database and can be differentiated from a permanent user by checking the `is_anonymous` claim in the JWT.
</Admonition>
A policy that reads `to anon using ( true )` grants every unauthenticated visitor read access to every row the role can already reach through grants. Use it only for data that is meant to be public.
### Views and RLS
Views bypass RLS by default because they are usually created with the `postgres` user. This is a feature of Postgres, which automatically creates views with `security definer`. A view over a protected table hands out every row its policies were meant to withhold, so a view needs the same attention as a table. To create one safely, see [Expose a view safely](#expose-a-view-safely).
## Secure a table with RLS
Follow these steps for every table in an exposed schema:
1. [Enable RLS and set the grants](#enable-rls-and-set-the-grants) to match the app.
2. [Write a policy per operation](#write-a-policy-for-each-operation).
3. [Create a `.sql` file under `supabase/tests/`](#policy-tests) that asserts allow and deny for `select`, `insert`, `update`, and `delete`, for `anon` and `authenticated`.
4. [Run `supabase test db`](#run-the-test-suite) and fix what it reports.
Until the suite passes, you don't know whether the policies do what you intended.
### Enable RLS and set the grants
Run the following SQL using the [SQL Editor](/dashboard/project/_/sql) in the Supabase Dashboard or with `psql` over a direct connection. To connect with `psql`, see [Direct connection](/docs/guides/database/connecting-to-postgres#direct-connection). To keep the change reproducible across environments, put the statements in a [migration](/docs/guides/deployment/database-migrations) instead. Grants and RLS belong in the same migration.
Enable RLS, then set the grants to match what each role does in your app:
1. Enable RLS on the table.
```sql
alter table public.reports enable row level security;
```
Once RLS is enabled, no data is accessible through the [API](/docs/guides/api) when using a publishable key, until you create policies.
2. Revoke any existing grants from both client roles.
```sql
revoke all on table public.reports from anon, authenticated;
```
3. Grant back only the privileges the role needs.
```sql
-- Signed-in users manage reports. Signed-out visitors get nothing.
grant select, insert, update, delete on table public.reports to authenticated;
```
4. Write the test file for the table, and run the suite.
```bash
supabase test new reports_rls
supabase test db
```
Give every table you secure one. The examples below show what goes in the file.
Data that clients read but never write, such as a feed a backend job populates, gets select only. The policy and the test file are part of the same change:
```sql
alter table public.announcements enable row level security;
revoke all on table public.announcements from anon, authenticated;
grant select on table public.announcements to anon, authenticated;
create policy "Anyone can read announcements"
on public.announcements for select
to anon, authenticated
using ( true );
```
```sql supabase/tests/announcements_rls_test.sql
-- File: supabase/tests/announcements_rls_test.sql
-- Create: supabase test new announcements_rls
-- Run: supabase test db
-- Repeat for every public-read table you secured.
begin;
select plan(10);
insert into announcements (id, body)
values ('33333333-3333-3333-3333-333333333333', 'published');
-- A read has to return the row. lives_ok passes on an empty result.
select ok(
not has_table_privilege('anon', 'public.announcements', 'insert,update,delete'),
'anon holds no write grant on the feed'
);
select ok(
not has_table_privilege('authenticated', 'public.announcements', 'insert,update,delete'),
'authenticated holds no write grant on the feed'
);
set local role anon;
select results_eq(
$$select body from announcements where id = '33333333-3333-3333-3333-333333333333'$$,
array['published'],
'anon reads the feed'
);
select throws_ok(
$$insert into announcements select * from announcements$$,
'42501',
null,
'anon cannot insert into the feed'
);
select throws_ok(
$$update announcements set id = id$$,
'42501',
null,
'anon cannot update the feed'
);
select throws_ok(
$$delete from announcements$$,
'42501',
null,
'anon cannot delete from the feed'
);
set local role authenticated;
select results_eq(
$$select body from announcements where id = '33333333-3333-3333-3333-333333333333'$$,
array['published'],
'authenticated reads the feed'
);
select throws_ok(
$$insert into announcements select * from announcements$$,
'42501',
null,
'authenticated cannot insert into the feed'
);
select throws_ok(
$$update announcements set id = id$$,
'42501',
null,
'authenticated cannot update the feed'
);
select throws_ok(
$$delete from announcements$$,
'42501',
null,
'authenticated cannot delete from the feed'
);
select * from finish();
rollback;
```
If new tables still receive automatic grants, see [Revoke default privileges](/docs/guides/api/securing-your-api#revoke-default-privileges). To enable RLS automatically on every new table, see [Event triggers](/docs/guides/database/postgres/event-triggers).
### Write a policy for each operation
Write a separate policy for `select`, `insert`, `update`, and `delete`. Postgres does not accept multiple operations in one `for` clause, and a `for all` policy hides which operation each rule was meant to cover.
These examples use a `profiles` table where each user manages only their own row:
```sql
create table profiles (
id uuid primary key,
user_id uuid references auth.users,
avatar_url text
);
alter table profiles enable row level security;
revoke all on table profiles from anon, authenticated;
grant select, insert, update, delete on table profiles to authenticated;
```
Supabase provides [helper functions](#helper-functions) that simplify RLS if you are using Supabase Auth. `auth.uid()` returns the ID of the user making the request.
#### SELECT policies
You can specify select policies with the `using` clause.
```sql
create policy "Users can view their own profile."
on profiles for select
to authenticated
using ( (select auth.uid()) = user_id );
```
#### INSERT policies
You can specify insert policies with the `with check` clause. The `with check` expression ensures that any new row adheres to the policy constraints, so a user cannot create a row that belongs to someone else.
```sql
create policy "Users can create their own profile."
on profiles for insert
to authenticated
with check ( (select auth.uid()) = user_id );
```
#### UPDATE policies
You can specify update policies by combining the `using` and `with check` expressions. The `using` clause decides which existing rows can be updated. The `with check` clause decides what the resulting row is allowed to look like, which stops a user from reassigning `user_id` to someone else.
```sql
create policy "Users can update their own profile."
on profiles for update
to authenticated
using ( (select auth.uid()) = user_id ) -- checks the existing row
with check ( (select auth.uid()) = user_id ); -- checks the resulting row
```
If no `with check` expression is defined, the `using` expression decides both which rows are visible and which new rows are allowed.
<Admonition type="caution">
To perform an `UPDATE` operation, a corresponding [`SELECT` policy](#select-policies) is required. Without a `SELECT` policy, the `UPDATE` operation will not work as expected.
</Admonition>
#### DELETE policies
You can specify delete policies with the `using` clause.
```sql
create policy "Users can delete their own profile."
on profiles for delete
to authenticated
using ( (select auth.uid()) = user_id );
```
#### Policy tests
When you adapt those four policies to a table, add this file for that table. The path is `supabase/tests/<table>_rls_test.sql`. For a table users share, also assert that a member who is not the owner can perform the operations its policies allow, and that a non-member cannot.
```sql supabase/tests/profiles_rls_test.sql
-- File: supabase/tests/profiles_rls_test.sql
-- Create: supabase test new profiles_rls
-- Run: supabase test db
-- One file per table you enabled RLS on. Name that table in the assertions.
-- Do not create a table only the tests use.
begin;
select plan(14);
insert into auth.users (id, email)
values
('11111111-1111-1111-1111-111111111111', 'owner@example.com'),
('22222222-2222-2222-2222-222222222222', 'other@example.com');
-- anon holds no grant, so the request stops before any policy runs.
set local role anon;
select throws_ok(
$$select * from profiles$$,
'42501',
null,
'anon cannot read profiles'
);
select throws_ok(
$$insert into profiles (id, user_id, avatar_url)
values (
gen_random_uuid(),
'11111111-1111-1111-1111-111111111111',
'anon.png'
)$$,
'42501',
null,
'anon cannot create a profile'
);
select throws_ok(
$$update profiles set avatar_url = 'anon.png'$$,
'42501',
null,
'anon cannot update profiles'
);
select throws_ok(
$$delete from profiles$$,
'42501',
null,
'anon cannot delete profiles'
);
-- The owner writes their own row. returning proves the row changed.
set local role authenticated;
set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';
select results_eq(
$$insert into profiles (id, user_id, avatar_url)
values (
gen_random_uuid(),
'11111111-1111-1111-1111-111111111111',
'owner.png'
)
returning avatar_url$$,
array['owner.png'],
'the owner creates their own profile'
);
select results_eq(
$$select avatar_url from profiles where user_id = '11111111-1111-1111-1111-111111111111'$$,
array['owner.png'],
'the owner reads their own profile'
);
select results_eq(
$$update profiles set avatar_url = 'updated.png'
where user_id = '11111111-1111-1111-1111-111111111111'
returning avatar_url$$,
array['updated.png'],
'the owner updates their own profile'
);
-- A signed-in stranger holds the grant, so the policy is what stops them.
set local request.jwt.claim.sub = '22222222-2222-2222-2222-222222222222';
select throws_ok(
$$insert into profiles (id, user_id, avatar_url)
values (
gen_random_uuid(),
'11111111-1111-1111-1111-111111111111',
'stolen.png'
)$$,
'42501',
null,
'another user cannot create a profile for the owner'
);
select is_empty(
$$select * from profiles$$,
'another user reads no profiles'
);
select is_empty(
$$update profiles set avatar_url = 'stolen.png' returning avatar_url$$,
'another user updates no profiles'
);
-- Matching no rows is not proof on its own. Pair every denied write with a
-- check that the row it targeted is intact. Scope it to that row: a suite
-- that asserts on everything a role can see breaks once the table holds more.
set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';
select results_eq(
$$select avatar_url from profiles where user_id = '11111111-1111-1111-1111-111111111111'$$,
array['updated.png'],
'the denied update left the owner row intact'
);
set local request.jwt.claim.sub = '22222222-2222-2222-2222-222222222222';
select is_empty(
$$delete from profiles returning avatar_url$$,
'another user deletes no profiles'
);
set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';
select results_eq(
$$select avatar_url from profiles where user_id = '11111111-1111-1111-1111-111111111111'$$,
array['updated.png'],
'the denied delete left the owner row intact'
);
-- Owner delete last so earlier cases still have a row to assert against.
set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';
select results_eq(
$$delete from profiles where user_id = '11111111-1111-1111-1111-111111111111'
returning avatar_url$$,
array['updated.png'],
'the owner deletes their own profile'
);
select * from finish();
rollback;
```
Match the assertion to how the request is denied. Only two of the three raise an error:
| Denied by | Postgres | Assert with |
| -------------------------------------- | --------------------------------- | -------------------------------------------------------------------------------------------- |
| A missing grant | raises `42501` | `throws_ok` |
| A `with check` violation | raises `42501` | `throws_ok` |
| A `using` clause filtering the row out | raises nothing, matches zero rows | `is_empty` over the statement with `returning`, then a read proving the target row is intact |
Never prove an allowed write with `lives_ok`. It passes when the write matched zero rows. Add `returning` and assert the returned value.
Switch role and identity with `set local role` and `set local request.jwt.claim.sub`.
### Share rows between users
Some rows belong to two users at once, such as an order that both its buyer and its seller can see. Store each user in their own column, and check both columns in the same policy. The following examples use an `orders` table where each row has a `buyer_id` and a `seller_id`:
```sql
create table orders (
id bigint generated always as identity primary key,
buyer_id uuid not null references auth.users,
seller_id uuid not null references auth.users,
total numeric
);
alter table orders enable row level security;
revoke all on table orders from anon, authenticated;
grant select, update on table orders to authenticated;
```
The select policy lets either user read the order:
```sql
create policy "Buyers and sellers can view their orders."
on orders for select
to authenticated
using ( (select auth.uid()) in (buyer_id, seller_id) );
```
The update policy uses the same expression in `using` and `with check`, so either user can update the order, but the updated row must still include them as the buyer or the seller:
```sql
create policy "Buyers and sellers can update their orders."
on orders for update
to authenticated
using ( (select auth.uid()) in (buyer_id, seller_id) )
with check ( (select auth.uid()) in (buyer_id, seller_id) );
```
For `insert` and `delete`, check only the user who can create or remove the row, such as `with check ( (select auth.uid()) = buyer_id )` for a buyer placing an order. If either user could delete the row, one user could remove it for both.
This pattern needs no `security definer` function, because a plain policy can check both columns of the row. Use a security definer function when the check reads another table, as in [Use security definer functions](#use-security-definer-functions).
Index `buyer_id` and `seller_id` separately, because a policy that checks both columns needs an index on each. See [Add indexes](#add-indexes).
### Specify roles in your policies
Always name the role a policy applies to, using the `to` clause. Instead of this:
```sql
create policy "rls_test_select" on rls_test
using ( auth.uid() = user_id );
```
Use:
```sql
create policy "rls_test_select" on rls_test
to authenticated
using ( (select auth.uid()) = user_id );
```
A policy with no `to` clause applies to `public`, a role that every role is a member of, including `anon`. The first policy runs for every unauthenticated visitor and matches no rows for them. The second stops at the `to authenticated` step for `anon` requests, so `( (select auth.uid()) = user_id )` never runs for them. Naming the role doesn't make an unsafe condition, such as an `auth.uid() is null` branch, safe. See [`auth.uid()`](#authuid).
### Run the test suite
The files above live under `supabase/tests/` and run through [pgTAP](/docs/guides/database/extensions/pgtap). Create them with `supabase test new <table>_rls`, and run them with `supabase test db`.
For more information about writing a policy test and running it against your local database, see [Test Row Level Security policies with pgTAP](/docs/guides/database/postgres/testing-row-level-security).
[`supabase-test-helpers`](https://github.com/usebasejump/supabase-test-helpers/tree/main) adds `tests.create_supabase_user()`, `tests.authenticate_as()`, and `tests.rls_enabled()`. See [Advanced pgTAP testing](/docs/guides/local-development/testing/pgtap-extended) and [Testing your database](/docs/guides/database/testing).
### Add indexes
Add an [index](/docs/guides/database/postgres/indexes) on every column your policies filter on. Postgres evaluates the policy against each candidate row, so an unindexed filter column turns a read into a sequential scan. For a policy like this:
```sql
create policy "rls_test_select" on test_table
to authenticated
using ( (select auth.uid()) = user_id );
```
You can add an index like:
```sql
create index userid
on test_table
using btree (user_id);
```
A column counts as indexed only when it comes first in a `btree` index. Postgres can't use a multi-column index to filter on a column that isn't the leading one, so a composite primary key indexes its first column and no others. A membership table keyed on `(team_id, user_id)` has no index on `user_id`:
```sql
create table team_members (
team_id uuid references teams (id),
user_id uuid references auth.users (id),
primary key (team_id, user_id)
);
-- The primary key covers team_id. A policy filtering on user_id needs its own index.
create index team_members_user_id_idx
on team_members
using btree (user_id);
```
A policy can also filter on a fixed condition that doesn't depend on the user, such as a status or visibility flag. Postgres applies it like a `where` clause, so queries on the table can use a [partial index](/docs/guides/database/postgres/indexes#partial-indexes) with the same predicate. Index the columns your queries sort or filter on, and use the policy's condition as the index predicate. For a policy like this:
```sql
create policy "rls_test_select" on test_table
to authenticated
using ( not is_archived );
```
You can add a partial index like:
```sql
create index active_created_at
on test_table
using btree (created_at)
where not is_archived;
```
Write the policy condition and the index predicate the same way. Postgres matches only some equivalent forms, so a `using ( is_archived is false )` policy can't use this index.
### Call functions with `select`
You can use `select` statement to improve policies that use functions. For example, instead of this:
```sql
create policy "rls_test_select" on test_table
to authenticated
using ( auth.uid() = user_id );
```
You can do:
```sql
create policy "rls_test_select" on test_table
to authenticated
using ( (select auth.uid()) = user_id );
```
This method works well for JWT functions like `auth.uid()` and `auth.jwt()` as well as `security definer` Functions. Wrapping the function causes an `initPlan` to be run by the Postgres optimizer, which allows it to "cache" the results per-statement, rather than calling the function on each row.
<Admonition type="caution">
You can only use this technique if the results of the query or function do not change based on the row data.
</Admonition>
Indexing the filter columns and wrapping helper calls keeps policies fast as a table grows. For the measured impact, and for tuning beyond these two rules, see [Row Level Security performance](/docs/guides/database/postgres/row-level-security-performance).
### Expose a view safely
In Postgres 15 and above, make a view obey the RLS policies of its underlying tables when invoked by `anon` and `authenticated` by setting `security_invoker = true`.
```sql
create view <VIEW_NAME>
with(security_invoker = true)
as select <QUERY>
```
In older versions of Postgres, protect your views by revoking access from the `anon` and `authenticated` roles, or by putting them in an unexposed schema.
## RLS reference
These are the functions and patterns available inside a policy expression.
### Helper functions
Supabase provides some helper functions that make it easier to write policies.
#### `auth.uid()`
Returns the ID of the user making the request.
`auth.uid()` returns `null` for any request whose JWT has no `sub` claim. That includes every `anon` request. For such a request, `auth.uid() = user_id` is never true, so a policy that compares the column alone returns no rows.
<Admonition type="danger">
A policy condition with an `or auth.uid() is null` branch returns every row to any request without a user ID. Don't add the branch to let these requests through:
```sql
-- Insecure: every request without a user ID reads every row
create policy "rls_test_select" on rls_test
using ( auth.uid() is null or auth.uid() = user_id );
```
For such a request, the `is null` branch is true for every row, so the policy returns every row the role's grants reach. This policy has no `to` clause, so it also applies to `anon`, and every unauthenticated visitor reads the whole table.
Adding `to authenticated` keeps `anon` requests out. A request with an `authenticated` JWT that has no `sub`, such as one your own server signs, still gets every row. Drop the branch instead:
```sql
create policy "rls_test_select" on rls_test
to authenticated
using ( (select auth.uid()) = user_id );
```
</Admonition>
#### `auth.jwt()`
<Admonition type="caution">
Not all information present in the JWT should be used in RLS policies. For instance, creating an RLS policy that relies on the `user_metadata` claim can create security issues in your application as this information can be modified by authenticated end users.
</Admonition>
Returns the JWT of the user making the request. Anything that you store in the user's `raw_app_meta_data` column or the `raw_user_meta_data` column will be accessible using this function. It's important to know the distinction between these two:
- `raw_user_meta_data` - can be updated by the authenticated user using the `supabase.auth.update()` function. It is not a good place to store authorization data.
- `raw_app_meta_data` - cannot be updated by the user, so it's a good place to store authorization data.
To build role-based policies from custom claims, refer to [Custom claims and role-based access control (RBAC)](/docs/guides/api/custom-claims-and-role-based-access-control-rbac).
The `auth.jwt()` function is extremely versatile. For example, if you store some team data inside `app_metadata`, you can use it to determine whether a particular user belongs to a team. This example assumes `team_id` is a `uuid` and that `app_metadata.teams` is an array of UUID strings, for example `{"app_metadata": {"teams": ["22222222-2222-2222-2222-222222222222"]}}`. Each element is cast to `uuid`, so an array of objects needs a different expression. If your IDs use another type, cast the element to that type instead.
```sql
create policy "User is in team"
on my_table
to authenticated
using (
team_id = any (
array(
select (jsonb_array_elements_text((select auth.jwt()) -> 'app_metadata' -> 'teams'))::uuid
)
)
);
```
Comparing the values as `uuid` normalizes case and lets Postgres use an index on `team_id`.
<Admonition type="caution">
Keep in mind that a JWT is not always up-to-date. In the team policy example, even if you remove a user from a team and update the `app_metadata` field, that will not be reflected using `auth.jwt()` until the user's JWT is refreshed.
Also, if you are using Cookies for Auth, then you must be mindful of the JWT size. Some browsers are limited to 4096 bytes for each cookie, and so the total size of your JWT should be small enough to fit inside this limitation.
</Admonition>
#### MFA
The `auth.jwt()` function can be used to check for [Multi-Factor Authentication](/docs/guides/auth/auth-mfa#enforce-rules-for-mfa-logins). For example, you could restrict a user from updating their profile unless they have at least 2 levels of authentication (Assurance Level 2):
```sql
create policy "Restrict updates."
on profiles
as restrictive
for update
to authenticated using (
(select auth.jwt()->>'aal') = 'aal2'
);
```
### Use security definer functions
A "security definer" function runs using the same role that _created_ the function. This means that if you create a role with a superuser (like `postgres`), then that function will have `bypassrls` privileges. For example, if you had a policy like this:
```sql
create policy "rls_test_select" on test_table
to authenticated
using (
exists (
select 1 from roles_table
where (select auth.uid()) = user_id and role = 'good_role'
)
);
```
We can instead create a `security definer` function which can scan `roles_table` without any RLS penalties:
```sql
create function private.has_good_role()
returns boolean
language plpgsql
security definer -- will run as the creator
set search_path = '' -- every name inside must be schema-qualified
as $$
begin
return exists (
select 1 from public.roles_table
where (select auth.uid()) = user_id and role = 'good_role'
);
end;
$$;
-- Update our policy to use this function:
create policy "rls_test_select"
on test_table
to authenticated
using ( (select private.has_good_role()) );
```
Add member and non-member cases to that table's file under `supabase/tests/`. A member who is not the owner must be allowed; a non-member must not.
Set `search_path = ''` on every `security definer` function and schema-qualify the names inside it. Without a pinned `search_path`, a caller can point an unqualified name at their own object and run it with the function owner's privileges.
<Admonition type="caution">
A `security definer` function in an exposed schema is callable over the Data API with the creator's privileges. Never create one in a schema listed under "Exposed schemas" in your [API settings](/dashboard/project/_/settings/api).
</Admonition>
### Avoid recursive policies
Two tables whose policies read each other never resolve. Postgres raises `42P17`, `infinite recursion detected in policy for relation`, and the query fails for every role the policies apply to.
Sharing features produce this shape. A policy on `lists` checks `list_members` to find who the list is shared with, and a policy on `list_members` checks `lists` to find who owns it:
```sql
-- Reject: each policy reads the table the other one protects.
create policy "members read lists" on lists for select
to authenticated
using (
exists (
select 1 from list_members m
where m.list_id = lists.id and m.user_id = (select auth.uid())
)
);
create policy "members read membership" on list_members for select
to authenticated
using (
exists (
select 1 from lists l
where l.id = list_members.list_id and l.owner_id = (select auth.uid())
)
);
```
Break the cycle with a [security definer function](#use-security-definer-functions). It reads the membership table as its owner, so the second policy never runs and the cycle is broken:
```sql
create schema if not exists private;
create function private.user_list_ids()
returns setof uuid
language sql
security definer
set search_path = ''
stable
as $$
select list_id from public.list_members
where user_id = (select auth.uid())
$$;
revoke execute on function private.user_list_ids() from public;
grant usage on schema private to authenticated;
grant execute on function private.user_list_ids() to authenticated;
create policy "members read lists" on lists for select
to authenticated
using ( id in (select private.user_list_ids()) );
create policy "members read membership" on list_members for select
to authenticated
using ( list_id in (select private.user_list_ids()) );
```
The function filters on `(select auth.uid())`, so it returns only the caller's lists. A member who doesn't own the list still reads it, and a non-member reads nothing.
This works because the function runs as its owner, and a `security definer` function only skips RLS when its owner can. On Supabase the owner is `postgres`, which has `bypassrls`. A function owned by a role without `bypassrls`, or reading a table set to `force row level security`, evaluates the membership policy again and stays recursive.
### Bypassing Row Level Security
Use a [secret key](/docs/guides/getting-started/api-keys) for administrative tasks that need to bypass RLS. A secret key authorizes access through the `service_role` Postgres role, which has the `bypassrls` attribute. Never use a secret key in the browser or expose it to customers.
The JWT-based `service_role` key is a legacy alternative. Prefer a secret key where possible.
<Admonition type="note">
A secret key bypasses RLS only when the request carries no user access token. If the request carries one, it runs under the RLS policies of that signed-in user, even when the client library was [initialized with a secret key](/kb/troubleshooting/why-is-my-service-role-key-client-getting-rls-errors-or-not-returning-data-7_1K9z).
</Admonition>
You can also create new [Postgres Roles](/docs/guides/database/postgres/roles) which can bypass Row Level Security using the "bypass RLS" privilege:
```sql
alter role "role_name" with bypassrls;
```
This can be useful for system-level access. **Never** share login credentials for any Postgres Role with this privilege.
## Related content
- [Row Level Security performance](/docs/guides/database/postgres/row-level-security-performance): diagnose whether policies are your bottleneck, and tune ones that are already correct.
- [Advanced pgTAP testing](/docs/guides/local-development/testing/pgtap-extended): schema-wide RLS test helpers and a worked multi-tenant example.
- [Testing your database](/docs/guides/database/testing): the CLI test workflow that `supabase test db` runs.
- [Securing your API](/docs/guides/api/securing-your-api): grants, dedicated schemas, and pre-request checks around the Data API.
- [Column Level Security](/docs/guides/database/postgres/column-level-security): restrict access to individual columns.
- [`supabase-test-helpers`](https://github.com/usebasejump/supabase-test-helpers/tree/main): a community extension that adds user creation and role impersonation helpers to pgTAP.
- [Troubleshooting Row Level Security](/kb/troubleshooting/rls-performance-and-best-practices-Z5Jjwv)