Skip to content

App roles

Normally every signed-in request runs as the database role authenticated. When several apps share one project (for example apps installed into a workspace), they would then all see the same data. App roles give each app its own role, app_<slug>. A request of that app runs as its role, and your grants and policies decide what it may read.

POST /v1/projects/{ref}/db/roles
{ "name": "app_crm" }

The name is app_ followed by lower-case letters, digits and _ (at most 40 characters). A project can have up to 50 app roles. Upper-case letters are refused (400), never converted.

Names ending in _public, _anon, _svc, _migrator or _runner are reserved for names Base derives from an app, so a new role or app with such a name is refused with 400. Creating app_crm is also refused with 409 name_conflict while a role or schema named app_crm_public, app_crm_runner, and so on already exists (for example left over from an older app): remove it first. Existing roles with a reserved suffix keep working. The same rules apply to bootstrap.app_roles and bootstrap.app_schemas when you create a project. GET /v1/projects/{ref}/db/roles lists them together with:

  • db_prefix;
  • max_slug_length, the longest slug this project allows.

Postgres roles are shared by every database of the server, so the real role is named "<db>.app_crm", like the project owner "<db>.owner". You use the short name app_crm everywhere except where SQL needs a role identifier (see below). The role:

  • cannot log in;
  • does not inherit privileges;
  • never bypasses row level security;
  • is a member of no other role;
  • owns nothing.

It gets what authenticated has on the built-in schemas (the auth.* helpers, Storage, Realtime) and nothing in your schemas until you grant it.

POST /v1/projects/{ref}/db/app-schemas
{ "name": "app_crm", "expose": true }

This call does several things, and repeating it is safe:

  • creates the role if it does not exist yet;
  • creates the schema app_crm, owned by the project owner (never by the app role);
  • grants the app role USAGE on that schema, and nothing to authenticated or anon;
  • with expose, adds the schema to the Data API (db_schemas, same rules and 50-schema limit).

Table grants, core grants and policies stay in the app’s migrations. GET /v1/projects/{ref}/db/app-schemas lists each app with state (active or detached), exposed and schema_exists.

An existing schema of that name is only taken over if it is owned by the project owner and is safe. It is refused with 409 app_schema_unsafe and the reasons when:

  • PUBLIC, anon or authenticated hold privileges on it;
  • another role has CREATE on it;
  • objects in it belong to another role;
  • default privileges are set for it.

"adopt": true revokes the first two and continues. The last two must be fixed by hand.

You decide how long to keep the data.

1. Detach: POST /v1/projects/{ref}/db/app-schemas/app_crm/detach.

  • The app role stops being accepted at once: new token exchanges get 401, and Storage and new Realtime joins refuse it.
  • Its open Realtime channels are closed when the project configuration reloads. That happens immediately in normal operation (under 1 s), and at most 60 s later if the change notification is lost.
  • The schema is removed from the Data API, and the role loses the memberships that PostgREST, Realtime and Storage use to switch to it.
  • The data stays.
  • What can still run: a token already issued keeps its database session only until the next request, which then fails because the role can no longer be switched to. Transactions already running finish.
  • POST .../attach (optionally { "expose": true }) undoes it. Detach and attach either complete or are rolled back, so the app is never left half detached.

2. Purge: DELETE /v1/projects/{ref}/db/app-schemas/app_crm. The app must be detached first (409 must_detach_first). The schema is dropped, then the role. Before anything is dropped:

  • Objects outside the schema that depend on it (views, foreign keys or policies in core, publication memberships, extension objects, …) give 409 external_dependents with the list. With cascade_external=true&confirm=app_crm they are dropped too.
  • A non-empty schema gives 409 schema_not_empty. cascade=true drops its contents and every grant the role still has.
  • A role that could not be deleted afterwards (grants outside its schema, without cascade) gives 409 role_in_use, and nothing is dropped.

The check and the drop happen in one transaction. The answer lists the external objects that were dropped, and warnings lists functions whose body mentions app_crm.: Postgres cannot see those dependencies, so check them. keep_role=true keeps the role. Every step is recorded in the audit log.

Run an app’s migrations as the app (run_as)

Section titled “Run an app’s migrations as the app (run_as)”

By default migrations run as the project owner, who can change everything in the database. With run_as an app’s migrations run as a role of their own that owns only the app’s schema:

Terminal window
# once per app (or install with { "name": "app_crm", "migrator": true })
curl -s -X POST -H "Authorization: Bearer $PAT" $BASE_API/v1/projects/shop/db/app-schemas/app_crm/migrator
curl -s -X POST -H "Authorization: Bearer $PAT" -H 'content-type: application/json' \
-d '{"app":"app_crm","run_as":"migrator","migrations":[{"version":"0001","sql":"create table app_crm.leads (id bigint primary key)"}]}' \
$BASE_API/v1/projects/shop/database/migrations/batch
  • Base creates two roles: <db>.app_crm_migrator owns the schema app_crm and everything in it, and <db>.app_crm_runner is the login the migrations connect as. Its password is generated, stored encrypted, never returned, and rotated every 30 days (or with POST .../app-schemas/app_crm/rotate-runner).
  • The migration can create and change objects in app_crm only. Anything outside it fails with permission denied. Grants to anon / authenticated still go through the policy gate.
  • SET ROLE, RESET ROLE, set_config('role', …), role DDL, extensions and admin functions are refused (400 statement_not_allowed). Even when SQL built at run time does it, the session can only reach a role without privileges: the migration is rolled back with 409 run_as_escaped.
  • run_as works for migrations, migrations/batch and migrations/plan, and for CREATE INDEX CONCURRENTLY on the app’s tables. It needs app.
  • Detaching the app disables the runner login; attaching enables it again; purging removes both roles.

