How a request reaches Postgres
Follow a request from your code to PostgreSQL, see which role it runs as and where auth.uid() gets its value, and know which component answers when something fails.
Mental model#
There are three doors into a project database. The SDK and the REST API go to a PostgREST server that belongs to the project. SQL sent with aura db raw, the Studio and the schema commands goes to the aura-db service, which checks it and runs it. A direct PostgreSQL connection goes through a router to the connection pooler of the cluster.
SDK / REST ─▶ gateway :8080 ─▶ PostgREST of the project ─────────────────────────▶ PostgreSQL
│ key, user token, rate limit role: aura_anon | aura_authenticated | aura_service_role
│
aura db raw ─▶ gateway ─▶ NATS ─▶ aura-db (SQL check) ─▶ PgBouncer ─────────────▶ PostgreSQL
role: tenant_<id>_admin (service_role key), or aura_anon / aura_authenticated with --as
psql, ORM ─▶ router :5432 (TLS) ─▶ PgBouncer of the organization cluster ────────▶ PostgreSQL
role: proj_xxxxxxxx (no pooler on a dedicated cluster)SDK and REST#
- Gateway, data plane. The request arrives on the project URL. The gateway attaches a request id, applies the rate limit of the plan (
db.requests), and authenticates the call: the API key inapikeyorX-API-Keymust belong to the project, and an optionalAuthorization: Bearer <access token>identifies a signed-in user. Aservice_rolekey that arrives with anOriginheader (a browser) is refused with401 SECRET_KEY_IN_BROWSER. - Routing. Reads, inserts, updates (
PATCH), deletes andrpc()calls go to the PostgREST server of the project over HTTP. APUTand the management routes (/raw,/schema, policies, functions…) go toaura-dbinstead. - Signed token. The gateway signs a short-lived token for PostgREST with a secret derived from the project id. It carries the PostgreSQL role to use (
aura_anonfor the anon key,aura_authenticatedfor a user,aura_service_rolefor theservice_rolekey) and, for a user only, the user id insub. A key alone has nosub, soauth.uid()isNULL. - PostgREST. It switches to that role for the transaction, puts the token claims in
request.jwt.claims, runs the pre-request hook of the platform and executes the query. It connects to the primary of the cluster directly, asaura_authenticator, with a small pool of its own. A read returns at most 1,000 rows. - Response. The gateway wraps the result as
{ data, meta }. An unfiltered read that returns no row for anon or a user gets ameta.hintthat names the likely cause: row level security without a matching policy.
SQL through aura-db#
- Gateway. Same authentication.
/rawthen requires theservice_rolekey; any other key gets403 FORBIDDEN. - NATS. The gateway forwards the request to
aura-dbover NATS (subjectaura.svc.db). - SQL check.
aura-dbreads the SQL and refuses transaction control,SET, catalogs, other schemas,CREATE EXTENSIONand the other patterns listed in Run SQL from the CLI or a server. - Transaction. It takes a connection from its pool, logged in as
aura_authenticatorthrough the PgBouncer of the cluster, opens a transaction and sets, withSET LOCAL: the role (tenant_<id>_adminfor theservice_rolekey,aura_anonoraura_authenticatedwith--as), the search path (your schema, the storage schema of the project,public), a statement timeout of 10 seconds by default, and the claims of the simulated user. - After a schema change. It enables row level security on every new table, sets
security_invokeron every new view, and asks PostgREST to reload its schema cache.
Direct connection#
The router listens on port 5432, answers the TLS handshake with the *.db.<domain> certificate, reads the user name from the startup message, finds the project of that proj_ role and forces its database. On the cluster of an organization it forwards the connection to PgBouncer in transaction mode; on a dedicated cluster it goes straight to the primary. Nothing checks your SQL on this path: PostgreSQL privileges and row level security decide. Connect to your database has the rules that follow from it.
Claims and auth helpers#
Policies and functions read the caller from the setting request.jwt.claims, through helpers of the auth schema:
| Helper | Returns | Value without a user |
|---|---|---|
auth.uid() | sub of the claims, as uuid | NULL |
auth.role() | role of the claims | depends on the path, see below |
auth.tenant() | app_metadata.tenant, if it is a UUID | NULL |
auth.has_role(name) | true if app_metadata.roles contains name | false |
auth.jwt() | all the claims, as jsonb | {} when no claims are set |
auth.email() | email of the claims | NULL |
The claims are set by the server, from a token it signed or checked: a client cannot write them.
auth.role() does not return the same value on the two paths. Through the SDK and REST it returns the PostgreSQL role name (aura_anon, aura_authenticated, aura_service_role); through aura db raw --as it returns anon or authenticated, and anon for the service_role key, which carries no claims there. Write policies with to aura_authenticated and auth.uid() rather than with a test on auth.role().
See the role of each key#
This function reports the role and the claims it runs with. Create it and let the three roles of the REST path call it:
aura db raw "create function whoami() returns json language sql stable as \$\$
select json_build_object('db_role', current_user, 'role', auth.role(), 'uid', auth.uid())
\$\$;
grant execute on function whoami() to aura_anon, aura_authenticated, aura_service_role" ℹ No results (0 rows).import { createClient } from '@aurabase/aurabase-js'
const url = process.env.AURABASE_URL!
const anon = createClient(url, process.env.AURABASE_ANON_KEY!)
console.log('anon key:', (await anon.rpc('whoami')).data)
const admin = createClient(url, process.env.AURABASE_SERVICE_ROLE_KEY!)
console.log('service_role key:', (await admin.rpc('whoami')).data)
const user = createClient(url, process.env.AURABASE_ANON_KEY!)
const email = `flow-${Date.now()}@example.com`
await user.auth.signUp({ email, password: 'correct-horse-battery-9' })
const { data: session } = await user.auth.signInWithPassword({ email, password: 'correct-horse-battery-9' })
const me = (await user.rpc('whoami')).data as { db_role: string; role: string; uid: string }
console.log('signed-in user:', me.db_role, me.role, me.uid === session?.user?.id)anon key: { db_role: 'aura_anon', role: 'aura_anon', uid: null }
service_role key: { db_role: 'aura_service_role', role: 'aura_service_role', uid: null }
signed-in user: aura_authenticated aura_authenticated trueThe script signs a test user up: on a project that requires email confirmation (the default), turn it off first with aura auth settings set email_confirmation_required=false, as in the Quickstart. Remove the function when you are done:
aura db raw "drop function whoami()" ℹ No results (0 rows).Trade-offs#
- Two engines behind one URL. PostgREST serves reads and writes,
aura-dbservesPUT, SQL and the schema API. Errors on the first path carry anupstream_codefrom PostgREST or PostgreSQL (42501,PGRST205…); errors on the second come back as400 BAD_REQUESTwith the PostgreSQL message. - PostgREST pool. Each PostgREST server keeps a small pool on the primary (by default 2 connections per replica on the cluster of an organization, 10 on a dedicated cluster; the deployment can change both). When all are busy, a request waits up to 3 seconds, then fails with
503 DB_POOL_TIMEOUTand aRetry-Afterheader. - A table created over the direct connection is unknown to PostgREST until the schema cache reloads:
notify pgrst, 'reload schema'(SQL throughaura-dbtriggers the reload for you). - Waking up. A project whose database instance is asleep answers
503withRetry-After: 5while it wakes up; retry the request. - Two statement timeouts. On the SDK and REST path, PostgreSQL cancels a statement after 5 seconds for the anon key and after 10 seconds for a signed-in user or the
service_rolekey, and the gateway answers504 STATEMENT_TIMEOUT. On theaura-dbpath (aura db raw), the limit is 10 seconds by default (a request can raise its own limit, but the gateway stops waiting after about 30 seconds by default and answers408) and the answer is400withcanceling statement due to statement timeout. The direct connection sets no timeout. See Connection pooling and limits. - Session state set on the direct connection does not survive the end of a transaction behind PgBouncer. See Connection pooling and limits.
Related pages#
- Roles, keys and RLS bypass
Each role on these paths, and which ones bypass row level security.
- Connection pooling and limits
The pools on each path and the limits of each plan.
- Run SQL from the CLI or a server
What the SQL check of aura-db refuses.
- Row-level security
Policies that use auth.uid() and the claims.