Перейти к содержимому
Логотип Аурабаза
аурабаза

Multi-tenant schema design

Pick how your customers' data is separated: one project per customer, or shared tables filtered by row level security, from a tenant claim in the user's token or from a membership table, and test that no tenant reads another's rows.

Практическое руководство10 мин читатьУровень передовой

Эта страница пока недоступна на вашем языке. Оно показано на английском языке.

A multi-tenant application serves several customers (tenants) and must never show one customer's rows to another. On Aurabase, the separation is either structural (a project per customer) or done by row level security on shared tables. A schema per customer inside one project is not available: a project has one schema, and create schema is refused.

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 tables sch_mt_notes and sch_mt_projects and the function sch_mt_is_member, sign up test users, then remove what they created. The sign-ups work because email confirmation is turned off on the test project; a project requires it by default.

Choose a pattern#

PatternSeparationFitsLimits
Tenant claim: a tenant_id column and the claim app_metadata.tenant of the user's token, read by auth.tenant()Row level securityOne user belongs to one tenant; many small tenantsA user changing tenant needs a new token; one tenant per user
Membership table: a table of (org, user, role) and a function that checks itRow level securityUsers in several organizations, roles per organizationOne more lookup per policy check; index the membership table
One project per customerSeparate database schema, keys, quotas and backups per customerFew large customers, data residency, contractual isolationEach project is created, migrated and paid for separately; no query across customers
A schema per customer in one projectNot available: create schema is refused by aura db raw and reserved to the platform

The first two can be combined: the claim for the default tenant, the membership table for users invited elsewhere.

Shared tables with a tenant claim#

auth.tenant() returns the tenant key of the user's app_metadata claim as a uuid, or null when it is absent or not a uuid. Only the service_role key can set app_metadata (users can edit their user_metadata, never app_metadata), so a user cannot choose its tenant. Give the table a tenant_id filled by default from the claim, and a policy that compares both:

create table sch_mt_notes (
  id bigint generated always as identity primary key,
  tenant_id uuid not null default auth.tenant(),
  body text not null
);

create index sch_mt_notes_tenant on sch_mt_notes (tenant_id);

create policy sch_mt_notes_tenant on sch_mt_notes
  for all to aura_authenticated
  using (tenant_id = auth.tenant())
  with check (tenant_id = auth.tenant());

insert into sch_mt_notes (tenant_id, body)
  values ('22222222-2222-4222-8222-222222222222', 'Note of another tenant');
  ℹ No results (0 rows).

Set the claim from a server with the admin API, then sign the user in again: the claim is read from the token, and a token issued before the change does not carry it.

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

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)

const email = `tenant-${Date.now()}@example.com`
const password = 'correct-horse-battery-9'
const signUp = await aura.auth.signUp({ email, password })
if (signUp.error) throw signUp.error
const first = await aura.auth.signInWithPassword({ email, password })
if (first.error) throw first.error

const before = await aura.from('sch_mt_notes').insert({ body: 'No tenant yet' })
console.log('before the claim:', before.error?.status, before.error?.code)

const updated = await admin.authAdmin.updateUser(first.data!.user.id, {
  app_metadata: { tenant: '11111111-1111-4111-8111-111111111111' },
})
console.log('claim set:', updated.error)

const again = await aura.auth.signInWithPassword({ email, password })
if (again.error) throw again.error

const inserted = await aura.from('sch_mt_notes').insert({ body: 'Note of my tenant' }).select('tenant_id, body')
console.log('insert:', inserted.data, inserted.error)

const visible = await aura.from('sch_mt_notes').select('body')
console.log('visible:', visible.data, visible.error)

const forged = await aura.from('sch_mt_notes').insert({ tenant_id: '22222222-2222-4222-8222-222222222222', body: 'Forged' })
console.log('forged:', forged.error?.status, forged.error?.code)
before the claim: 403 INSUFFICIENT_PRIVILEGE
claim set: null
insert: [
  {
    tenant_id: '11111111-1111-4111-8111-111111111111',
    body: 'Note of my tenant'
  }
] null
visible: [ { body: 'Note of my tenant' } ] null
forged: 403 INSUFFICIENT_PRIVILEGE

Without the claim, auth.tenant() is null and the policy refuses the write. With it, the row takes the tenant of the token, the other tenant's note stays invisible, and a row sent with another tenant_id is refused by with check. In your own sign-up flow, set app_metadata.tenant from a server right after creating the user (invitation, admin action), or from the custom access token hook of Auth.

Shared tables with a membership table#

When a user can belong to several organizations, keep the memberships in a table, like org_members (org_id, user_id, role) of the example schema, and check membership in the policy. Put the check in a security definer function: the policy then works even though users cannot read org_members themselves, and the membership table is not queried through its own policies at each row.

aura db raw "create table sch_mt_projects (
  id bigint generated always as identity primary key,
  org_id bigint not null references orgs (id) on delete cascade,
  name text not null)"
aura db raw "create index sch_mt_projects_org on sch_mt_projects (org_id)"

aura db function create sch_mt_is_member --language sql --returns boolean \
  --args "p_org:bigint" \
  --body 'select exists (select 1 from org_members where org_id = p_org and user_id = auth.uid())' \
  --security definer --grant-execute-to authenticated

aura db raw "create policy sch_mt_projects_members on sch_mt_projects
  for select to aura_authenticated using (sch_mt_is_member(org_id))"

