انتقل إلى المحتوى
شعار أوراباسي
aurabase

Column-level security

Let the public roles read or change only some columns of a table over REST, the SDK and SQL, while row level security keeps deciding which rows. Realtime row events are the exception: they carry every column.

دليل عملي7 د قراءةالمستوى وسيطة

هذه الصفحة غير متوفرة بلغتك بعد. يتم عرضه باللغة الإنجليزية.

Row level security decides which rows a role sees; it cannot hide one column of a visible row. Column privileges can: PostgreSQL lets you grant select, insert, update and references on a list of columns. A request that names a column the role may not use fails with permission denied, whatever the policies say. One path does not check column privileges: Realtime postgres_changes sends the whole row (see Realtime sends whole rows).

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_col_members (a member directory with a public name and a private email), then remove it:

aura db raw "create table sec_col_members (
  id bigint generated always as identity primary key,
  user_id uuid not null default auth.uid(),
  display_name text not null,
  email text not null)"
aura db raw "insert into sec_col_members (user_id, display_name, email) values
  ('00000000-0000-4000-8000-0000000000a1', 'Alice', 'alice@example.com'),
  ('00000000-0000-4000-8000-0000000000b2', 'Bob', 'bob@example.com')"
aura db raw "create policy sec_col_members_read on sec_col_members
  for select to aura_anon, aura_authenticated using (true)"
  ℹ No results (0 rows).
  ℹ No results (0 rows).
  ℹ No results (0 rows).

The policy opens every row to everyone, email included. The rest of the page closes the email column.

Rows are policies, columns are privileges#

A role may use a column if it holds the privilege on that column or on the whole table. Tables created through Aurabase grant every privilege on the whole table to aura_anon and aura_authenticated, so revoking one column has no effect while the table-level grant stays: PostgreSQL 18 documents that revoking a column privilege from a role that holds the table privilege changes nothing. The order is therefore:

  1. revoke the table-level privilege from the public roles;
  2. grant it back on the allowed columns only.

Hide a column from readers#

revoke select on sec_col_members from aura_anon, aura_authenticated;
grant select (id, user_id, display_name) on sec_col_members to aura_anon, aura_authenticated;
  ℹ No results (0 rows).

aura db raw accepts grant and revoke, as do the SQL editor of the Studio and migrations. The service_role key keeps every column: it is not one of the two roles above.

What the API returns#

A request that names only allowed columns works; a request for the hidden column, or for every column, fails with 403:

for select in 'display_name' 'display_name,email' '*'; do
  curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/sec_col_members?select=$select&order=id" -H "apikey: $AURABASE_ANON_KEY" \
  | node -e 'const r = JSON.parse(require("fs").readFileSync(0, "utf8")); console.log(r.error ? `${r.error.code} ${r.error.message} (${r.error.upstream_code})` : JSON.stringify(r.data))'
done
[{"display_name":"Alice"},{"display_name":"Bob"}]
INSUFFICIENT_PRIVILEGE permission denied for table sec_col_members (42501)
INSUFFICIENT_PRIVILEGE permission denied for table sec_col_members (42501)

The message names the table, not the column. With the SDK, select() without arguments asks for *: list the columns instead.

import { createClient } from '@aurabase/aurabase-js'

const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const all = await aura.from('sec_col_members').select()
console.log(all.data, all.error?.status, all.error?.code)

const listed = await aura.from('sec_col_members').select('display_name').order('id')
console.log(listed.data, listed.error)
null 403 INSUFFICIENT_PRIVILEGE
[ { display_name: 'Alice' }, { display_name: 'Bob' } ] null

Realtime sends whole rows#

Column privileges do not apply to Realtime. When a table is enabled for postgres_changes, each INSERT and UPDATE is delivered with all the columns of the new row (record), and the check made for each subscriber only asks whether the role may see that row, not which of its columns. A DELETE carries only the primary key, in old_record, as does the old_record of an UPDATE. A signed-in user who cannot read email over the REST API receives it in the change event:

aura db table realtime sec_col_members on
  ✔ Realtime enabled on 'sec_col_members'.
import { createClient } from '@aurabase/aurabase-js'

const url = process.env.AURABASE_URL!
const user = createClient(url, process.env.AURABASE_ANON_KEY!)
const admin = createClient(url, process.env.AURABASE_SERVICE_ROLE_KEY!)
const email = `colsec-${Date.now()}@example.com`
await user.auth.signUp({ email, password: 'correct-horse-battery-9' })
const { error } = await user.auth.signInWithPassword({ email, password: 'correct-horse-battery-9' })
if (error) throw error

const rest = await user.from('sec_col_members').select('display_name, email')
console.log('REST:', rest.error?.code)

const events: Array<{ new: Record<string, unknown> }> = []
let status = ''
const channel = user.realtime
  .channel('sec-col-members')
  .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'sec_col_members' }, (payload) => events.push(payload))
  .subscribe((s) => { status = s })
for (let i = 0; i < 150 && status !== 'SUBSCRIBED'; i++) await new Promise((r) => setTimeout(r, 200))
await new Promise((r) => setTimeout(r, 2000))

