الأمان على مستوى الصفوف
فعّل الأمان على مستوى الصفوف في جدول، وامنح كل مستخدم صفوفه بسياسة واحدة، وافهم لماذا يعود الصف المخفي مصفوفةً فارغة، وتحقق من أجزاء قاعدة البيانات التي لا تغطيها السياسات.
Row level security (RLS) is the PostgreSQL feature that decides, row by row, what a role may read and write. On a table with RLS on, a query only sees the rows that a policy lets its role see, and a write is accepted only if a policy allows it. With no policy at all, nothing is visible and nothing can be written, except by the roles that bypass RLS.
How it works#
Each request reaches PostgreSQL as a role: the anon key becomes aura_anon, a signed-in user becomes aura_authenticated with its id in auth.uid(), and the service_role key becomes a role that bypasses RLS (Roles, keys and RLS bypass lists them). PostgreSQL then adds the policies written for that role to the query:
select * from todos ← the query sent by the SDK for alice
policy todos_owner: using (auth.uid() = user_id)
select * from todos where auth.uid() = user_id ← what PostgreSQL runsThree facts shape everything on this page:
- Tables created through Aurabase have RLS on.
aura db table create, the schema API, the Studio andaura db raw(soaura db pushtoo) enable and force RLS on every new table. Until you add a policy, the anon key and signed-in users get no row. - A hidden row is not an error. A read that no policy allows returns an empty array; an update or delete that reaches no row succeeds and changes nothing. Only a written row that a policy refuses fails.
- RLS filters rows, not privileges. The public roles hold every table privilege on the tables of your schema by default,
truncateincluded, and several kinds of objects have no RLS at all. What row level security does not protect lists them; Roles and privileges shows how to reduce those privileges.
Prerequisites#
-
A linked project:
aura link <project-id>. -
The example schema, installed with the service role key of the project:
export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docsIt creates
profiles,orgs,org_members,posts,todos, the viewopen_todosand the functiontodo_count(p_user uuid). See Example schema.
The examples create the table sec_rls_notes, then remove it. The SDK example signs a test user up: on a project that requires email confirmation (the default), turn it off first, as in the Quickstart.
Turn it on and off#
Create a table in SQL. Its user_id column defaults to the id of the signed-in user, so the application never has to send it:
aura db raw "create table sec_rls_notes (
id bigint generated always as identity primary key,
user_id uuid not null default auth.uid(),
body text not null)"
aura db table list | grep sec_rls_notes ℹ No results (0 rows).
• sec_rls_notes [RLS][RLS] marks a table whose RLS is on. aura db table rls <table> on|off switches it, as do PATCH /v1/db/{project_id}/schema/tables/{table}/rls with {"enabled": true} (the service_role key is required) and the RLS policies tab of a table in the Studio (/<project-id>/database/sql/table-editor/rls). Turning it on runs enable and force row level security together; turning it off runs no force and disable together, and says what it means. The block below switches it off with the CLI and back on over HTTP:
aura db table rls sec_rls_notes off
curl -s -X PATCH "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sec_rls_notes/rls" \
-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d '{"enabled": true}'
echo ✔ RLS disabled on 'sec_rls_notes'.
⚠ Row Level Security is now OFF on 'sec_rls_notes': anyone holding the public (anon) key can read and write every row of this table. Re-enable it with `aura db table rls sec_rls_notes on` and add policies before exposing the table.
{"data":{"table":"sec_rls_notes","rls_enabled":true},"meta":null}In SQL, alter table … enable row level security and alter table … force row level security do the same. A table that you create with disable row level security in the same request keeps it off: Aurabase only turns RLS on for tables that appear during a request and that the request did not explicitly leave open. Two kinds of tables are never switched on for you: tables created over the direct PostgreSQL connection, and partitions. See What row level security does not protect.
Give each user its own rows#
One policy covers the four commands for signed-in users: using filters the rows a user reads, updates and deletes, with check validates the rows it inserts or updates.
create policy sec_rls_notes_owner on sec_rls_notes
for all to aura_authenticated
using (auth.uid() = user_id)
with check (auth.uid() = user_id); ℹ No results (0 rows).to aura_authenticated keeps the anon key out of the policy entirely: a visitor has no auth.uid(), so an owner policy would not match anyway, but the role clause says it plainly and saves the evaluation. Check the result as two demo users and as a visitor before writing any application code:
aura db raw "insert into sec_rls_notes (user_id, body) values
('00000000-0000-4000-8000-0000000000a1', 'Alice: call the bank'),
('00000000-0000-4000-8000-0000000000b2', 'Bob: book the room')"
aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select body from sec_rls_notes"
aura db raw --as anon "select count(*) as visible from sec_rls_notes" ℹ No results (0 rows).
ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1).
body
────────────────────
Alice: call the bank
ℹ 1 row(s).
ℹ Executed as anon.
visible
───────
0
ℹ 1 row(s).From an application, a signed-in user reads its own notes, writes new ones without sending user_id, and cannot write a note for someone else:
import { createClient } from '@aurabase/aurabase-js'
const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const email = `rls-${Date.now()}@example.com`
const password = 'correct-horse-battery-9'
await aura.auth.signUp({ email, password })
const { error: signInError } = await aura.auth.signInWithPassword({ email, password })
if (signInError) throw signInError
const before = await aura.from('sec_rls_notes').select('body')
console.log('before:', before.data, before.error)
const mine = await aura.from('sec_rls_notes').insert({ body: 'My first note' }).select('body')
console.log('insert:', mine.data, mine.error)
const forAlice = await aura.from('sec_rls_notes').insert({ user_id: '00000000-0000-4000-8000-0000000000a1', body: 'Not mine' })
console.log('insert for alice:', forAlice.error?.status, forAlice.error?.code, forAlice.error?.message)
const touched = await aura.from('sec_rls_notes').update({ body: 'Edited' }).eq('body', 'Alice: call the bank').select('body')
console.log('update alice:', touched.data, touched.error)
const after = await aura.from('sec_rls_notes').select('body')
console.log('after:', after.data)before: [] null
insert: [ { body: 'My first note' } ] null
insert for alice: 403 INSUFFICIENT_PRIVILEGE new row violates row-level security policy for table "sec_rls_notes"
update alice: [] null
after: [ { body: 'My first note' } ]The other common shapes (public read of published rows, signed-in read, membership of an organization, a role claim, a restrictive policy) are on Policies.
Empty answers and refusals#
PostgreSQL hides rows instead of failing, so most RLS mistakes look like missing data. What each path returns when no policy allows the operation:
| Operation | SDK and REST API | aura db raw --as …, db.sql() |
|---|---|---|
| Read | 200, data: []. An unfiltered read adds meta.hint, which names the role and suggests a policy. | ℹ No results (0 rows). |
Insert, or an update whose new row fails with check | 403 INSUFFICIENT_PRIVILEGE, new row violates row-level security policy for table "…", upstream_code: "42501" | 400 BAD_REQUEST, Invalid request: new row violates row-level security policy for table "…" |
| Update of rows the role cannot see | 200, data: [], meta.hint starting No row was updated. and rows_affected: 0 | Success, no row changed |
| Delete of rows the role cannot see | 204, nothing deleted | Success, no row deleted |
| Table without the privilege (not a policy matter) | 403 INSUFFICIENT_PRIVILEGE, permission denied for table … | 400 BAD_REQUEST, Invalid request: permission denied for table … |
The two paths do not use the same status for the same refusal: write your error handling on the code (INSUFFICIENT_PRIVILEGE, or the PostgreSQL code 42501) and the message, not on the status alone.
To see the rows a role can reach, run the query with aura db raw --as anon or --as authenticated --user <uuid>, or ask the simulator, which also tries writes inside a transaction it rolls back: Simulate a policy.
Auth helpers in policies#
Policies read the caller from the claims of its token. The schema auth of the database provides these functions. None of them raises an error when the request carries no token or lacks a claim: the last column gives what each one returns then, so a policy that compares them to a user value denies instead of failing. One exception: if SQL of your own sets the claims to an empty string (set local request.jwt.claims = ''), auth.jwt() fails with invalid input syntax for type json, while the other functions still return the values of the last column.
| Function | Returns | Without a token or claim | Notes |
|---|---|---|---|
auth.uid() | uuid of the signed-in user (claim sub) | NULL | NULL for the anon key, for a service_role key and for a key of scope authenticated sent without a user token |
auth.role() | text, claim role | 'anon' | Differs by path: aura_anon, aura_authenticated, aura_service_role through the SDK and REST; anon, authenticated through aura db raw --as and the simulator. Do not compare it in a policy: use to aura_authenticated instead. |
auth.jwt() | jsonb, all claims | {} | |
auth.email() | text, claim email | NULL | |
auth.claim(key) | jsonb, one top-level claim | NULL | |
auth.tenant() | uuid from app_metadata.tenant | NULL | Also NULL when the value is not a uuid. See Multi-tenant schema design. |
auth.has_role(name) | boolean, true if app_metadata.roles contains name | false | Roles you set from a server, never from user_metadata, which users can change themselves |
auth.is_anonymous() | boolean, true for a user signed in anonymously | false | Such a user has the role aura_authenticated and an id |
The same values seen from each path, through a function that returns them:
aura db raw "create function sec_rls_whoami() returns json language sql stable as
\$\$ select json_build_object('uid', auth.uid(), 'role', auth.role()) \$\$;
grant execute on function sec_rls_whoami() to aura_anon"
curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rpc/sec_rls_whoami" \
-H "apikey: $AURABASE_ANON_KEY" -H 'content-type: application/json' -d '{}'
echo
aura db raw --as anon "select sec_rls_whoami() as caller" ℹ No results (0 rows).
{"data":{"uid" : null, "role" : "aura_anon"},"meta":{}}
ℹ Executed as anon.
caller
──────────────────────────
{"role":"anon","uid":null}
ℹ 1 row(s).Point rows at users#
There is no auth.users table to reference: references auth.users (id) fails with relation "auth.users" does not exist. The users of a project live in the schema project_<id>_auth, which the REST API does not serve and which Auth manages. Store the owner in a plain uuid column, as todos.user_id does, and fill it with default auth.uid() or from the session (session.user.id in the SDK). A foreign key to project_<id>_auth.users is accepted by PostgreSQL, but how it interacts with the deletion of a user by Auth was not tested: keep the column without a foreign key, and remove a deleted user's rows from a server.
What row level security does not protect#
Row level security only filters the rows of tables that have it on, for the roles that do not bypass it. The rest depends on privileges and on how objects were created. These are the gaps measured on a project, with the safe practice for each:
| Gap | What happens | Safe practice |
|---|---|---|
| Broad default privileges | Every table, view, materialized view and partition of your schema grants all privileges to aura_anon and aura_authenticated: select, insert, update, delete, truncate, references, trigger and maintain. | Revoke what the public roles never need: Roles and privileges. |
truncate | PostgreSQL does not apply policies to truncate: a role that holds the privilege empties the table, whatever the policies say. The REST API never sends truncate; SQL run as a public role (a function you expose, for example) can. | Revoke truncate from aura_anon and aura_authenticated. |
Views with security_invoker = false | A view created with this option reads with its owner's rights: the anon key reads every row through it, and writes through it when it is updatable. | Never set it; Aurabase sets security_invoker = true on views without the option. See Views. |
| Materialized views | PostgreSQL has no RLS on them: the public roles read every stored row. | Revoke them from the public roles. See Views. |
| Partitions | A partition created in SQL has RLS off; reading the parent applies the parent's policies, but SQL that names the partition reads it unfiltered. | Turn RLS on for each partition. See Partitions. |
| Objects created over the direct connection | A table created after switching to the administrator role over psql or an ORM gets the broad privileges and no RLS: the anon key reads it. | Enable RLS in the same migration. See Connect. |
| Tables created by a public role | The public roles may create tables in your schema; such a table belongs to them and has no RLS. | Revoke create on your schema from them (Roles and privileges). |
| Realtime and hidden columns | A table enabled for postgres_changes sends whole rows to every subscriber allowed to see the row: column privileges do not apply to the events. | Do not enable Realtime on a table with hidden columns. See Column-level security. |
| Platform tables | A few tables of the Auth and Storage schemas of your project have no RLS and are readable by the public roles; the REST API does not serve them, but a view in your schema would. | Keep views and functions on your own tables. See Project isolation. |
| Roles that bypass RLS | The service_role key, aura db raw without --as, and the password of the direct connection act as administrator: they read every row, including Auth data. | Keep them on servers; never in a browser or a mobile app. See API keys. |
Checklist before you ship#
aura db table list: every table you expose shows[RLS]. Partitions are listed too; turn RLS on for each.- Every table the application reads has a policy per role and command it needs, written with
to aura_authenticatedorto aura_anonandauth.uid(), never withauth.role(). - Every view has
security_invoker = true; no view was created withsecurity_invoker = false. - Materialized views are revoked from
aura_anonandaura_authenticated. truncate,references,triggerandmaintainare revoked from the public roles on your tables,createon your schema, and the defaults changed for future tables (Roles and privileges). Re-check after platform upgrades.- Functions are granted only to the roles that call them; a
security definerfunction filters onauth.uid()itself (Database functions). - The
service_rolekey and the direct-connection password stay on servers (API keys). - A test proves that a second user and a visitor cannot read or change the first user's rows, and it runs in CI (Test RLS in CI).
- SQL sent through
aura db raw,db.sql()or the SQL editor usesset local, neversetalone: a setting withoutlocalis accepted, but it can outlive the request on the pooled connection and apply to later requests of the project (Run SQL).
The security advisor (GET /v1/db/{project_id}/schema/advisors/security with the service_role key) flags tables and partitions with RLS off and policies whose using is true. It does not inspect privileges, views or materialized views.
Policies and query speed#
A policy is added to every query on the table, so it costs what a where clause costs. Index the columns a policy compares, as the example schema does with todos_user_id_idx; PostgreSQL then uses the index for the policy:
aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "explain select * from todos" ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1).
QUERY PLAN
──────────────────────────────────────────────────────────────────────────────
Bitmap Heap Scan on todos (cost=4.43..13.89 rows=4 width=65)
Filter: (auth.uid() = user_id)
-> Bitmap Index Scan on todos_user_id_idx (cost=0.00..4.43 rows=4 width=0)
Index Cond: (user_id = auth.uid())
ℹ 4 row(s).Also filter in the query itself (.eq('user_id', userId)): the planner then knows the condition before it reads the policy. A policy that queries another table for each row (a membership check) is the usual slow case; put that check in a security definer function, as Multi-tenant schema design does. Aurabase did not benchmark other rewrites of policies for this page.
Result#
The table has RLS on, one owner policy for signed-in users, and no policy for visitors:
aura db policy list --table sec_rls_notes --json[
{
"check_expr": "(auth.uid() = user_id)",
"command": "ALL",
"policy_name": "sec_rls_notes_owner",
"roles": [
"aura_authenticated"
],
"table_name": "sec_rls_notes",
"using_expr": "(auth.uid() = user_id)"
}
]Common errors#
| Message | Cause | Fix |
|---|---|---|
data: [] with a meta.hint starting 0 rows returned. | RLS is on and no select policy lets this role read these rows; or the table is empty. | Add a policy for the role (Policies); check with aura db raw "select …" --as …. |
403 INSUFFICIENT_PRIVILEGE, new row violates row-level security policy for table "…" | The row written does not satisfy with check, often a user_id that is not the caller's, or no insert policy for the role. | Write rows the policy accepts; use default auth.uid() for the owner column. |
An update returns [] and meta.hint starting No row was updated. | No update policy reaches these rows for the role, or the filter matches nothing. | Add an update policy with using; check the filter. |
A policy works with aura db raw --as but not from the SDK, or the reverse | It compares auth.role(), which returns different names on the two paths. | Replace it by to aura_authenticated or to aura_anon. |
| Every signed-in user sees nothing | auth.uid() is NULL: the request carries no user token (anon key alone, or a key of scope authenticated). | Sign the user in with the SDK, which sends its token. |
relation "auth.users" does not exist | The Auth users are not in a schema named auth. | Store the user id in a uuid column (Point rows at users). |
infinite recursion detected in policy for relation "…" | A policy queries its own table. | Move the check into a security definer function (Simulate a policy shows the error). |
permission denied for table … | The role lacks the privilege, before any policy is read: a revoked privilege or a table created over the direct connection with the project's own login role. | Grant the privilege (Roles and privileges). |
Clean up#
drop function if exists sec_rls_whoami();
drop table sec_rls_notes; ℹ No results (0 rows).See also#
- Policies
Create, change and drop policies in SQL, with the CLI or over HTTP.
- Simulate a policy
Try reads and writes as anon or as a user, rolled back.
- Test RLS in CI
A script that fails when a user can read someone else's rows.
- Roles and privileges
The privileges behind the policies, and how to reduce them.
- Column-level security
Hide columns that every reader of a row must not see.
- Public read access
Open a table, or some of its rows, to the anon key.
- API keys
Which key bypasses RLS and where each one may live.
- Multi-tenant schema design
Policies for organizations and tenants.