Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

docs(database): restructure the RLS guide by information type (#49017)

Miranda Limonczenko6368f00ca0ee
diff --git a/apps/docs/content/guides/database/postgres/event-triggers.mdx b/apps/docs/content/guides/database/postgres/event-triggers.mdx
index 682b7d042a5..914fb27bbf3 100644
--- a/apps/docs/content/guides/database/postgres/event-triggers.mdx
+++ b/apps/docs/content/guides/database/postgres/event-triggers.mdx
@@ -55,7 +55,48 @@ EXECUTE FUNCTION dont_drop_function();
### Example trigger function - auto enable Row Level Security
-See how to [auto enable RLS for new tables](/docs/guides/database/postgres/row-level-security#auto-enable-rls-for-new-tables).
+If you want [Row Level Security](/docs/guides/database/postgres/row-level-security) enabled automatically for new tables, create an event trigger that runs after table creation and calls `ALTER TABLE ... ENABLE ROW LEVEL SECURITY` on each newly created table.
+
+```sql
+CREATE OR REPLACE FUNCTION rls_auto_enable()
+RETURNS EVENT_TRIGGER
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = pg_catalog
+AS $$
+DECLARE
+ cmd record;
+BEGIN
+ FOR cmd IN
+ SELECT *
+ FROM pg_event_trigger_ddl_commands()
+ WHERE command_tag IN ('CREATE TABLE', 'CREATE TABLE AS', 'SELECT INTO')
+ AND object_type IN ('table','partitioned table')
+ LOOP
+ IF cmd.schema_name IS NOT NULL AND cmd.schema_name IN ('public') AND cmd.schema_name NOT IN ('pg_catalog','information_schema') AND cmd.schema_name NOT LIKE 'pg_toast%' AND cmd.schema_name NOT LIKE 'pg_temp%' THEN
+ BEGIN
+ EXECUTE format('alter table if exists %s enable row level security', cmd.object_identity);
+ RAISE LOG 'rls_auto_enable: enabled RLS on %', cmd.object_identity;
+ EXCEPTION
+ WHEN OTHERS THEN
+ RAISE LOG 'rls_auto_enable: failed to enable RLS on %', cmd.object_identity;
+ RAISE;
+ END;
+ ELSE
+ RAISE LOG 'rls_auto_enable: skip % (either system schema or not in enforced list: %.)', cmd.object_identity, cmd.schema_name;
+ END IF;
+ END LOOP;
+END;
+$$;
+
+DROP EVENT TRIGGER IF EXISTS ensure_rls;
+CREATE EVENT TRIGGER ensure_rls
+ON ddl_command_end
+WHEN TAG IN ('CREATE TABLE', 'CREATE TABLE AS', 'SELECT INTO')
+EXECUTE FUNCTION rls_auto_enable();
+```
+
+Note that this applies to tables created after the trigger is installed. Existing tables still need RLS enabled manually.
### Event trigger Functions and firing events
diff --git a/apps/docs/content/guides/database/postgres/row-level-security-performance.mdx b/apps/docs/content/guides/database/postgres/row-level-security-performance.mdx
index af0a3d11c7e..37c124cc8c2 100644
--- a/apps/docs/content/guides/database/postgres/row-level-security-performance.mdx
+++ b/apps/docs/content/guides/database/postgres/row-level-security-performance.mdx
@@ -91,7 +91,7 @@ Policies are implicit `where` clauses, so it's common to run `select` statements
{/* prettier-ignore */}
```js
-const { data } = supabase
+const { data } = await supabase
.from('table')
.select()
```
@@ -100,7 +100,7 @@ Always add a filter:
{/* prettier-ignore */}
```js
-const { data } = supabase
+const { data } = await supabase
.from('table')
.select()
.eq('user_id', userId)
@@ -121,7 +121,7 @@ using (
(select auth.uid()) in (
select user_id
from team_user
- where team_user.team_id = team_id -- joins to the source "test_table.team_id"
+ where team_user.team_id = test_table.team_id -- joins to the source table
)
);
```
diff --git a/apps/docs/content/guides/database/postgres/row-level-security.mdx b/apps/docs/content/guides/database/postgres/row-level-security.mdx
index ea7fbf76114..d953048136f 100644
--- a/apps/docs/content/guides/database/postgres/row-level-security.mdx
+++ b/apps/docs/content/guides/database/postgres/row-level-security.mdx
@@ -7,47 +7,36 @@ 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.
-## Row Level Security in Supabase
-
<Admonition type="danger">
-A table in an exposed schema without RLS is readable and writable by anyone with your publishable key. RLS must always be enabled on any table stored in an exposed schema. By default, this is the `public` schema.
-
-RLS is enabled by default on tables created with the Table Editor in the dashboard. If you create a table in raw SQL or with the SQL editor, enable RLS yourself and leave each role only the privileges it needs:
-
-```sql
--- Take back the privileges granted automatically to client roles.
-revoke all on table <schema_name>.<table_name> from anon, authenticated;
-
--- Grant back only what each role needs.
-grant select on table <schema_name>.<table_name> to anon, authenticated;
-grant insert, update, delete on table <schema_name>.<table_name> to authenticated;
+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.
-alter table <schema_name>.<table_name>
-enable row level security;
-```
+</Admonition>
-Policies alone don't do this. See [Grants and policies](#grants-and-policies).
+Use the guide in three parts:
-</Admonition>
+- [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.
+- [RLS reference](#rls-reference) documents the helper functions and patterns you use inside a policy expression.
-You write RLS rules in SQL, so a rule can express whatever access logic your app needs. Combine RLS with [Supabase Auth](/docs/guides/auth) for end-to-end user security from the browser to the database.
+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.
-RLS is a Postgres primitive and can provide "[defense in depth](<https://en.wikipedia.org/wiki/Defense_in_depth_(computing)>)" to protect your data from malicious actors even when accessed through third-party tooling.
+## Understand Row Level Security
-## Policies
+### 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. For example, a policy like this:
+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 tries to select from the todos table:
+That policy translates to this whenever a user selects from the todos table:
```sql
select *
@@ -56,17 +45,9 @@ where auth.uid() = todos.user_id;
-- Policy is implicitly added.
```
-## Enabling Row Level Security
-
-You can enable RLS for any table using the `enable row level security` clause:
-
-```sql
-alter table "table_name" enable row level security;
-```
-
-Once you have enabled RLS, no data will be accessible via the [API](/docs/guides/api) when using a publishable key, until you create policies.
+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
+### 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.
@@ -80,111 +61,11 @@ On existing projects, a new table in `public` starts with every privilege alread
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.
-A missing grant 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.
-
-### Set the grants for a table
-
-Run these statements in the [SQL Editor](/dashboard/project/_/sql/new) for a one-off change, or in a [migration](/docs/guides/deployment/database-migrations) to keep the change reproducible across environments. Grants and RLS belong in the same migration.
-
-Set the grants to match what each role does in your app:
-
-1. Revoke the automatic grants from both client roles.
-
- ```sql
- revoke all on table public.reports from anon, authenticated;
- ```
-
-2. 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;
- ```
-
-3. Enable RLS on the table and write policies that decide which rows each role reaches.
-
-For data that clients read but never write, such as a feed a backend job populates, grant no writes in step 2:
-
-```sql
-revoke all on table public.weather_readings from anon, authenticated;
-grant select on table public.weather_readings to anon, authenticated;
-```
-
-To stop new tables from receiving the automatic grants in the first place, see [Revoke default privileges](/docs/guides/api/securing-your-api#revoke-default-privileges).
-
-Write the tests for this table in the same change. See [Test your policies](#test-your-policies).
-
-## Auto-enable RLS for new tables
-
-If you want RLS enabled automatically for new tables, you can create an event trigger that runs after table creation. This uses a Postgres [event trigger](/docs/guides/database/postgres/event-triggers) to call `ALTER TABLE ... ENABLE ROW LEVEL SECURITY` on each newly created table.
-
-```sql
-CREATE OR REPLACE FUNCTION rls_auto_enable()
-RETURNS EVENT_TRIGGER
-LANGUAGE plpgsql
-SECURITY DEFINER
-SET search_path = pg_catalog
-AS $$
-DECLARE
- cmd record;
-BEGIN
- FOR cmd IN
- SELECT *
- FROM pg_event_trigger_ddl_commands()
- WHERE command_tag IN ('CREATE TABLE', 'CREATE TABLE AS', 'SELECT INTO')
- AND object_type IN ('table','partitioned table')
- LOOP
- IF cmd.schema_name IS NOT NULL AND cmd.schema_name IN ('public') AND cmd.schema_name NOT IN ('pg_catalog','information_schema') AND cmd.schema_name NOT LIKE 'pg_toast%' AND cmd.schema_name NOT LIKE 'pg_temp%' THEN
- BEGIN
- EXECUTE format('alter table if exists %s enable row level security', cmd.object_identity);
- RAISE LOG 'rls_auto_enable: enabled RLS on %', cmd.object_identity;
- EXCEPTION
- WHEN OTHERS THEN
- RAISE LOG 'rls_auto_enable: failed to enable RLS on %', cmd.object_identity;
- END;
- ELSE
- RAISE LOG 'rls_auto_enable: skip % (either system schema or not in enforced list: %.)', cmd.object_identity, cmd.schema_name;
- END IF;
- END LOOP;
-END;
-$$;
-
-DROP EVENT TRIGGER IF EXISTS ensure_rls;
-CREATE EVENT TRIGGER ensure_rls
-ON ddl_command_end
-WHEN TAG IN ('CREATE TABLE', 'CREATE TABLE AS', 'SELECT INTO')
-EXECUTE FUNCTION rls_auto_enable();
-```
-
-Note that this applies to tables created after the trigger is installed. Existing tables still need RLS enabled manually.
-
-<Admonition type="caution" title="`auth.uid()` Returns `null` When Unauthenticated">
-
-When a request is made without an authenticated user (e.g., no access token is provided or the session has expired), `auth.uid()` returns `null`.
-
-This means that a policy like:
-
-```sql
-USING (auth.uid() = user_id)
-```
-
-will silently fail for unauthenticated users, because:
-
-```sql
-null = user_id
-```
-
-is always false in SQL.
-
-To avoid confusion and make your intention clear, we recommend explicitly checking for authentication:
-
-```sql
-USING (auth.uid() IS NOT NULL AND auth.uid() = user_id)
-```
+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.
-</Admonition>
+A missing grant 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 [Lock down the table](#lock-down-the-table).
-## Authenticated and unauthenticated roles
+### Authenticated and unauthenticated roles
Supabase maps every request to one of the roles:
@@ -213,99 +94,110 @@ Using the `anon` Postgres role is different from an [anonymous user](/docs/guide
</Admonition>
-## Creating policies
+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.
-Policies are SQL logic that you attach to a Postgres table. You can attach as many policies as you want to each table.
+### Views and RLS
-Supabase provides some [helpers](#helper-functions) that simplify RLS if you're using Supabase Auth. The examples below use these helpers.
+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).
-### SELECT policies
+## Secure a table with RLS
-You can specify select policies with the `using` clause.
+Follow these steps for every table in an exposed schema.
-Say you have a table called `profiles` in the public schema and you want to enable read access to everyone.
+### Lock down the table
-```sql
--- 1. Create table
-create table profiles (
- id uuid primary key,
- user_id uuid references auth.users,
- avatar_url text
-);
+Run these statements in the [SQL Editor](/dashboard/project/_/sql/new) for a one-off change, or in a [migration](/docs/guides/deployment/database-migrations) to keep the change reproducible across environments. Grants and RLS belong in the same migration.
--- 2. Enable RLS
-alter table profiles enable row level security;
+Enable RLS, then set the grants to match what each role does in your app:
--- 3. Create Policy
-create policy "Public profiles are visible to everyone."
-on profiles for select
-to anon -- the Postgres Role (recommended)
-using ( true ); -- the actual Policy
-```
+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.
-Alternatively, if you only wanted users to be able to see their own profiles:
+ ```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;
+ ```
+
+Data that clients read but never write, such as a feed a backend job populates, gets no write grant at all:
```sql
-create policy "User can see their own profile only."
-on profiles for select
-to authenticated
-using ( (select auth.uid()) = user_id );
+revoke all on table public.weather_readings from anon, authenticated;
+grant select on table public.weather_readings to anon, authenticated;
```
-### INSERT policies
+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 the tests for this table in the same change. See [Test your policies](#test-your-policies).
-You can specify insert policies with the `with check` clause. The `with check` expression ensures that any new row data adheres to the policy constraints.
+### Write a policy for each operation
-Say you have a table called `profiles` in the public schema and you only want users to create a profile for themselves. In that case, check that their user ID matches the value they are trying to insert:
+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
--- 1. Create table
create table profiles (
id uuid primary key,
user_id uuid references auth.users,
avatar_url text
);
--- 2. Enable RLS
alter table profiles enable row level security;
--- 3. Create Policy
-create policy "Users can create a profile."
-on profiles for insert
-to authenticated -- the Postgres Role (recommended)
-with check ( (select auth.uid()) = user_id ); -- the actual Policy
+revoke all on table profiles from anon, authenticated;
+grant select, insert, update, delete on table profiles to authenticated;
```
-### UPDATE policies
+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.
-You can specify update policies by combining both the `using` and `with check` expressions.
+#### SELECT policies
-The `using` clause represents the condition that must be true for the update to be allowed, and `with check` clause ensures that the updates made adhere to the policy constraints.
+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 );
+```
-Say you have a table called `profiles` in the public schema and you only want users to update their own profile.
+#### INSERT policies
-You can create a policy where the `using` clause checks if the user owns the profile being updated. And the `with check` clause ensures that, in the resultant row, users do not change the `user_id` to a value that is not equal to their User ID, maintaining that the modified profile still meets the ownership condition.
+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
--- 1. Create table
-create table profiles (
- id uuid primary key,
- user_id uuid references auth.users,
- avatar_url text
-);
+create policy "Users can create their own profile."
+on profiles for insert
+to authenticated
+with check ( (select auth.uid()) = user_id );
+```
--- 2. Enable RLS
-alter table profiles enable row level security;
+#### 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.
--- 3. Create Policy
+```sql
create policy "Users can update their own profile."
on profiles for update
-to authenticated -- the Postgres Role (recommended)
-using ( (select auth.uid()) = user_id ) -- checks if the existing row complies with the policy expression
-with check ( (select auth.uid()) = user_id ); -- checks if the new row complies with the policy expression
+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, then the `using` expression will be used both to determine which rows are visible (normal USING case) and which new rows will be allowed to be added (WITH CHECK case).
+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">
@@ -313,115 +205,110 @@ To perform an `UPDATE` operation, a corresponding [`SELECT` policy](#select-poli
</Admonition>
-### DELETE policies
+#### DELETE policies
You can specify delete policies with the `using` clause.
-Say you have a table called `profiles` in the public schema and you only want users to be able to delete their own profile:
-
```sql
--- 1. Create table
-create table profiles (
- id uuid primary key,
- user_id uuid references auth.users,
- avatar_url text
-);
-
--- 2. Enable RLS
-alter table profiles enable row level security;
-
--- 3. Create Policy
-create policy "Users can delete a profile."
+create policy "Users can delete their own profile."
on profiles for delete
-to authenticated -- the Postgres Role (recommended)
-using ( (select auth.uid()) = user_id ); -- the actual Policy
+to authenticated
+using ( (select auth.uid()) = user_id );
```
-### Views
+### Specify roles in your policies
-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`.
+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 );
+```
-In Postgres 15 and above, you can make a view obey the RLS policies of the underlying tables when invoked by `anon` and `authenticated` roles by setting `security_invoker = true`.
+Use:
```sql
-create view <VIEW_NAME>
-with(security_invoker = true)
-as select <QUERY>
+create policy "rls_test_select" on rls_test
+to authenticated
+using ( (select auth.uid()) = user_id );
```
-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.
+This prevents the policy `( (select auth.uid()) = user_id )` from running for any `anon` users, since the execution stops at the `to authenticated` step.
-## Helper functions
+These three rules keep policies correct as a table grows. For the measured impact and for tuning beyond them, see [Row Level Security performance](/docs/guides/database/postgres/row-level-security-performance).
-Supabase provides some helper functions that make it easier to write Policies.
+### Add indexes
-### `auth.uid()`
+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:
-Returns the ID of the user making the request.
+```sql
+create policy "rls_test_select" on test_table
+to authenticated
+using ( (select auth.uid()) = user_id );
+```
-### `auth.jwt()`
+You can add an index like:
-<Admonition type="caution">
+```sql
+create index userid
+on test_table
+using btree (user_id);
+```
-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.
+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`:
-</Admonition>
+```sql
+create table team_members (
+ team_id uuid references teams (id),
+ user_id uuid references auth.users (id),
+ primary key (team_id, user_id)
+);
-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:
+-- 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);
+```
-- `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.
+### Call functions with `select`
-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. For example, if this was an array of IDs:
+You can use `select` statement to improve policies that use functions. For example, instead of this:
```sql
-create policy "User is in team"
-on my_table
+create policy "rls_test_select" on test_table
to authenticated
-using ( team_id in (select auth.jwt() -> 'app_metadata' -> 'teams'));
+using ( auth.uid() = user_id );
```
-<Admonition type="caution">
-
-Keep in mind that a JWT is not always "fresh". In the example above, 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):
+You can do:
```sql
-create policy "Restrict updates."
-on profiles
-as restrictive
-for update
-to authenticated using (
- (select auth.jwt()->>'aal') = 'aal2'
-);
+create policy "rls_test_select" on test_table
+to authenticated
+using ( (select auth.uid()) = user_id );
```
-## Bypassing Row Level Security
-
-Supabase provides special "Service" keys, which can be used to bypass RLS. These should never be used in the browser or exposed to customers, but they are useful for administrative tasks.
+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="note">
+<Admonition type="caution">
-A Service 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 Service Key.
+You can only use this technique if the results of the query or function do not change based on the row data.
</Admonition>
-You can also create new [Postgres Roles](/docs/guides/database/postgres/roles) which can bypass Row Level Security using the "bypass RLS" privilege:
+### 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
-alter role "role_name" with bypassrls;
+create view <VIEW_NAME>
+with(security_invoker = true)
+as select <QUERY>
```
-This can be useful for system-level access. **Never** share login credentials for any Postgres Role with this privilege.
+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.
-## Test your policies
+### Test your policies
We recommend writing tests for every policy, in the same change that sets the grants and creates the policies. Tests are a fundamental part of a secure setup, and they give you a repeatable way to prove a policy behaves the way you intended.
@@ -429,7 +316,7 @@ A wrong policy fails quietly. Too permissive, and a query returns rows it should
Supabase runs database tests with [pgTAP](/docs/guides/database/extensions/pgtap) through the CLI. Test files are `.sql` files under `supabase/tests/`.
-### Anatomy of a policy test
+#### Anatomy of a policy test
Each case sets an identity, runs one statement as that identity, and asserts the outcome. Three things decide whether the assertion means anything.
@@ -443,16 +330,17 @@ Each case sets an identity, runs one statement as that identity, and asserts the
**Allowed writes.** The absence of an error doesn't prove that anything changed. Add `returning` to the statement so one assertion covers both directions. An allowed write returns the changed row, and a write the policy filters out returns nothing.
-### Write and run the tests
+#### Write and run the tests
-1. Create the tests directory and a test file:
+1. Create a test file:
```bash
- mkdir -p supabase/tests
- touch supabase/tests/profiles_rls.test.sql
+ supabase test new profiles_rls
```
-2. Write the tests. Cover `select`, `insert`, `update`, and `delete` twice each, once for a request the policy allows and once for a request it denies. Cover `anon` as well as `authenticated`.
+2. Write the tests. Cover `select`, `insert`, `update`, and `delete` twice each, once for a request the policy allows and once for a request it denies, for `anon` as well as `authenticated`.
+
+ [`supabase-test-helpers`](https://github.com/usebasejump/supabase-test-helpers/tree/main) removes most of the setup below. It adds `tests.create_supabase_user()`, `tests.authenticate_as()`, and `tests.rls_enabled()`, so you don't hand-roll user seeding or role switching. See [Advanced pgTAP testing](/docs/guides/local-development/testing/pgtap-extended) for schema-wide assertions and a worked multi-tenant example.
3. Run the suite:
@@ -460,19 +348,18 @@ Each case sets an identity, runs one statement as that identity, and asserts the
supabase test db
```
-This example tests a `profiles` table where `authenticated` holds every privilege, `anon` holds none, and each user reads and writes only their own row:
+This example shows each of those techniques against a `profiles` table where `authenticated` holds every privilege, `anon` holds none, and each user reads and writes only their own row. Extend it to the remaining operations:
```sql supabase/tests/profiles_rls.test.sql
begin;
-select plan(11);
+select plan(4);
--- Seed two users. The rows come later, through the policies under test.
insert into auth.users (id, email)
values
('11111111-1111-1111-1111-111111111111', '[email protected]'),
('22222222-2222-2222-2222-222222222222', '[email protected]');
--- Signed-out visitors hold no grant, so the request stops before any policy runs.
+-- anon holds no grant, so the request stops before any policy runs.
set local role anon;
select throws_ok(
$$select * from profiles$$,
@@ -480,15 +367,8 @@ select throws_ok(
null,
'anon cannot read profiles'
);
-select throws_ok(
- $$insert into profiles (id, user_id)
- values (gen_random_uuid(), '11111111-1111-1111-1111-111111111111')$$,
- '42501',
- null,
- 'anon cannot insert a profile'
-);
--- The owner reads and writes their own row.
+-- 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(
@@ -502,25 +382,6 @@ select results_eq(
array['owner.png'],
'the owner creates their own profile'
);
-select results_eq(
- $$select avatar_url from profiles$$,
- array['owner.png'],
- 'the owner reads their own profile'
-);
-select results_eq(
- $$update profiles set avatar_url = 'updated.png' returning avatar_url$$,
- array['updated.png'],
- 'the owner updates their own profile'
-);
-
--- The with check clause rejects the row, which raises.
-select throws_ok(
- $$insert into profiles (id, user_id)
- values (gen_random_uuid(), '22222222-2222-2222-2222-222222222222')$$,
- '42501',
- null,
- 'the owner cannot create a profile for someone else'
-);
-- A signed-in stranger holds the grant, so the policy is what stops them. The
-- using clause filters the row out, so these match nothing and raise nothing.
@@ -533,23 +394,6 @@ select is_empty(
$$update profiles set avatar_url = 'stolen.png' returning avatar_url$$,
'another user updates no profiles'
);
-select is_empty(
- $$delete from profiles returning id$$,
- 'another user deletes no profiles'
-);
-
--- The row is still there, still holding the owner's value.
-set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';
-select results_eq(
- $$select avatar_url from profiles$$,
- array['updated.png'],
- 'the other user changed nothing'
-);
-select results_eq(
- $$delete from profiles returning avatar_url$$,
- array['updated.png'],
- 'the owner deletes their own profile'
-);
select * from finish();
rollback;
@@ -557,89 +401,87 @@ rollback;
For CLI setup and more pgTAP helpers, see [Testing your database](/docs/guides/database/testing).
-## Write policies that scale
+## RLS reference
-Postgres evaluates a policy expression against each candidate row, so the cost scales with the rows a query scans. Three rules keep that cost from growing with your table. Apply all three to every policy you write.
+These are the functions and patterns available inside a policy expression.
-### Add indexes
+### Helper functions
-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:
+Supabase provides some helper functions that make it easier to write policies.
-```sql
-create policy "rls_test_select" on test_table
-to authenticated
-using ( (select auth.uid()) = user_id );
-```
+#### `auth.uid()`
-You can add an index like:
+Returns the ID of the user making the request.
-```sql
-create index userid
-on test_table
-using btree (user_id);
-```
+<Admonition type="caution" title="`auth.uid()` Returns `null` When Unauthenticated">
-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`:
+When a request is made without an authenticated user (e.g., no access token is provided or the session has expired), `auth.uid()` returns `null`.
-```sql
-create table team_members (
- team_id uuid references teams (id),
- user_id uuid references auth.users (id),
- primary key (team_id, user_id)
-);
+This means that a policy like:
--- 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);
+```sql
+USING (auth.uid() = user_id)
```
-### Call functions with `select`
-
-You can use `select` statement to improve policies that use functions. For example, instead of this:
+will silently fail for unauthenticated users, because:
```sql
-create policy "rls_test_select" on test_table
-to authenticated
-using ( auth.uid() = user_id );
+null = user_id
```
-You can do:
+is always false in SQL.
+
+To avoid confusion and make your intention clear, we recommend explicitly checking for authentication:
```sql
-create policy "rls_test_select" on test_table
-to authenticated
-using ( (select auth.uid()) = user_id );
+USING (auth.uid() IS NOT NULL AND 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>
+
+#### `auth.jwt()`
<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.
+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>
-### Specify roles in your policies
-
-Always name the role a policy applies to, using the `to` clause. Instead of this:
+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:
-```sql
-create policy "rls_test_select" on rls_test
-using ( auth.uid() = user_id );
-```
+- `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.
-Use:
+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. For example, if this was an array of IDs:
```sql
-create policy "rls_test_select" on rls_test
+create policy "User is in team"
+on my_table
to authenticated
-using ( (select auth.uid()) = user_id );
+using ( team_id in (select auth.jwt() -> 'app_metadata' -> 'teams'));
```
-This prevents the policy `( (select auth.uid()) = user_id )` from running for any `anon` users, since the execution stops at the `to authenticated` step.
+<Admonition type="caution">
-These three rules keep policies correct as a table grows. To diagnose whether a policy is still the bottleneck, and to tune beyond these rules, see [Row Level Security performance](/docs/guides/database/postgres/row-level-security-performance).
+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
@@ -688,6 +530,26 @@ A `security definer` function in an exposed schema is callable over the Data API
</Admonition>
+### 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.
+
+</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.
diff --git a/apps/docs/content/troubleshooting/interpreting-supabase-grafana-io-charts-MUynDR.mdx b/apps/docs/content/troubleshooting/interpreting-supabase-grafana-io-charts-MUynDR.mdx
index 9efe9c4793d..3b93646ebe2 100644
--- a/apps/docs/content/troubleshooting/interpreting-supabase-grafana-io-charts-MUynDR.mdx
+++ b/apps/docs/content/troubleshooting/interpreting-supabase-grafana-io-charts-MUynDR.mdx
@@ -42,7 +42,7 @@ Excessive IO usage is highly problematic as it clarifies that your database is e
- **Excessive and needless sequential scans:** poorly indexed tables force requests to scan disk ([guide to resolve](https://github.com/orgs/supabase/discussions/22449))
- **Too little cache**: There is not enough memory, so instead of reading data from the memory cache, it is accessed from disk ([guide to inspect](https://github.com/orgs/supabase/discussions/22449))
-- **Poorly optimized RLS policies**: RLS that rely heavily on joins are more likely to hit disk. If possible, they should optimized ([RLS performance guide](/docs/guides/database/postgres/row-level-security-performance))
+- **Poorly optimized RLS policies**: RLS that rely heavily on joins are more likely to hit disk. If possible, they should be optimized ([RLS performance guide](/docs/guides/database/postgres/row-level-security-performance))
- **Excessive bloat**: This is the least likely to cause major issues, but bloat can take up space, preventing data on disk from being placed in the same locality. This can force the database to scan more pages than necessary. ([explainer guide](/blog/postgres-bloat))
- **Uploading high amounts of data:** temporarily increase compute add-on size for the duration of the uploads
- **Insufficient memory**: Sometimes an inadequate amount of memory forces queries to hit disk instead of the memory cache. Address memory issues ([guide](https://github.com/orgs/supabase/discussions/27021)) can reduce disk strain.