Supabase RLS Policies

Supabase RLS Policies

Guides an agent to write, review and test Supabase Row Level Security policies, proving with pgTAP tests that one user cannot read or change another user's rows.

Skill files1 file
SKILL.md254 lines
1
---
2
name: supabase-rls-policies
3
description: 'Write, review, and test Supabase Row Level Security (RLS) policies so that one user cannot read or change another user''s rows. Use when creating or changing tables, policies, views, or security definer functions in a Supabase project, when reviewing a migration that touches RLS, or when asked to prove user isolation with pgTAP tests that sign in as two users.'
4
---
5
6
# Supabase RLS Policies
7
8
Write Row Level Security (RLS) policies for Supabase tables, then prove them with pgTAP tests that act as two different users. A policy is not finished until a test shows that a second user cannot read, change, delete, or create rows that belong to the first user.
9
10
## When to Use This Skill
11
12
- Creating a table in an exposed schema (by default `public`)
13
- Adding or changing a policy, a view, or a `security definer` function
14
- Reviewing a migration or pull request that touches RLS
15
- Answering whether users or tenants are isolated from each other
16
17
## Workflow
18
19
1. **List the access rules first.** For each table, write down which role (`anon` or `authenticated`) may run which operation (`select`, `insert`, `update`, `delete`) on which rows. Confirm the list with the user before writing SQL. Each rule gets one test.
20
2. **Write the migration.** Enable RLS, add one policy per operation, and index every column the policies filter on.
21
3. **Write a pgTAP test file** for the table under `supabase/tests/`, using the template below.
22
4. **Run `supabase test db`** and read every line of output.
23
5. **Break the policy on purpose, on a local database only.** Copy the test file and add a temporary policy with `using (true)` right after `begin;`, for example `create policy "tmp_open" on public.notes for select to authenticated using (true);`. Run `supabase test db` against the local stack from `supabase start`, confirm at least one test fails, then delete the copy. Do the same with a temporary `for update` and a `for delete` policy. The file ends with `rollback`, so the temporary policy is undone even when the run fails or stops early. Never put a temporary policy in a migration, and never run this against a shared or production database. Do not drop the real policy to do this: with no policy every read is denied, so denial tests still pass and prove nothing.
24
6. **Do not change a policy just to make a test pass.** Report which assertion failed and which policy it covers, and let the user decide which one is wrong.
25
26
## Rules for Every Table
27
28
### Enable RLS and name the role
29
30
- Run `alter table ... enable row level security` on every table in an exposed schema. Once RLS is on and no policy exists, the API returns no rows.
31
- Add a `to` clause to every policy. Without it the policy applies to `PUBLIC`, which means every role, including `anon`.
32
- `auth.uid()` returns `null` when the request has no signed in user. `to authenticated` keeps anonymous requests from reaching the check at all.
33
34
### One policy per operation, with the owner checked on writes
35
36
```sql
37
alter table public.notes enable row level security;
38
39
create policy "notes_select_own" on public.notes
40
for select to authenticated
41
using ((select auth.uid()) = owner_id);
42
43
create policy "notes_insert_own" on public.notes
44
for insert to authenticated
45
with check ((select auth.uid()) = owner_id);
46
47
create policy "notes_update_own" on public.notes
48
for update to authenticated
49
using ((select auth.uid()) = owner_id)
50
with check ((select auth.uid()) = owner_id);
51
52
create policy "notes_delete_own" on public.notes
53
for delete to authenticated
54
using ((select auth.uid()) = owner_id);
55
56
create index notes_owner_id_idx on public.notes using btree (owner_id);
57
```
58
59
- `using` checks rows that already exist. `with check` checks the row being written. Rows that fail `using` are skipped with no error; a row that fails `with check` raises an error.
60
- **Bind the owner column in every insert and update check.** A check such as `auth.uid() is not null` only proves the caller is signed in. Any signed in user can then insert a row with another user's id in the owner column.
61
- A column default such as `default auth.uid()` does not protect the owner column. Postgres uses a default only when the insert does not supply a value, and the client can always supply one.
62
- An `update` needs a matching `select` policy, or the update will not work as expected.
63
- Wrap `auth.uid()` and `auth.jwt()` in `(select ...)` so Postgres runs them once per statement instead of once per row.
64
- Index every column a policy filters on. A column counts as indexed only when it is the first column of a btree index.
65
66
### Authorization data in the token
67
68
- Never base a policy on `user_metadata` (`raw_user_meta_data`). Signed in users can change it themselves.
69
- Store roles, teams, and plans in `app_metadata` (`raw_app_meta_data`), which users cannot change, and read it with `auth.jwt()`.
70
- A change to `app_metadata` reaches `auth.jwt()` only after the user's token is refreshed. A user removed from a team keeps access until then.
71
72
### Multi factor authentication
73
74
To require a second factor, add a restrictive policy:
75
76
```sql
77
create policy "notes_require_aal2" on public.notes
78
as restrictive
79
for all to authenticated
80
using ((select auth.jwt()->>'aal') = 'aal2');
81
```
82
83
Restrictive policies only narrow access. A table with only restrictive policies returns no rows, so keep the permissive policies above.
84
85
### Views
86
87
Views bypass RLS by default because they run with the rights of the role that created them. On Postgres 15 and later, create views with `security_invoker = true`:
88
89
```sql
90
create view public.my_notes
91
with (security_invoker = true)
92
as select id, body from public.notes;
93
```
94
95
On older versions, remove every grant path or keep the view in a schema that is not exposed. Revoking only the direct grants is not enough: a grant to `PUBLIC`, a grant to a role the API roles are members of, or a grant on a single column still lets them read the view. Check the result with `has_any_column_privilege`, which counts all three; `relacl` lists only direct table grants.
96
97
```sql
98
revoke all on public.my_notes from public, anon, authenticated;
99
select has_any_column_privilege('anon', 'public.my_notes', 'select'),
100
has_any_column_privilege('authenticated', 'public.my_notes', 'select'); -- both must be false
101
```
102
103
### Security definer functions
104
105
- A `security definer` function runs as its owner. If the owner is `postgres`, it bypasses RLS.
106
- Never create one in an exposed schema. It can be called over the Data API with the owner's rights.
107
- Set `search_path = ''` and schema qualify every name inside the function.
108
109
### Keys
110
111
- Secret keys (and the legacy `service_role` key) bypass RLS. Use them only on a server, never in a browser or mobile app.
112
- A secret key bypasses RLS only when the request has no user access token. If the request carries one, that user's policies apply.
113
114
## Two User pgTAP Test Template
115
116
Save as `supabase/tests/notes_rls_test.sql` and adapt the table, columns, and ids. The file runs in one transaction and rolls back, so test data never persists.
117
118
```sql
119
begin;
120
create extension if not exists pgtap with schema extensions;
121
select plan(8);
122
123
-- Two users, created before switching roles.
124
insert into auth.users (id, email) values
125
('11111111-1111-1111-1111-111111111111', 'user1@test.com'),
126
('22222222-2222-2222-2222-222222222222', 'user2@test.com');
127
128
insert into public.notes (id, owner_id, body) values
129
('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '11111111-1111-1111-1111-111111111111', 'user 1 note');
130
131
-- As user 1: the owner can read and change their own row.
132
set local role authenticated;
133
set local request.jwt.claims = '{"sub": "11111111-1111-1111-1111-111111111111", "role": "authenticated"}';
134
135
select results_eq(
136
$$select body from public.notes where id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'$$,
137
$$values ('user 1 note'::text)$$,
138
'user 1 reads their own note'
139
);
140
141
select results_eq(
142
$$update public.notes set body = 'edited' where id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' returning body$$,
143
$$values ('edited'::text)$$,
144
'user 1 updates their own note'
145
);
146
147
-- As user 2: every attempt on user 1's row must fail.
148
-- User 2 owns no rows yet, so the write probes need no where clause.
149
set local request.jwt.claims = '{"sub": "22222222-2222-2222-2222-222222222222", "role": "authenticated"}';
150
151
select is_empty(
152
$$select 1 from public.notes where id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'$$,
153
'user 2 cannot read user 1 note'
154
);
155
156
select is_empty(
157
$$update public.notes set body = 'changed' returning 1$$,
158
'user 2 cannot update user 1 note'
159
);
160
161
select is_empty(
162
$$delete from public.notes returning 1$$,
163
'user 2 cannot delete user 1 note'
164
);
165
166
select throws_ok(
167
$$insert into public.notes (owner_id, body) values ('11111111-1111-1111-1111-111111111111', 'forged')$$,
168
'42501', null,
169
'user 2 cannot create a note owned by user 1'
170
);
171
172
select results_eq(
173
$$insert into public.notes (owner_id, body) values ('22222222-2222-2222-2222-222222222222', 'user 2 note') returning owner_id$$,
174
$$values ('22222222-2222-2222-2222-222222222222'::uuid)$$,
175
'user 2 creates their own note'
176
);
177
178
-- No where clause: the update policy alone picks user 2's row,
179
-- so only its with check can stop the transfer.
180
select throws_ok(
181
$$update public.notes set owner_id = '11111111-1111-1111-1111-111111111111'$$,
182
'42501', null,
183
'user 2 cannot hand their note to user 1'
184
);
185
186
select * from finish();
187
rollback;
188
```
189
190
Notes on the template:
191
192
- Use `returning` on writes. An update or delete that RLS filters out succeeds with zero rows, so only the returned rows show what happened.
193
- In user 2's update and delete probes, do not filter on a column or return one. When an update or delete reads a column, Postgres applies the `select` policy as well, so a correct `select` policy can hide an `update` or `delete` policy that is too open. Return the constant `1` and rely on user 2 owning no rows yet.
194
- Filter reads by the ids the test inserted. A count over the whole table breaks once other data exists.
195
- Error `42501` is the code Postgres raises when a written row fails a `with check` expression.
196
- Add an `anon` case for any table that anonymous visitors must not read, and add one to the plan count. Replace the claims first: changing the role does not clear them, so `auth.uid()` would still return user 2's id.
197
198
```sql
199
set local request.jwt.claims = '{"role": "anon"}';
200
set local role anon;
201
select is_empty(
202
$$select 1 from public.notes where id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'$$,
203
'an anonymous visitor cannot read user 1 note'
204
);
205
```
206
207
If your project does not grant table privileges to `anon`, the read raises `42501` instead, so use `throws_ok`.
208
209
## Testing Policies That Read Other Claims
210
211
The template sets the whole claims object in `request.jwt.claims`, the setting PostgREST fills from the token. `auth.uid()` and `auth.jwt()` both read it. If a test sets only `request.jwt.claim.sub`, `auth.uid()` still works but `auth.jwt()` returns `null`, so a policy that compares a claim such as `aal` or a value in `app_metadata` sees `null`. The `aal2` policy above denies every user in that state, so a test that expects a denial passes for the wrong reason.
212
213
For a table with the restrictive `aal2` policy, add `"aal": "aal2"` to the claims at both user switches in the template, so the owner checks still pass. Then test the other side before `select * from finish();`, and add these two assertions to the plan count:
214
215
```sql
216
-- If the anon case ran first, the SQL role is still anon. The role claim in the JSON does not change it.
217
set local role authenticated;
218
set local request.jwt.claims = '{"sub": "11111111-1111-1111-1111-111111111111", "role": "authenticated", "aal": "aal1"}';
219
select is_empty(
220
$$select 1 from public.notes where id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'$$,
221
'an aal1 session cannot read user 1 note'
222
);
223
224
set local request.jwt.claims = '{"sub": "11111111-1111-1111-1111-111111111111", "role": "authenticated", "aal": "aal2"}';
225
select isnt_empty(
226
$$select 1 from public.notes where id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'$$,
227
'an aal2 session reads user 1 note'
228
);
229
```
230
231
## Review Checklist
232
233
- [ ] RLS is enabled on every table in an exposed schema
234
- [ ] Every policy names a role with `to`
235
- [ ] Insert and update checks bind the owner column to `(select auth.uid())`
236
- [ ] No policy reads `user_metadata`
237
- [ ] Views use `security_invoker = true`, or are not exposed
238
- [ ] Security definer functions live outside exposed schemas and set `search_path = ''`
239
- [ ] Each policy column has an index that leads with that column
240
- [ ] Each user data table has a two user test covering read, update, delete, and insert
241
- [ ] The second user's update and delete probes read no column
242
- [ ] Tests set the full `request.jwt.claims` object at each user switch, and replace it before the `anon` case
243
- [ ] The suite fails when a temporary `using (true)` policy is added inside the test transaction on a local database
244
245
## References
246
247
- [Row Level Security](https://supabase.com/docs/guides/database/postgres/row-level-security), Supabase docs
248
- [Test Row Level Security policies with pgTAP](https://supabase.com/docs/guides/database/postgres/testing-row-level-security), Supabase docs
249
- [Multi-Factor Authentication](https://supabase.com/docs/guides/auth/auth-mfa), Supabase docs
250
- [CREATE POLICY](https://www.postgresql.org/docs/current/sql-createpolicy.html), PostgreSQL docs
251
- [Transactions](https://docs.postgrest.org/en/stable/references/transactions.html), PostgREST docs (`request.jwt.claims`)
252
- [CREATE TABLE](https://www.postgresql.org/docs/current/sql-createtable.html), PostgreSQL docs (column defaults)
253
- [auth.uid() source](https://github.com/supabase/auth/blob/35307ce6c1ca59016fd820f1d77d9b6201dc2e15/migrations/20220224000811_update_auth_functions.up.sql) and [auth.jwt() source](https://github.com/supabase/auth/blob/35307ce6c1ca59016fd820f1d77d9b6201dc2e15/migrations/20220531120530_add_auth_jwt_function.up.sql), Supabase Auth
254

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,420 prompts

More by @OpenSourceBuffGuy

See all
Skateboard selection screen with HotDog Dash selected prompt image

Skateboard selection screen with HotDog Dash selected

Plans a 15-second game clip that moves from a skateboard selection screen into a live city world, with every UI state and sound cue set per timed beat.

video-prompt, hailuo, timed-beats, reference-image, image-to-video, character-consistency, state-tracking, structured-output, motion-graphics, scene-transitions, video-games, game-development, action, camera-movement, sound-effects, multi-shot, ui-mockup, animation, advanced, long-form, transformation, for-gamers, dance

Blue and gold character tree with doll ornaments prompt image

Blue and gold character tree with doll ornaments

Turns a reference character into a lavishly decorated Christmas tree with themed plush ornaments, matching lights and a character topper.

image-prompt, reference-image, photo-editing, christmas, holiday, photorealistic, nano-banana, placeholders, structured-output, character-design, cozy, luxury, still-life, golden-hour, soft-lighting, vibrant-colors, wide-shot, for-artists, gift-ideas, vertical-format

Woman laughs as giant koi splash her prompt image

Woman laughs as giant koi splash her

Generates a 15-second handheld phone-style video of a woman laughing as giant koi splash her in a Japanese canal town, keeping her face from a reference image.

video-prompt, hailuo, timed-beats, handheld, vlog, documentary, smartphone-photo, candid, reference-image, character-consistency, photorealistic, natural-light, summer, japan, animals, travel, negative-prompt, vertical-format, structured-output, long-form, for-content-creators, for-filmmakers, camera-movement, ugc-video, sound-effects, minimax

Reviews

Loading reviews…

Discussion

Loading comments…