Enabling it on an existing app moves the schema and the objects the project owner owns in it to the migrator.

In a migration (as the project owner), use the helpers. They only accept a registered app role, and only objects in the app’s own schema (same name as the role) or in core:

create schema app_crm;
create table app_crm.leads (id bigint primary key, name text, owner uuid default auth.uid());
alter table app_crm.leads enable row level security;
select base.grant_app_schema('app_crm'); -- USAGE on schema app_crm
select base.grant_app('app_crm', 'select, insert', 'table', 'app_crm.leads');
select base.grant_app('app_crm', 'select', 'default_tables', 'app_crm'); -- future tables
Kind Privileges
schema USAGE (never CREATE: an app role must not own objects)
table, all_tables, default_tables SELECT, INSERT, UPDATE, DELETE; TRUNCATE and REFERENCES only in the app’s own schema, never in core
sequence, all_sequences, default_sequences USAGE, SELECT, UPDATE
function EXECUTE

ALL and TRIGGER are never accepted. base.revoke_app(...) takes the same arguments.

A grant, owner, policy or user mapping that names another project’s app role ("<other db>.app_x") is refused (42501). Only what the current statement adds is checked, so an older leftover never blocks your migrations. Leftovers are reported, never removed:

  • the advisor lists them as foreign_app_role;
  • the database upgrade run prints a warning.

GRANT ... ON DATABASE is a cluster-wide object that this check cannot see, but the project owner has no grant option on its database, so it cannot make such a grant.

auth.role() returns the app role’s short name. It is taken from the role the request actually runs as, never from a token claim:

create policy crm_own on app_crm.leads for all to public
using (auth.role() = 'app_crm' and owner = auth.uid());

auth.uid() (a uuid sub) and auth.jwt() work as usual. Base does not interpret claims such as tenant_id or perms: read them in your policies with auth.jwt().

Storage policies on storage.objects (uploads, downloads, signed URLs, listing) and Realtime see the same role. On the Realtime side that covers postgres_changes, channel policies on realtime.channel_access, and presence. Public buckets stay readable by anyone. Storage events record the app role. For example, bucket_id = 'app_crm_files' and auth.role() = 'app_crm' confines a bucket to one app.

An app’s requests carry a JWT from your third-party issuer (for example your gateway). Map a claim to the app role:

{ "role_claim": "app", "role_map": { "crm": "app_crm" }, "default_role": "anon" }
  • Only roles in role_map can be reached. Saving a map with an unregistered app role fails with 422 unknown_app_role.
  • When role_map contains an app role, the provider fails closed. The claim must be one plain string (printable ASCII, at most 100 characters) found in the map. A missing or unmapped value, an array, an object or a number, or a non-ASCII value is refused with 401, never mapped to default_role.
  • A token whose claim names a database role directly, such as service_role, postgres, app_crm or another project’s role, is refused with 401.
  • If the role is deleted later, its tokens get 401. They never fall back to authenticated.

DELETE /v1/projects/{ref}/db/roles/app_crm answers 409 role_in_use in two cases, and changes nothing either way:

  • the role still has grants or objects in the project database;
  • another database references it.

?cascade=true resolves the first case only: it revokes everything and drops what the role owns in the project database, then drops the role. All of it runs under one lock. In the rare case that the final DROP ROLE still fails, the answer is 500 role_drop_failed: the role is kept, but its privileges and owned objects in the project database are already gone, so re-grant them before using the app again. Tokens that were issued for a deleted role stop working at once. Both deletes are recorded in the audit log.

The security advisor reports these findings:

Finding Level When
app_role_owns_objects warn an app role owns objects (owners bypass row level security)
app_role_privileged error an app role can log in, inherits privileges, bypasses row level security, has REPLICATION, or belongs to another role
foreign_app_role error objects here are granted to another project’s app role
migrator_privileged / runner_privileged error a migrator or runner role has attributes or memberships beyond the ones Base gives it
migrator_inherited error a role inherits an app migrator (it would hold the app’s privileges)
app_code_runs_as_owner warn the project owner can read or write tables of an app with a migrator: SQL it runs there executes the app’s code with its privileges
app_role_reserved_suffix info an existing app role ends with a reserved suffix (it keeps working)
app_role_exec_secdef warn an app role may run a SECURITY DEFINER function of a user schema (it runs as its owner)
exposed_schema_no_usage warn an exposed app_<slug> schema gives no USAGE to its role
app_schema_shared_with_authenticated / app_schema_shared_with_anon warn an app schema is opened to everyone