コンテンツへスキップ
オーラベースのロゴ
オーラベース

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.

解説9 分 読み取りレベル 中間

このページはまだお使いの言語では利用できません。英語で表示されます。

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#

  1. 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 in apikey or X-API-Key must belong to the project, and an optional Authorization: Bearer <access token> identifies a signed-in user. A service_role key that arrives with an Origin header (a browser) is refused with 401 SECRET_KEY_IN_BROWSER.
  2. Routing. Reads, inserts, updates (PATCH), deletes and rpc() calls go to the PostgREST server of the project over HTTP. A PUT and the management routes (/raw, /schema, policies, functions…) go to aura-db instead.
  3. 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_anon for the anon key, aura_authenticated for a user, aura_service_role for the service_role key) and, for a user only, the user id in sub. A key alone has no sub, so auth.uid() is NULL.
  4. 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, as aura_authenticator, with a small pool of its own. A read returns at most 1,000 rows.
  5. Response. The gateway wraps the result as { data, meta }. An unfiltered read that returns no row for anon or a user gets a meta.hint that names the likely cause: row level security without a matching policy.

SQL through aura-db#

  1. Gateway. Same authentication. /raw then requires the service_role key; any other key gets 403 FORBIDDEN.
  2. NATS. The gateway forwards the request to aura-db over NATS (subject aura.svc.db).
  3. SQL check. aura-db reads the SQL and refuses transaction control, SET, catalogs, other schemas, CREATE EXTENSION and the other patterns listed in Run SQL from the CLI or a server.
  4. Transaction. It takes a connection from its pool, logged in as aura_authenticator through the PgBouncer of the cluster, opens a transaction and sets, with SET LOCAL: the role (tenant_<id>_admin for the service_role key, aura_anon or aura_authenticated with --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.
  5. After a schema change. It enables row level security on every new table, sets security_invoker on 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:

HelperReturnsValue without a user
auth.uid()sub of the claims, as uuidNULL
auth.role()role of the claimsdepends on the path, see below
auth.tenant()app_metadata.tenant, if it is a UUIDNULL
auth.has_role(name)true if app_metadata.roles contains namefalse
auth.jwt()all the claims, as jsonb{} when no claims are set
auth.email()email of the claimsNULL

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 true

The 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-db serves PUT, SQL and the schema API. Errors on the first path carry an upstream_code from PostgREST or PostgreSQL (42501, PGRST205…); errors on the second come back as 400 BAD_REQUEST with 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_TIMEOUT and a Retry-After header.
  • A table created over the direct connection is unknown to PostgREST until the schema cache reloads: notify pgrst, 'reload schema' (SQL through aura-db triggers the reload for you).
  • Waking up. A project whose database instance is asleep answers 503 with Retry-After: 5 while 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_role key, and the gateway answers 504 STATEMENT_TIMEOUT. On the aura-db path (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 answers 408) and the answer is 400 with canceling 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.
@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ 問題を報告する