await admin.db.from('sec_col_members').insert({ user_id: '00000000-0000-4000-8000-0000000000b2', display_name: 'Carol', email: 'carol@example.com' })
for (let i = 0; i < 150 && events.length === 0; i++) await new Promise((r) => setTimeout(r, 200))
console.log('Realtime:', Object.keys(events[0]?.new ?? {}).sort().join(', '))

channel.unsubscribe()
user.realtime.disconnect()
REST: INSUFFICIENT_PRIVILEGE
Realtime: display_name, email, id, user_id

Until this changes, do not enable postgres_changes on a table that has columns hidden from the public roles. If it is enabled, turn it off: aura db table realtime <table> off. Keep such columns in a second table, joined by the same id, that is never enabled for Realtime, and enable Realtime on the table of public columns only.

The example signs up a user and signs them in at once. A new project requires email confirmation by default, so on your project the sign-in fails until the user confirms the address; the test project of this page has confirmation turned off (aura auth settings set email_confirmation_required=false).

Restrict the columns a user can change#

The same applies to writes. Here each member may change its own display name, but not its email, and nobody may insert through the API:

revoke insert, update on sec_col_members from aura_anon, aura_authenticated;
grant update (display_name) on sec_col_members to aura_authenticated;
create policy sec_col_members_own_update on sec_col_members
  for update to aura_authenticated
  using (auth.uid() = user_id) with check (auth.uid() = user_id);
  ℹ No results (0 rows).
ALICE=00000000-0000-4000-8000-0000000000a1
aura db raw --as authenticated --user $ALICE "update sec_col_members set display_name = 'Alice M.' where user_id = '$ALICE' returning display_name"
aura db raw --as authenticated --user $ALICE "update sec_col_members set email = 'new@example.com' where user_id = '$ALICE'" || true
  ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1).
  display_name
  ────────────
  Alice M.    

  ℹ 1 row(s).
  ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1).
Error: [400] BAD_REQUEST: Invalid request: permission denied for table sec_col_members

Change protected columns from a server with the service_role key, or through a security definer function that checks what it writes (Database functions).

Check the privileges#

has_column_privilege and has_table_privilege answer for any role, and aura db raw accepts them:

aura db raw "select c.col, has_column_privilege('aura_anon', 'sec_col_members', c.col, 'select') as anon_reads,
  has_column_privilege('aura_authenticated', 'sec_col_members', c.col, 'update') as user_updates
  from (values ('display_name'), ('email')) c(col)"
  anon_reads │ col          │ user_updates
  ───────────┼──────────────┼─────────────
  true       │ display_name │ true        
  false      │ email        │ false       

  ℹ 2 row(s).

Keep the revoke and grant statements in a migration or a script that you run again: according to the code of the provisioner, Aurabase re-applies its default grants to your schema when it upgrades the internal schemas of a project, which would grant the table-level privileges again and make hidden columns readable (read in the code, not reproduced for this page). Run this check after each platform upgrade, or in CI (Test RLS in CI). Roles and privileges explains the default grants.

Other ways to hide columns#

OptionBehavior on Aurabase
Column privilegesThe columns are refused to the role over REST, the SDK, SQL run as that role and views read by that role. Not over Realtime: a table enabled for postgres_changes sends whole rows.
RealtimeSends every column of a changed row to each subscriber allowed to see the row. Never enable it on a table with hidden columns.
A view of the allowed columnsViews run with the caller's rights (security_invoker = true is set on them), so the caller still needs the privileges on the columns of the table: a view gives a name to the allowed columns but does not replace the privileges. A view with security_invoker = false would bypass the policies of the table: never use one for this (Views).
A security definer functionReturns exactly the columns it selects, for the rows it filters with auth.uid(). Suits a computed or partial answer ("my profile", "public card of a member").
Two tablesMove private columns to a second table with its own policies, joined by the same id. Often the clearest design for data such as emails or phone numbers. Keep the private table out of Realtime: then its columns never appear in change events, while the public table can stay enabled.

Result#

aura db raw "select display_name, email from sec_col_members order by id"
  display_name │ email            
  ─────────────┼──────────────────
  Alice M.     │ alice@example.com
  Bob          │ bob@example.com  
  Carol        │ carol@example.com

  ℹ 3 row(s).

The service_role key reads both columns, including the row added for the Realtime example; the public roles read the name only, and Alice changed her name but not her email.

Common errors#

MessageCauseFix
403 INSUFFICIENT_PRIVILEGE, permission denied for table … on a readThe request asks for a column the role may not read, often select=* or select() without arguments.List the allowed columns.
403 INSUFFICIENT_PRIVILEGE, permission denied for table … on an updateThe update sets a column without update privilege for the role.Send allowed columns only; change the others from a server.
The hidden column is still readableThe table-level privilege was not revoked first, a platform upgrade granted it again, or the reader receives it in a Realtime postgres_changes event, which carries every column.Revoke at table level, then grant the columns; check with has_column_privilege. Turn Realtime off on the table (aura db table realtime <table> off).
A view of the allowed columns fails with permission deniedThe view runs with the caller's rights and reads a revoked column.Select only allowed columns in the view.

Clean up#

aura db table realtime sec_col_members off
aura db raw "drop table sec_col_members"
  ✔ Realtime disabled on 'sec_col_members'.
  ℹ No results (0 rows).

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ الإبلاغ عن مشكلة