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

Policies: create, change and drop

Create the policies that decide which rows each role reads and writes, change their expressions without a gap, drop them, and pick the door that supports what your policy needs.

ハウツーガイド10 分 読み取りレベル 中間

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

A policy is a rule attached to one table: for one command (or all), for some roles, it says which rows are visible (using) and which new rows are acceptable (with check). This page writes the policies of a small articles table: everyone reads published articles, signed-in users manage their own, and anonymous sign-ins cannot write. Row-level security explains what policies do and do not protect.

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 docs

    It creates profiles, orgs, org_members, posts, todos, the view open_todos and the function todo_count(p_user uuid). See Example schema.

The examples create the table sec_pol_articles and its policies, then remove them. All the doors below require the service_role key (or a Studio session); the anon key gets 403 FORBIDDEN, DDL operation is reserved to the service_role role.

aura db raw "create table sec_pol_articles (
  id bigint generated always as identity primary key,
  user_id uuid not null default auth.uid(),
  title text not null,
  published boolean not null default false)"
aura db raw "insert into sec_pol_articles (user_id, title, published) values
  ('00000000-0000-4000-8000-0000000000a1', 'Alice, published', true),
  ('00000000-0000-4000-8000-0000000000a1', 'Alice, draft', false),
  ('00000000-0000-4000-8000-0000000000b2', 'Bob, draft', false)"
  ℹ No results (0 rows).
  ℹ No results (0 rows).

Where to write a policy#

SQL (aura db raw, SQL editor, migrations)aura db policyHTTP /v1/db/{project_id}/policiesStudio, RLS policies tab
Target roles (to …)Any roleNone: the policy applies to every role (public)target_roles: anon, authenticated, service_role or their aura_ namesCheck boxes: authenticated, anon, service_role; none checked means every role
Subqueries (exists (select …))YesRefusedRefusedRefused (it calls the HTTP API)
as restrictiveYesNoNoNo
Change expressions in placealter policyaura db policy updatePUT …/policies/{name}/{table}No (drop and create)

Use SQL in migrations: it is the only door that has every option, and the file replays the same way on every environment. The CLI and the HTTP API suit quick rules that need no subquery; call a function for anything that reads another table (see Common policies).

Parts of a policy#

create policy <name> on <table>
  [as permissive | as restrictive]          -- permissive by default
  for all | select | insert | update | delete
  to <role>, …                              -- every role (public) if omitted
  using (<which existing rows>)
  with check (<which new rows>)

Which expression each command evaluates:

Commandusingwith check
selectRows the role readsNot allowed
insertNot allowedRows the role may insert
updateRows the role may update (the row before the change)The row after the change; using is reused when omitted
deleteRows the role may deleteNot allowed
allAll of the aboveInserts and updates; using is reused when omitted

A policy only names a role; the role still needs the privilege on the table. Tables created through Aurabase grant all table privileges to aura_anon and aura_authenticated, so in practice the policies decide. See Roles and privileges.

With the CLI#

aura db policy add <table> <name> <command> creates a policy, with --using-expr and --check-expr. It has no option for roles: the policy applies to every role. That fits a public read rule:

aura db policy add sec_pol_articles sec_pol_articles_published SELECT --using-expr "published"
aura db policy list --table sec_pol_articles --json
  ✔ Policy 'sec_pol_articles_published' created on 'sec_pol_articles' (SELECT).
  • USING: published
[
  {
    "check_expr": null,
    "command": "SELECT",
    "policy_name": "sec_pol_articles_published",
    "roles": [
      "public"
    ],
    "table_name": "sec_pol_articles",
    "using_expr": "published"
  }
]

roles: ["public"] means every role, anon included. The table output of aura db policy list does not show the roles; use --json to see them. --table filters one table; without it, the list hides the internal Storage policies, which --all adds.

Over HTTP#

POST /v1/db/{project_id}/policies takes the table, the name, the command, the two expressions and the roles. This policy lets signed-in users manage their own articles:

curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/policies" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
  -d '{"table": "sec_pol_articles", "name": "sec_pol_articles_owner", "command": "ALL",
       "using_expr": "auth.uid() = user_id", "check_expr": "auth.uid() = user_id",
       "target_roles": ["authenticated"]}'
echo
curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/policies" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  | node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data
    for (const p of d.filter((p) => p.table_name === "sec_pol_articles")) console.log(p.policy_name, p.command, p.roles.join(","))'
{"data":null,"meta":null}
sec_pol_articles_owner ALL aura_authenticated
sec_pol_articles_published SELECT public
FieldRequiredValues
tableYesA table of your schema; the five Storage tables (storage_buckets, storage_objects…) target the Storage schema of the project
nameYesA plain identifier: letters, digits and _
commandYesSELECT, INSERT, UPDATE, DELETE or ALL, any case
using_expr, check_exprNoAn SQL expression; an empty string is ignored
target_rolesNoanon, authenticated, service_role, aura_anon, aura_authenticated, aura_service_role; the short names are translated to the aura_ roles. Omitted or empty: every role.

The CLI, the HTTP API and the Studio check each expression before running it, and refuse:

  • ;, comments (--, /*) and dollar quoting ($$, $tag$);
  • the words select, insert, update, delete, with, create, drop, alter, truncate, grant, revoke, execute, copy, import, export and load, so no subquery;
  • a list of functions: file and large-object access, dblink, pg_sleep, set_config, pg_notify, the *_to_xml family, and string builders such as format, concat, replace or encode;
  • any qualified name other than auth.<function>, so no public.my_function() and no other_schema.table.

A policy that must read another table calls a function of your schema instead, unqualified: is_member(org_id).

In SQL#

SQL has no such checks beyond those of aura db raw and accepts every option. A restrictive policy is combined with and with the others: this one keeps users who signed in anonymously from writing, whatever the other policies allow:

create policy sec_pol_articles_no_anonymous_writes on sec_pol_articles
  as restrictive
  for insert to aura_authenticated
  with check (not auth.is_anonymous());
  ℹ No results (0 rows).

How policies combine#

For a given table, command and role, PostgreSQL 18 combines the policies this way: at least one permissive policy must let the row through (they are joined with or), and every restrictive policy must also let it through (joined with and). With no permissive policy, nothing is allowed. Policies for other roles or other commands do not apply.

The articles table now has a public select policy and an owner all policy for signed-in users. Alice reads the published article of everyone, plus her own draft; a visitor reads published articles only:

aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select title from sec_pol_articles order by title"
aura db raw --as anon "select title from sec_pol_articles order by title"
  ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1).
  title           
  ────────────────
  Alice, draft    
  Alice, published

  ℹ 2 row(s).
  ℹ Executed as anon.
  title           
  ────────────────
  Alice, published

  ℹ 1 row(s).

Bob's draft stays hidden from both: no permissive policy matches it.

Common policies#

NeedPolicy
Each user its own rowsfor all to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id)
Everyone reads some rowsfor select to aura_anon, aura_authenticated using (published). See Public read access.
Signed-in users read everythingfor select to aura_authenticated using (true)
Members of an organizationfor select to aura_authenticated using (is_member(org_id)), with is_member a security definer function that reads the membership table. See Multi-tenant schema design.
One tenant per userusing (tenant_id = auth.tenant()), the tenant set in app_metadata from a server. See Multi-tenant schema design.
A role you assignusing (auth.has_role('editor')), the roles set in app_metadata.roles from a server
Block a kind of user everywhereA restrictive policy, as above

Avoid auth.role() in expressions: it returns aura_authenticated through the SDK and authenticated through aura db raw --as and the simulator, so the same policy behaves differently depending on who calls. The to clause is the reliable way to target a role.

Change and drop a policy#

aura db policy update runs alter policy: the table keeps its rule while the expression changes, unlike a drop followed by a create. Omitted clauses stay as they are.

aura db policy update sec_pol_articles sec_pol_articles_published --using-expr "published and title <> ''"
aura db policy delete sec_pol_articles sec_pol_articles_no_anonymous_writes --force
  ✔ Policy 'sec_pol_articles_published' updated on 'sec_pol_articles'.
  • USING: published and title <> ''
  ℹ Omitted clauses are left AS IS (ALTER POLICY only rewrites what is provided).
  ✔ Policy 'sec_pol_articles_no_anonymous_writes' deleted from 'sec_pol_articles'.

Over HTTP, PUT /v1/db/{project_id}/policies/{policy_name}/{table} takes using_expr and check_expr (at least one), and DELETE on the same path drops the policy. The drop uses if exists: an unknown name returns 200 and changes nothing, so check the name, then list the policies:

curl -s -X PUT "$AURABASE_URL/v1/db/$PROJECT_ID/policies/sec_pol_articles_owner/sec_pol_articles" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
  -d '{"check_expr": "auth.uid() = user_id and title <> '"''"'"}'
echo
curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/policies/sec_pol_no_such_policy/sec_pol_articles" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY"
echo
{"data":null,"meta":null}
{"data":null,"meta":null}

In SQL: alter policy … using (…) and drop policy … on …. Without --force, aura db policy delete asks for confirmation and stops when it has no terminal.

Result#

aura db policy list --table sec_pol_articles
» RLS Policies
  Table                     Policy                    Cmd        USING Expression
  -------------------------------------------------------------------------------------
  sec_pol_articles          sec_pol_articles_owner    ALL        (auth.uid() = user_id)
  sec_pol_articles          sec_pol_articles_published SELECT     (published AND (title <> ''::text))

  ℹ 2 policy(ies).

PostgreSQL stores the expressions in its own normalized form, which is what the list shows.

Common errors#

The refusals of the CLI and the HTTP API, measured:

aura db policy add sec_pol_articles sec_pol_x SELECT --using-expr "user_id in (select user_id from org_members)" || true
aura db policy add sec_pol_articles sec_pol_articles_published SELECT --using-expr "true" || true
aura db policy add sec_pol_articles sec_pol_x READ --using-expr "true" || true
Error: [400] BAD_REQUEST: Invalid request: Invalid USING expression: the SQL keyword 'SELECT' is not allowed in policy expressions — subqueries are not permitted
Error: [400] BAD_REQUEST: Invalid request: policy "sec_pol_articles_published" for table "sec_pol_articles" already exists
Error: Invalid command 'READ'. Valid: SELECT, INSERT, UPDATE, DELETE, ALL
MessageCauseFix
Invalid USING expression: the SQL keyword 'SELECT' is not allowed in policy expressions — subqueries are not permittedA subquery through the CLI, the HTTP API or the Studio.Call a function, or create the policy in SQL.
Invalid USING expression: cross-schema references are not allowed ('…') — only the 'auth.' prefix is permittedA qualified name such as public.f().Drop the schema prefix.
policy "…" for table "…" already existsThe name is taken on that table.update it, or choose another name.
relation "project_….…" does not existUnknown table.Check the name with aura db table list.
Role 'admin' non autorise. Valeurs acceptees : …target_roles outside the six accepted names (the message is partly in French).Use anon, authenticated or service_role.
At least one expression (USING or WITH CHECK) is requiredPUT without expression.Send using_expr or check_expr.
policy "…" for table "…" does not existPUT on an unknown policy.List the policies; names are case-sensitive.
only WITH CHECK expression allowed for INSERTusing on an insert policy (PostgreSQL).Use with check.
infinite recursion detected in policy for relation "…"A policy that queries its own table, written in SQL.Move the check into a security definer function.

Clean up#

Dropping the table drops its policies:

drop table sec_pol_articles;
  ℹ No results (0 rows).

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ 問題を報告する