Simulate a policy
Ask PostgreSQL what a visitor or a given user can read, insert, update or delete in a table, without changing any row, and use the answer to find the policy that hides a row or refuses a write.
POST /v1/db/{project_id}/rls/simulate runs one operation on one table as the role and user you name, inside a transaction that is always rolled back. The answer says whether rows came back, how many, a sample of them, and the PostgreSQL error when the operation failed. It requires the service_role key.
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 tables sec_sim_notes and sec_sim_members and the function sec_sim_my_teams, then remove them:
aura db raw "create table sec_sim_notes (
id bigint generated always as identity primary key,
user_id uuid not null default auth.uid(),
body text not null)"
aura db raw "create policy sec_sim_notes_owner on sec_sim_notes
for all to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id)"
aura db raw "insert into sec_sim_notes (user_id, body) values
('00000000-0000-4000-8000-0000000000a1', 'Alice note'),
('00000000-0000-4000-8000-0000000000b2', 'Bob note')" ℹ No results (0 rows).
ℹ No results (0 rows).
ℹ No results (0 rows).What the simulator runs#
In one transaction, rolled back at the end whatever happens:
- It sets the claims of a token:
role(anonorauthenticated),subfromuser_id,email, and the extraclaimsyou send. - It switches to
aura_anonoraura_authenticated. Forservice_role, it stays on the administrator role of the project, which bypasses row level security. - It runs the operation on the table of your schema:
operation | SQL run |
|---|---|
SELECT | select * from <table> limit <limit> |
INSERT | insert into <table> (<payload keys>) values (<payload values>) returning * |
UPDATE | update <table> set <payload> returning *, on every row the role can reach (no filter) |
DELETE | delete from <table> returning *, on every row the role can reach (no filter) |
Because it is real SQL in PostgreSQL, the policies, privileges, constraints, defaults and triggers of the table all apply, exactly as for a request of that role. Two things are not undone by the rollback: values taken from an identity column or a sequence (an INSERT simulation leaves a gap in the ids), and work done outside the database.
Request#
| Field | Required | Values |
|---|---|---|
table | Yes | A table of your schema, plain identifier |
operation | Yes | SELECT, INSERT, UPDATE or DELETE, any case. ALL is refused. |
role | Yes | anon, authenticated, service_role, or their aura_ names |
user_id | No | The uuid returned by auth.uid() |
email | No | The value of auth.email() |
claims | No | A JSON object merged into the claims, for auth.jwt(), auth.tenant(), auth.has_role() ({"app_metadata": {"roles": ["editor"]}}). Its role is always replaced by the role above; its sub and email are replaced only when user_id or email is sent and not empty. |
payload | INSERT, UPDATE | A non-empty JSON object, column → value. Strings, numbers, booleans and null are sent as SQL literals; arrays and objects as jsonb. |
limit | No | Rows of a SELECT, from 1 to 50; 25 by default |
Response#
Always 200 once the request is valid, with these fields in data:
| Field | Meaning |
|---|---|
allowed | SELECT: at least one row came back, or the table has row level security off. Other operations: at least one row was written. |
rls_enabled | Row level security is on for the table. |
row_count | Rows returned by the operation (at most limit for a SELECT). |
sample_rows | The rows themselves, up to limit. |
error_code | null, or RLS_DENIED (a policy refused a written row, or a privilege is missing), RECURSIVE_POLICY (a policy queries its own table), SQL_ERROR (anything else: unknown column, constraint, unknown table). |
error_message | The PostgreSQL message, prefixed Invalid request: . |
evaluated_by | Always postgresql. |
execution_time_ms | Time spent, in milliseconds. |
allowed: false with no error means "no row": a SELECT on an empty table, or on rows no policy shows, gives the same answer. Look at row_count against what you expected, not at allowed alone.
Simulate a read#
Alice reads her own note; a visitor reads none. The command prints the fields that matter and the bodies of the rows:
for who in '"role": "authenticated", "user_id": "00000000-0000-4000-8000-0000000000a1"' '"role": "anon"'; do
curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \
-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
-d "{\"table\": \"sec_sim_notes\", \"operation\": \"SELECT\", $who}" \
| node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data
console.log(d.allowed, d.rls_enabled, d.row_count, d.error_code, d.sample_rows.map((r) => r.body))'
donetrue true 1 null [ 'Alice note' ]
false true 0 null []Simulate writes#
Bob tries to insert a note in Alice's name, then in his own, then deletes what he can reach; a visitor tries to update. Nothing is kept:
simulate() {
curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \
-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d "$1" \
| node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data
console.log(d.allowed, d.row_count, d.error_code, d.error_message ?? "")'
}
BOB=00000000-0000-4000-8000-0000000000b2
simulate '{"table": "sec_sim_notes", "operation": "INSERT", "role": "authenticated", "user_id": "'$BOB'",
"payload": {"user_id": "00000000-0000-4000-8000-0000000000a1", "body": "Not mine"}}'
simulate '{"table": "sec_sim_notes", "operation": "INSERT", "role": "authenticated", "user_id": "'$BOB'",
"payload": {"body": "Mine"}}'
simulate '{"table": "sec_sim_notes", "operation": "DELETE", "role": "authenticated", "user_id": "'$BOB'"}'
simulate '{"table": "sec_sim_notes", "operation": "UPDATE", "role": "anon", "payload": {"body": "Defaced"}}'
aura db raw "select body from sec_sim_notes order by body"false 0 RLS_DENIED Invalid request: new row violates row-level security policy for table "sec_sim_notes"
true 1 null
true 1 null
false 0 null
body
──────────
Alice note
Bob note
ℹ 2 row(s).The DELETE simulation reached one row, Bob's own: a real delete sent by Bob without filter would remove exactly that. The table still holds both notes.
Simulate claims#
claims lets you test policies that read the token: a role set in app_metadata.roles, a tenant, an email. Add a policy that lets auditors read every note, then compare Bob with and without the role:
aura db raw "create policy sec_sim_notes_auditors on sec_sim_notes
for select to aura_authenticated using (auth.has_role('auditor'))"
for claims in '{}' '{"app_metadata": {"roles": ["auditor"]}}'; do
curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \
-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
-d '{"table": "sec_sim_notes", "operation": "SELECT", "role": "authenticated",
"user_id": "00000000-0000-4000-8000-0000000000b2", "claims": '"$claims"'}' \
| node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data; console.log(d.row_count)'
done ℹ No results (0 rows).
1
2The simulator sets the claim role to anon or authenticated, as aura db raw --as does, while the SDK and the REST API see aura_anon and aura_authenticated in auth.role(). A policy that compares auth.role() is therefore not simulated faithfully; target roles with to … instead.
Find a recursive policy#
A policy that reads its own table to decide (here: "members see the rows of their teams") makes PostgreSQL loop. The simulator names the problem:
aura db raw "create table sec_sim_members (team_id int not null, user_id uuid not null, primary key (team_id, user_id))"
aura db raw "create policy sec_sim_members_team on sec_sim_members for select to aura_authenticated
using (team_id in (select m.team_id from sec_sim_members m where m.user_id = auth.uid()))"
aura db raw "insert into sec_sim_members values (1, '00000000-0000-4000-8000-0000000000a1'), (1, '00000000-0000-4000-8000-0000000000b2')"
curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \
-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
-d '{"table": "sec_sim_members", "operation": "SELECT", "role": "authenticated", "user_id": "00000000-0000-4000-8000-0000000000a1"}' \
| node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data; console.log(d.error_code, d.error_message)' ℹ No results (0 rows).
ℹ No results (0 rows).
ℹ No results (0 rows).
RECURSIVE_POLICY Invalid request: infinite recursion detected in policy for relation "sec_sim_members"Move the lookup into a security definer function, which reads the table with its owner's rights and therefore without going through the policy again, and use it in the policy:
aura db function create sec_sim_my_teams --language sql --returns 'setof int' \
--body 'select team_id from sec_sim_members where user_id = auth.uid()' \
--security definer --grant-execute-to authenticated
aura db raw "drop policy sec_sim_members_team on sec_sim_members;
create policy sec_sim_members_team on sec_sim_members for select to aura_authenticated
using (team_id in (select sec_sim_my_teams()))"
curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \
-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
-d '{"table": "sec_sim_members", "operation": "SELECT", "role": "authenticated", "user_id": "00000000-0000-4000-8000-0000000000a1"}' \
| node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data; console.log(d.allowed, d.row_count, d.error_code)' ✔ Function 'sec_sim_my_teams' created (sql → setof int).
• EXECUTE granted to: authenticated
⚠ SECURITY DEFINER: function executes with its owner's privileges, not the caller's.
ℹ No results (0 rows).
true 2 nullAlice now sees both members of her team. The function returns only the teams of the caller and is granted to signed-in users only.
In the Studio#
Database › a table › RLS simulator (/<project-id>/database/sql/table-editor/rls/simulate) sends the same request. When the server answers, the verdict comes from PostgreSQL; when it does not, the Studio falls back to an estimate computed in the browser and labels it as such: trust only the PostgreSQL verdict.
Result#
The simulations changed no row: the table holds the two notes of the setup.
aura db raw "select count(*) as notes from sec_sim_notes" notes
─────
2
ℹ 1 row(s).Common errors#
for body in '{"table": "sec_sim_notes", "operation": "ALL", "role": "anon"}' \
'{"table": "sec_sim_notes", "operation": "SELECT", "role": "admin"}' \
'{"table": "sec_sim_notes", "operation": "UPDATE", "role": "anon"}' \
'{"table": "sec_sim_notes", "operation": "INSERT", "role": "service_role", "payload": {"owner": "x"}}'; do
curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \
-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d "$body" \
| node -e 'const r = JSON.parse(require("fs").readFileSync(0, "utf8")); console.log(r.error ? r.error.message : r.data.error_code + " " + r.data.error_message)'
doneInvalid request: Specify SELECT, INSERT, UPDATE or DELETE to simulate an operation
Invalid request: Invalid simulation role: 'admin'
Invalid request: A non-empty JSON payload is required to simulate UPDATE
SQL_ERROR Invalid request: column "owner" of relation "sec_sim_notes" does not exist (line 4, column 77)| Message | Cause | Fix |
|---|---|---|
Specify SELECT, INSERT, UPDATE or DELETE to simulate an operation (400) | operation is ALL. | Simulate each command. |
Invalid simulation role: '…' (400) | A role other than anon, authenticated or service_role. | Use one of the three; express other roles as claims. |
A non-empty JSON payload is required to simulate UPDATE (400) | INSERT or UPDATE without payload. | Send the columns to write. |
Invalid RLS command: '…' (400) | Unknown operation. | SELECT, INSERT, UPDATE or DELETE. |
403 FORBIDDEN, DDL operation is reserved to the service_role role | Called with the anon key. | Call it from a server with the service_role key. |
error_code: "SQL_ERROR", relation "project_….…" does not exist | Unknown table. | Check the name with aura db table list. |
error_code: "RLS_DENIED", permission denied for table … | A privilege is missing, which is not a policy. | Grant it (Roles and privileges). |
allowed: false, row_count: 0, no error | No row came back: an empty table, or no policy shows the rows. | Compare with service_role, which bypasses the policies. |
Clean up#
drop table if exists sec_sim_members;
drop function if exists sec_sim_my_teams();
drop table sec_sim_notes; ℹ No results (0 rows).