Test row level security in CI
Turn your policies into checks that fail the build when a visitor or another user can read, change or write rows they should not, and know which tool fits which check.
Policies are code, and a policy that is too open fails silently: the application keeps working, and shows more than it should. A test that reads and writes as a visitor and as two different users catches that, before deployment and after every schema change.
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 test a table sec_test_notes with an owner policy, and save the script in tests/rls.sh; the Clean up block removes both. Run the tests against a project made for it (a preview branch or a test project), never against production data: the checks insert rows.
aura db raw "create table sec_test_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_test_notes_owner on sec_test_notes
for all to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id)"
aura db raw "insert into sec_test_notes (user_id, body) values ('00000000-0000-4000-8000-0000000000a1', 'Alice note')" ℹ No results (0 rows).
ℹ No results (0 rows).
ℹ No results (0 rows).What to prove#
For each table the application exposes:
| Check | Expected |
|---|---|
| A visitor reads | Nothing, or only the public rows |
| A user reads | Its own rows, and the shared rows it is entitled to |
| A second user reads the first one's rows | Nothing |
| A second user updates or deletes the first one's rows | Zero rows changed |
| A user inserts a row in someone else's name | Refused |
| Row level security | On for every table and partition |
| Privileges of the public roles | Only what you decided (Roles and privileges) |
Test with users that differ: a check run only as the owner of the rows proves nothing about the others.
Three ways to run the checks#
| Tool | Runs as | Needs | Writes | Fits |
|---|---|---|---|---|
aura db raw --as anon / --as authenticated --user <uuid> | The public role, with the user id you choose | The service_role key and the project URL | Rolled back with --dry-run | Most checks: fast, no real user needed |
POST /v1/db/{project_id}/rls/simulate | The same | The service_role key, curl | Always rolled back | Checks from any language; one operation per call (Simulate a policy) |
| The SDK with a signed-in user | Exactly what the application runs | The anon key, real sign-ups | Real | A final end-to-end check of the real path |
aura db raw --as and the simulator set auth.role() to anon or authenticated, while the SDK path sees aura_anon and aura_authenticated. Policies written with to … and auth.uid() behave the same on all three; a policy that compares auth.role() does not, which an SDK test reveals.
A test script#
The block below saves a script in tests/rls.sh and runs it. count compares the result of a query with the expected number, refused expects a write to fail; writes run with --dry-run, so the test leaves no row behind. Adapt the table names and ids to your schema; the two ids are the demo users of the example schema.
mkdir -p tests
cat > tests/rls.sh <<'SCRIPT'
#!/usr/bin/env bash
# Row level security checks. Needs AURABASE_SERVICE_ROLE_KEY and a linked project.
set -uo pipefail
ALICE=00000000-0000-4000-8000-0000000000a1
BOB=00000000-0000-4000-8000-0000000000b2
failed=0
fail() { # a failed check sets the exit code to 1, unless a check could not run (2 is kept)
echo "FAIL $1"; [ "$failed" -eq 2 ] || failed=1
}
reason() { # the status and code of an error printed by aura, such as "[401] API_KEY_INVALID", or its first line
grep -oE '\[[0-9]{3}\] [A-Z_]+' <<< "$1" | head -n 1 | grep . || grep -m 1 -v 'Executed as' <<< "$1"
}
count() { # count <label> <expected> <arguments of aura db raw>
local label=$1 expected=$2 out got
shift 2
if ! out=$(aura db raw --json "$@" 2>&1); then
echo "ERROR $label: $(reason "$out")"; failed=2; return
fi
# with --as, --json prints an "Executed as …" line before the JSON: read from the first "["
got=$(node -pe 'const t = require("fs").readFileSync(0, "utf8"); JSON.parse(t.slice(t.indexOf("[")))[0].n' <<< "$out")
if [ "$got" = "$expected" ]; then echo "ok $label"; else fail "$label: expected $expected, got $got"; fi
}
refused() { # refused <label> <arguments of aura db raw>: passes only on a row level security refusal
local label=$1 out
shift
if out=$(aura db raw --dry-run "$@" 2>&1); then
fail "$label: accepted"
elif grep -q 'violates row-level security policy' <<< "$out"; then
echo "ok $label"
else
echo "ERROR $label: refused for another reason: $(reason "$out")"; failed=2
fi
}
count "a visitor reads no note" 0 --as anon "select count(*) as n from sec_test_notes"
count "alice reads her note" 1 --as authenticated --user $ALICE "select count(*) as n from sec_test_notes"
count "bob reads none of alice's notes" 0 --as authenticated --user $BOB "select count(*) as n from sec_test_notes where user_id = '$ALICE'"
count "bob changes none of alice's notes" 0 --dry-run --as authenticated --user $BOB \
"with changed as (update sec_test_notes set body = 'x' where user_id = '$ALICE' returning 1) select count(*) as n from changed"
count "bob deletes none of alice's notes" 0 --dry-run --as authenticated --user $BOB \
"with gone as (delete from sec_test_notes where user_id = '$ALICE' returning 1) select count(*) as n from gone"
refused "bob cannot write a note as alice" --as authenticated --user $BOB \
"insert into sec_test_notes (user_id, body) values ('$ALICE', 'x')"
if ! tables=$(aura db table list --json 2>&1); then
echo "ERROR table list: $(reason "$tables")"; failed=2
else
open=$(node -pe 'JSON.parse(require("fs").readFileSync(0, "utf8")).filter((t) => !t.rls_enabled).map((t) => t.name).join(" ")' <<< "$tables")
if [ -z "$open" ]; then echo "ok every table has row level security"; else fail "tables without row level security: $open"; fi
fi
exit $failed
SCRIPT
bash tests/rls.shok a visitor reads no note
ok alice reads her note
ok bob reads none of alice's notes
ok bob changes none of alice's notes
ok bob deletes none of alice's notes
ok bob cannot write a note as alice
ok every table has row level securityThe script exits with 1 when a check fails and with 2 when a check could not run (missing or wrong key, network, rate limit); when both happen in one run, the exit code is 2. A refusal only counts when it is the refusal of a policy (new row violates row-level security policy), never any error. Either way the CI job fails. The script makes seven checks: six send one aura db raw request each, the last one lists the tables. Each aura db raw request counts against the SQL quota of the project: on the Free plan, 60 requests per minute and 2,000 per month by default (Pro: 600 per minute, 100,000 per month). Run on every pull request, the script uses 6 of the monthly 2,000 each time: run it against a test project, and group several counts in one query when the suite grows.
See it catch a leak#
A policy added later, meant for an admin page, opens every note to every signed-in user:
aura db raw "create policy sec_test_notes_everyone on sec_test_notes for select to aura_authenticated using (true)"
bash tests/rls.sh || echo "exit code $?"
aura db raw "drop policy sec_test_notes_everyone on sec_test_notes" ℹ No results (0 rows).
ok a visitor reads no note
ok alice reads her note
FAIL bob reads none of alice's notes: expected 0, got 1
ok bob changes none of alice's notes
ok bob deletes none of alice's notes
ok bob cannot write a note as alice
ok every table has row level security
exit code 1
ℹ No results (0 rows).The permissive policies of a role add up with or: the owner policy still exists, but the new one lets Bob read Alice's note. The update and delete checks still pass, since the new policy is for select only.
A check that cannot run is an error, not a pass. With a wrong key, every request fails before reaching PostgreSQL, and the script says so instead of counting the refusal of the insert as a success:
AURABASE_SERVICE_ROLE_KEY=aura_sk_not_a_real_key bash tests/rls.sh || echo "exit code $?"ERROR a visitor reads no note: [401] API_KEY_INVALID
ERROR alice reads her note: [401] API_KEY_INVALID
ERROR bob reads none of alice's notes: [401] API_KEY_INVALID
ERROR bob changes none of alice's notes: [401] API_KEY_INVALID
ERROR bob deletes none of alice's notes: [401] API_KEY_INVALID
ERROR bob cannot write a note as alice: refused for another reason: [401] API_KEY_INVALID
ERROR table list: [401] API_KEY_INVALID
exit code 2Test through the SDK#
An SDK test signs a real user up and runs the same requests as the application. It also catches mistakes that only the SDK path shows, such as a policy that compares auth.role():
import assert from 'node:assert/strict'
import { createClient } from '@aurabase/aurabase-js'
const url = process.env.AURABASE_URL!
const anonKey = process.env.AURABASE_ANON_KEY!
const visitor = createClient(url, anonKey)
const seen = await visitor.from('sec_test_notes').select('id')
assert.deepEqual(seen.data, [], 'a visitor reads no note')
const user = createClient(url, anonKey)
const email = `rls-test-${Date.now()}@example.com`
const password = 'correct-horse-battery-9'
await user.auth.signUp({ email, password })
const { error } = await user.auth.signInWithPassword({ email, password })
assert.equal(error, null)
const others = await user.from('sec_test_notes').select('body')
assert.deepEqual(others.data, [], "a new user reads none of alice's notes")
const forged = await user.from('sec_test_notes').insert({ user_id: '00000000-0000-4000-8000-0000000000a1', body: 'x' })
assert.equal(forged.error?.code, 'INSUFFICIENT_PRIVILEGE', 'writing as alice is refused')
const own = await user.from('sec_test_notes').insert({ body: 'mine' }).select('body')
assert.deepEqual(own.data, [{ body: 'mine' }], 'a user writes its own note')
console.log('all SDK checks passed')all SDK checks passedA project requires email confirmation by default: turn it off on the test project (aura auth settings set email_confirmation_required=false), as in the Quickstart. Sign-ups are also limited per IP address (5 per hour by default, rate_limit_signup_per_hour): create a few test users once and sign them in at each run, rather than signing new ones up every time.
Run it in CI#
aura db raw talks to the data plane with the service_role key: no aura login is needed in CI. It reads the project from aurabase.toml (written by aura link, commit it) or from AURABASE_PROJECT_ID and NEXT_PUBLIC_AURABASE_URL. Excerpt of a GitHub Actions workflow (not replayed here):
name: rls
on: [pull_request]
jobs:
rls:
runs-on: ubuntu-latest
env:
AURABASE_PROJECT_ID: ${{ vars.TEST_PROJECT_ID }}
NEXT_PUBLIC_AURABASE_URL: ${{ vars.TEST_PROJECT_URL }}
AURABASE_SERVICE_ROLE_KEY: ${{ secrets.TEST_SERVICE_ROLE_KEY }}
steps:
- uses: actions/checkout@v4
- run: npm install -g @aurabase/cli
- run: aura db push # apply the migrations of the pull request first
- run: bash tests/rls.shStore the service_role key of the test project as a secret of the repository, never in the workflow file.
pgTAP#
pgTAP is not available: it is not in the list of extensions a project may enable, and projects cannot run create extension. aura db extensions enable pgtap answers Extension 'pgtap' is not allowed on this cluster. Write the checks as above, or as SQL queries that return counts.
Result#
The checks left no row behind, apart from the note written by the SDK test user:
aura db raw "select count(*) as notes from sec_test_notes where body <> 'mine'" notes
─────
1
ℹ 1 row(s).Common errors#
| Message | Cause | Fix |
|---|---|---|
AURABASE_SERVICE_ROLE_KEY is not set. | The variable is missing in the CI job. | Add the secret to the job environment. |
No project linked. Run 'aura link' first (or 'aura init'). | No aurabase.toml and no AURABASE_PROJECT_ID. | Commit aurabase.toml or set the variable. |
--as authenticated requires --user <uuid> (the impersonated user) | --as authenticated without a user id. | Pass --user <uuid>. |
429 RATE_LIMITED | More than 60 SQL requests in a minute on the Free plan. | Fewer checks per run, or group several counts in one query. |
FAIL … expected 0, got 1 | A policy lets a role reach rows it should not. | Read the policies of the table (aura db policy list --table … --json) and remove or narrow the one that matches. |
| The SDK test hangs, then fails on sign-up | The sign-up limit per IP is reached. | Reuse test users; raise rate_limit_signup_per_hour on the test project only. |
Clean up#
rm -rf tests
aura db raw "drop table sec_test_notes" ℹ No results (0 rows).