The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
cleans up the Auth section of RLS
Copple1d8fdb78980c
diff --git a/apps/docs/pages/guides/auth/row-level-security.mdx b/apps/docs/pages/guides/auth/row-level-security.mdxindex 2a3ba432e24..14ca6564dcc 100644--- a/apps/docs/pages/guides/auth/row-level-security.mdx+++ b/apps/docs/pages/guides/auth/row-level-security.mdx@@ -8,9 +8,9 @@ export const meta = {tocVideo: 'Ow_Uzedfohk',}-When you need granular authorization rules, nothing beats PostgreSQL's [Row Level Security (RLS)](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).+Supabase Auth is designed to work perfectly with [Postgres Row Level Security](/docs/guides/database/postgres/row-level-security) (RLS).-[Policies](https://www.postgresql.org/docs/current/sql-createpolicy.html) are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs.+You can use RLS to create [Policies](https://www.postgresql.org/docs/current/sql-createpolicy.html) that are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs.<div className="video-container"><iframe@@ -28,8 +28,8 @@ You can just think of them as adding a `WHERE` clause to every query. For exampl```sqlcreate policy "Individuals can view their own todos."- on todos for select- using ( auth.uid() = user_id );+on todos for select+using ( auth.uid() = user_id );```.. would translate to this whenever a user tries to select from the todos table:@@ -40,66 +40,151 @@ from todoswhere auth.uid() = todos.user_id; -- Policy is implicitly added.```+## Authenticated and anonymous roles++Supabase Auth maps every request to either of these roles:++- `anon`: an anonymous request (the user is not logged in)+- `authenticated`: an authenticated request (the user is logged in)++These are actually [Postgres Roles](/docs/guides/database/postgres/roles), and so they have significant value for the [performance](/docs/guides/database/postgres/row-level-security#specify-roles-in-your-policies) of your RLS Policies. You can use these roles within your Policies using the `TO` parameter:++```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 );+```++## Helper Functions-Supabase provides you with a few easy functions that you can use with your policies.+Supabase provides some helper functions that make it easier to write Policies.### `auth.uid()`-Returns the ID of the user making the request.+Returns the ID of the user making the request.### `auth.jwt()`-Returns the JWT of the user making the request.+Returns the JWT of the user making the request. Anything that you store in the user's `app_metadata` column or the `user_metadata` column will be accessible using this function. Be careful not to store too much data in both of these fields, becuase some browsers have a limitation of 4096 bytes for cookies.++It's important to know the distinciton between these two:++- `user_metadata` - can be updated by the authenticated user using the `supabase.auth.update()` function. It is not a good place to store authorization data.+- `app_metadata` - cannot be updated by the user, so it's a good place to store authorization data.++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:-## Examples+```sql+create policy "User is in team"+on my_table+to authenticated+using ( team_id in (select auth.jwt() -> 'app_metadata' -> 'teams'));+```-Here are some examples to show you the power of PostgreSQL's RLS.+{/* prettier-ignore */}+<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>-### Restrict updates+## Important considerations++We recommend reading the [Row Level Security](/docs/guides/database/postgres/row-level-security) guide in the database section to learn more about Postgres RLS. When using Postgres on Supabase there are some important things to keep in mind to maintain data security.++### Never use a service key on the client++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.++<Admonition type="note">+Initializing a client with a Service Key will not override RLS if a user token is set. If a user is signed in with a client, Supabase will adhere to the RLS policy of the user.+</Admonition>++### Always enable RLS on public tables++You should _always_ enable RLS on tables created in a public schemas. This is considered "default safe". Unfortunately this is not enabled by default on Postgres, so you will need to keep this in mind - especially if you are using the SQL Editor or database migrations. RLS is already enabled by default if you create a table using the Table Editor. If you want to allow public access to a table, just add a Policy with `true`:```sql--- 1. Create table-create table profiles (- id uuid references auth.users,- avatar_url text+create policy "Allow public access"+on my_table for select+using ( true );+```++### Using external authorization systems++If you want to use another authorization method for your applications that's also fine. Supabase is "just Postgres", so if your application works with Postgres, then it also works with Supabase. If you take this path, don't put your tables in the `public` schema - instead create a new schema for your tables and functions:++```sql+create schema private;++create table private.employees (+ id serial primary key,+ name text);+```--- 2. Enable RLS-alter table profiles- enable row level security;+If you do put anything in the `public` schema, make sure to enable RLS (you don't need to add any policies):--- 3. Create Policy-create policy "Users can update their own profiles."- on profiles for update using (- auth.uid() = id- );+```sql+create table profiles (+ id serial primary key,+ email text+);++alter table profiles enable row level security;```-1. Creates a table called `profiles` in the public schema (default schema).-2. Enables RLS.-3. Creates a policy which allows logged in users to update their own data.+This makes the tables inaccessible via the [Serverless APIs](/docs/guides/api).+-**Note:** If you want to use upsert operations, the user needs to have `INSERT`, `UPDATE`, and `SELECT` permissions.+## Usage-### Only anon or authenticated access+Row Level Security is extremely versatile, since it simply uses SQL to express access rules for your data.-You can add a Postgres role+### Using functions++You can use any Postgres function inside a Policy. The [Helper Functions](#helper-functions) above are simply Postgres functions we've made available in the `auth` schema. This is an example which:++1. Creates a table called `profiles` in the public schema (default schema).+2. Enables RLS.+3. Creates a policy which allows logged in users to update their own data, using the `auth.uid()` function.```sql-create policy "Public profiles are viewable by everyone."-on profiles for select-to authenticated, anon+-- 1. Create table+create table profiles (+ 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 update their own profiles"+on profiles for update+to authenticatedusing (- true+ auth.uid() = id);```-### Policies with joins+**Note:** If you want to use [upsert](/docs/reference/javascript/upsert) operations, the user needs to have `INSERT`, `UPDATE`, and `SELECT` permissions.++### Using joins-Policies can even include table joins. This example shows how you can query "external" tables to build more advanced rules.+Policies can include table joins. This example shows how you can query "external" tables to build more advanced rules.```sql+-- 1. Create a table of teamscreate table teams (id serial primary key,name text@@ -112,11 +197,10 @@ create table members ();-- 3. Enable RLS-alter table teams- enable row level security;+alter table teams enable row level security;-- 4. Create Policy-create policy "Team members can update team details if they belong to the team."+create policy "Team members can update team details if they belong to the team"on teamsfor update using (auth.uid() in (@@ -126,275 +210,67 @@ create policy "Team members can update team details if they belong to the team.");```-**Note:** If RLS is also enabled for _members_, the user must also have read (_select_) access to _members_. Otherwise the joined query will not yield any results.+An important note here: if RLS is also enabled for `members`, the user must also have read (`select`) access to members. Otherwise the joined query will not yield any results. Another alternative is to use a "security definer" function which is created by a user with [bypassrls](/docs/guides/database/postgres/row-level-security#specify-roles-in-your-policies) priveleges.-### Policies with security definer functions+### Using security definer functions-Policies can also make use of `security definer functions`. This is useful in a many-to-many relationship where you want to restrict access to the linking table. Following the `teams` and `members` example from above, this example shows how you can use the security definer function in combination with a policy to control access to the `members` table.+You can use `security definer` functions inside Policies. This is useful in a many-to-many relationships, and [important for performance](/docs/guides/database/postgres/row-level-security#use-security-definer-functions). Following the `teams` and `members` example from above, this example shows how you can use the security definer function in combination with a policy to control access to the `members` table.```sql--- 1. Follow example for 'Policies with joins' above+-- 1. Create a table of teams+create table teams (+ id serial primary key,+ name text+);++-- 2. Create many to many join+create table members (+ team_id bigint references teams,+ user_id uuid references auth.users+);-- 2. Enable RLS-alter table members- enable row level security+alter table teams enable row level security;+alter table members enable row level security--- 3. Create security definer function-create or replace function get_teams_for_authenticated_user()+-- 3. Create security definer function, which should be run as "postgres"+create function private.get_teams_for_authenticated_user()returns setof bigintlanguage sqlsecurity definerset search_path = publicstableas $$- select team_id- from members- where user_id = auth.uid()+ select team_id+ from members+ where user_id = auth.uid()$$;-- 4. Create Policycreate policy "Team members can update team members if they belong to the team."- on members- for all using (- team_id in (- select get_teams_for_authenticated_user()- )- );--```--### Verifying email domains--Postgres has a function `right(string, n)` that returns the rightmost n characters of a string.-You could use this to match staff member's email domains.--```sql--- 1. Create table-create table leaderboard (- id uuid references auth.users,- high_score bigint-);---- 2. Enable RLS-alter table leaderboard- enable row level security;---- 3. Create Policy-create policy "Only Blizzard staff can update leaderboard"- on leaderboard- for update using (- right(auth.jwt() ->> 'email', 13) = '@blizzard.com'- );-```--### Advanced policies--Use the full power of SQL to build extremely advanced rules.--In this example, we will create a `posts` and `comments` tables and then create a policy that depends on another policy.-(In this case, the comments policy depends on the posts policy.)--```sql-create table posts (- id serial primary key,- creator_id uuid not null references auth.users(id),- title text not null,- body text not null,- publish_date date not null default now(),- audience uuid[] null -- many to many table omitted for brevity-);--create table comments (- id serial primary key,- post_id int not null references posts(id) on delete cascade,- user_id uuid not null references auth.users(id),- body text not null,- comment_date date not null default now()-);--create policy "Creator can see their own posts"-on posts-for select-using (- auth.uid() = posts.creator_id-);--create policy "Logged in users can see the posts if they belong to the post 'audience'."-on posts-for select-using (- auth.uid() = any (posts.audience)-);--create policy "Users can see all comments for posts they have access to."-on comments-for select-using (- exists (- select 1 from posts- where posts.id = comments.post_id+on members+for all using (+ team_id in (+ select private.get_teams_for_authenticated_user()));```-## Using external authorization systems--If you want to use another authorization method for your applications that's also fine. Supabase is "just Postgres", so if your application works with Postgres, then it also works with Supabase. If you take this path, don't put your tables in the `public` schema - instead create a new schema for your tables and functions:--```sql-create schema private;+### Using built-in functions-create table private.employees (- id serial primary key,- name text-);-```+Postgres has a number of built-in functions. Most commonly you'll use `in()` and `any()` which will match a column's value to a list of values.-If you do put anything in the `public` schema, make sure to enable RLS (you don't need to add any policies):+You can use any Postgres functions inside Policies. For example, we can use the `right(string, n)` function to match email domains:```sql-create table profiles (- id serial primary key,- email text+create policy "Only Supabase staff can update the leaderboard"+on leaderboard+to authenticated+for update using (+ right(auth.jwt() ->> 'email', 13) = '@supabase.com');--alter table profiles enable row level security;-```--This makes the tables inaccessible via the [Serverless APIs](/docs/guides/api).---### Never use a service key on the client--Supabase provides special "Service" keys, which can be used to bypass all RLS.-These should never be used in the browser or exposed to customers, but they are useful for administrative tasks.-<Admonition type="caution">-Initializing a client with a Service Key will not override RLS if a user token is set. If a user is signed in with a client, Supabase will adhere to the RLS policy of the user.-</Admonition>--### Testing policies--To test policies on the database itself (i.e., from the [SQL Editor](https://supabase.com/dashboard/project/_/sql) or from `psql`) without switching to your frontend and logging in as different users, you can utilize the following helper SQL procedures ([credits](https://github.com/supabase/supabase/issues/7311#issuecomment-1398648114)):--```sql-grant anon, authenticated to postgres;--create or replace procedure auth.login_as_user (user_email text)- language plpgsql- as $$-declare- auth_user auth.users;-begin- select- * into auth_user- from- auth.users- where- email = user_email;- execute format('set request.jwt.claim.sub=%L', (auth_user).id::text);- execute format('set request.jwt.claim.role=%I', (auth_user).role);- execute format('set request.jwt.claim.email=%L', (auth_user).email);- execute format('set request.jwt.claims=%L', json_strip_nulls(json_build_object('app_metadata', (auth_user).raw_app_meta_data))::text);-- raise notice '%', format( 'set role %I; -- logging in as %L (%L)', (auth_user).role, (auth_user).id, (auth_user).email);- execute format('set role %I', (auth_user).role);-end;-$$;--create or replace procedure auth.login_as_anon ()- language plpgsql- as $$-begin- set request.jwt.claim.sub='';- set request.jwt.claim.role='';- set request.jwt.claim.email='';- set request.jwt.claims='';- set role anon;-end;-$$;--create or replace procedure auth.logout ()- language plpgsql- as $$-begin- set request.jwt.claim.sub='';- set request.jwt.claim.role='';- set request.jwt.claim.email='';- set request.jwt.claims='';- set role postgres;-end;-$$;```-To switch to a given user (by email), use `call auth.login_as_user('[email protected]');`. You can also switch to the `anon` role using `call auth.login_as_anon();`. When you are done, use `call auth.logout();` to return yourself to the `postgres` role.--These procedures can also be used for writing [pgTAP](/docs/guides/database/extensions/pgtap) unit tests for policies.--<details>- <summary>Click here to see an example `psql` interaction using this.</summary>--This example shows that the `public.profiles` table from the tutorial example can indeed be updated by the `postgres` role and the owner of the row but not from `anon` connections:--```shell-postgres=> select id, email from auth.users;- id | email---------------------------------------+-------------------- d4f0aa86-e6f6-41d1-bd32-391f077cf1b9 | [email protected]- 15d6811a-16ee-4fa2-9b18-b63085688be4 | [email protected]- 4e1010bb-eb37-4a4d-a05a-b0ee315c9d56 | [email protected]-(3 rows)--postgres=> table public.profiles;- id | updated_at | username | full_name | avatar_url | website---------------------------------------+------------+----------+-----------+------------+---------- d4f0aa86-e6f6-41d1-bd32-391f077cf1b9 | | user1 | User 1 | |- 15d6811a-16ee-4fa2-9b18-b63085688be4 | | user2 | User 2 | |- 4e1010bb-eb37-4a4d-a05a-b0ee315c9d56 | | user3 | User 3 | |-(3 rows)--postgres=> call auth.login_as_anon();-CALL-postgres=> update public.profiles set updated_at=now();-UPDATE 0 -- anon users cannot update any profile but see all of them-postgres=> table public.profiles;- id | updated_at | username | full_name | avatar_url | website---------------------------------------+------------+----------+-----------+------------+---------- d4f0aa86-e6f6-41d1-bd32-391f077cf1b9 | | user1 | User 1 | |- 15d6811a-16ee-4fa2-9b18-b63085688be4 | | user2 | User 2 | |- 4e1010bb-eb37-4a4d-a05a-b0ee315c9d56 | | user3 | User 3 | |-(3 rows)--postgres=> call auth.logout();-CALL-postgres=> call auth.login_as_user('[email protected]');-NOTICE: set role authenticated; -- logging in as 'd4f0aa86-e6f6-41d1-bd32-391f077cf1b9' ('[email protected]')-CALL-postgres=> update public.profiles set updated_at=now();-UPDATE 1 -- authenticated users can update their own profile and see all of them-postgres=> table public.profiles;- id | updated_at | username | full_name | avatar_url | website---------------------------------------+-------------------------------+----------+-----------+------------+---------- 15d6811a-16ee-4fa2-9b18-b63085688be4 | | user1 | User 1 | |- 4e1010bb-eb37-4a4d-a05a-b0ee315c9d56 | | user2 | User 2 | |- d4f0aa86-e6f6-41d1-bd32-391f077cf1b9 | 2023-02-18 21:39:16.204612+00 | user3 | User 3 | |-(3 rows)--postgres=> call auth.logout();-CALL-postgres=> update public.profiles set updated_at=now();-UPDATE 3 -- the 'postgres' role can update and see all profiles-postgres=> table public.profiles;- id | updated_at | username | full_name | avatar_url | website---------------------------------------+-------------------------------+----------+-----------+------------+---------- 15d6811a-16ee-4fa2-9b18-b63085688be4 | 2023-02-18 21:40:08.216324+00 | user1 | User 1 | |- 4e1010bb-eb37-4a4d-a05a-b0ee315c9d56 | 2023-02-18 21:40:08.216324+00 | user2 | User 2 | |- d4f0aa86-e6f6-41d1-bd32-391f077cf1b9 | 2023-02-18 21:40:08.216324+00 | user3 | User 3 | |-(3 rows)--```--</details>-export const Page = ({ children }) => <Layout meta={meta} children={children} />export default Page