aura db raw "insert into orgs (slug, name) values ('sch-mt-globex', 'Globex')"
aura db raw "insert into sch_mt_projects (org_id, name)
  select id, slug || ' roadmap' from orgs where slug in ('acme', 'sch-mt-globex')"
  ℹ No results (0 rows).
  ℹ No results (0 rows).
  ✔ Function 'sch_mt_is_member' created (sql → boolean).
  • EXECUTE granted to: authenticated
  ⚠ SECURITY DEFINER: function executes with its owner's privileges, not the caller's.
  ℹ No results (0 rows).
  ℹ No results (0 rows).
  ℹ No results (0 rows).

The function only answers "is the caller a member of this org": it reveals nothing else, filters on auth.uid(), and is granted to signed-in users only. A new user sees no project until a server adds it to an organization:

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

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)

const email = `member-${Date.now()}@example.com`
const password = 'correct-horse-battery-9'
const signUp = await aura.auth.signUp({ email, password })
if (signUp.error) throw signUp.error
const { data: session, error } = await aura.auth.signInWithPassword({ email, password })
if (error) throw error

const none = await aura.from('sch_mt_projects').select('name')
console.log('before:', none.data, none.error)

const acme = await admin.db.from('orgs').select('id').eq('slug', 'acme').single()
const joined = await admin.db.from('org_members').insert({ org_id: (acme.data as { id: number }).id, user_id: session!.user.id, role: 'member' })
console.log('joined:', joined.error)

const mine = await aura.from('sch_mt_projects').select('name')
console.log('after:', mine.data, mine.error)
before: [] null
joined: null
after: [ { name: 'acme roadmap' } ] null

Roles per organization follow the same idea: a function such as has_org_role(p_org, 'admin') reads org_members.role, and the write policies call it. For roles that hold across the whole project, auth.has_role('<role>') reads the roles array of app_metadata.

One project per customer#

Each project has its own schema in its own database, its own API keys, its own users and its own quotas: a key of one project cannot reach another (Project isolation). Create a project per customer with aura projects create, apply the same migrations to each, and route each customer to its project URL and keys. You give up queries across customers and take on one migration run per project; in exchange, a policy mistake cannot leak data between customers, and each customer can be backed up, restored or deleted alone.

Checklist for shared tables#

CheckWhy
Every tenant table has a tenant_id (or org_id) column, not null, indexedPolicies filter on it at each query; without an index, each read scans the table.
Every tenant table has row level security and policies for each command it servesTables created by Aurabase have row level security on; a table without a policy is closed, a policy with using (true) is open to every tenant.
with check repeats the tenant condition on insert and update policiesOtherwise a user writes rows into another tenant.
Foreign keys between tenant tables stay inside the tenantA row of tenant A must not point to a row of tenant B; check it in the policy or with a composite key (tenant_id, id).
Views are security invoker, materialized views are revoked from aura_anon and aura_authenticatedA materialized view or a security_invoker = false view ignores row level security (Views and materialized views).
security definer functions filter on auth.uid() or auth.tenant() themselvesThey bypass row level security.
Tests sign in as users of two tenants and check that each sees only its rowsThe only proof that the policies do what you think. aura db raw --as authenticated --user <uuid> helps for membership checks; the tenant claim needs a real token, as in the example above.

Result#

The service role sees the rows of every tenant; each user saw only its own:

aura db raw "select tenant_id, body from sch_mt_notes order by id"
aura db raw "select name from sch_mt_projects order by name"
  body                   │ tenant_id
  ───────────────────────┼─────────────────────────────────────
  Note of another tenant │ 22222222-2222-4222-8222-222222222222
  Note of my tenant      │ 11111111-1111-4111-8111-111111111111

  ℹ 2 row(s).
  name
  ─────────────────────
  acme roadmap
  sch-mt-globex roadmap

  ℹ 2 row(s).

Common errors#

MessageCauseFix
403 INSUFFICIENT_PRIVILEGE new row violates row-level security policy for table "…"The user's token has no tenant claim, or the row's tenant_id differs from it.Set app_metadata.tenant, sign in again, and let the default fill tenant_id.
An empty array for a user who should see rowsNo membership row, an old token without the claim, or no select policy.Check org_members, sign in again, add the policy.
403 INSUFFICIENT_PRIVILEGE permission denied for function …The membership function is not granted to authenticated.--grant-execute-to authenticated.
Operation not allowed in a raw query: 'CREATE SCHEMA'. (…)A schema per tenant attempted with aura db raw.Use a tenant column or a project per customer.
infinite recursion detected in policy for relation "…" (400 RECURSIVE_POLICY)A policy on the membership table queries the membership table.Check membership in a security definer function, as above.

Clean up#

aura db table drop sch_mt_projects --force
aura db table drop sch_mt_notes --force
aura db function drop sch_mt_is_member --force
aura db raw "delete from orgs where slug = 'sch-mt-globex'"
aura db raw "delete from org_members where user_id not in ('00000000-0000-4000-8000-0000000000a1', '00000000-0000-4000-8000-0000000000b2')"
  ✔ Table 'sch_mt_projects' dropped.
  ✔ Table 'sch_mt_notes' dropped.
  ✔ Function 'sch_mt_is_member' dropped (or already absent).
  ℹ No results (0 rows).
  ℹ No results (0 rows).

org_members.user_id has no foreign key to the users of Auth, so deleting a user leaves its memberships: the last command removes the one added for the test user. Delete the test users themselves with aura auth users delete <user-id>.

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ Сообщить о проблеме