skip to content

schemas, roles and row-level security

search_path, GRANT, and policies that filter rows per tenant without a single WHERE.

address
everything.design.schemas_roles_and_rls
part
part 7, schema design
chapter
chapter 13 of 13
reading time
8 min

a schema is a namespace inside a database (public, sales.orders), and the search_path decides which schema an unqualified name means, which is also a classic security hole. roles are users and groups at once, and GRANT gives them rights on objects.

row-level security goes one step further: a policy on a table adds a condition to every query, so a tenant only ever sees its own rows, without a single WHERE in the app. USING filters what you can see and touch, WITH CHECK what you may write. table owners skip policies unless you FORCE them; superusers and BYPASSRLS roles always skip them.

the picture

you know the multi-tenant app where every query ends in AND tenant_id = $1, and one day one of them doesn't? that's a data leak written as a missing line. RLS moves the line into the table, where no query can forget it.

think of an office building (a database). floors are schemas, rooms are tables. a key card (a role) opens some floors and some rooms (GRANT). row-level security is a filing cabinet in the room that only shows each visitor the folders with their company's name on them, whatever drawer they open.

  • one postgres server
  • ├── rolesusers and groups, shared by every database
  • └──
  • ├── schema pg_catalogthe built-in types, functions and catalog tables
  • ├── where unqualified names go by default
  • │ ├── customers
  • │ └── orders
  • └── another namespace: reporting.orders is a different table
  • └── orders
what lives where. roles belong to the whole cluster, everything else to one database. click a node to fold it.

schemas and search_path

an unqualified name like orders is looked up in the schemas of the search_path, in order, and the first match wins. pg_catalog is always searched (first, unless you place it), and so is your temporary schema:

sqlempty db
CREATE SCHEMA reporting;
CREATE TABLE public.orders (id int, note text);
CREATE TABLE reporting.orders (id int, note text);
INSERT INTO public.orders VALUES (1, 'the live table');
INSERT INTO reporting.orders VALUES (1, 'last night''s copy');
 
SELECT current_schemas(true) AS searched, note FROM orders;
SET search_path = reporting, public;
SELECT current_schemas(true) AS searched, note FROM orders;
output, from postgres 18.6
#1 · CREATE SCHEMA
#2 · CREATE TABLE
#3 · CREATE TABLE
#4 · INSERT 0 1
#5 · INSERT 0 1
#6 · SELECT 1
searchedname[]notetext
{pg_catalog,public}the live table
(1 row)
#7 · SET
#8 · SELECT 1
searchedname[]notetext
{pg_catalog,reporting,public}last night's copy
(1 row)

same query, different table. that's useful (a staging schema that shadows production for a test run) and it's also the footgun.

hover a stage.

how postgres resolves lower(name), a function call: it collects every lower on the path, then picks the best match for the argument types. path order only breaks ties.

so anyone who can create a function in a schema on your path can hijack a call to a built-in by offering a better-typed one:

sqlempty db
CREATE TABLE people (name varchar(40));
INSERT INTO people VALUES ('Ada Lovelace');
SELECT lower(name) FROM people;
 
-- someone with CREATE on public adds this:
CREATE FUNCTION public.lower(varchar) RETURNS text LANGUAGE sql AS $$ SELECT 'gotcha: ' || $1 $$;
 
SELECT lower(name) FROM people;
SELECT pg_catalog.lower(name) FROM people;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · SELECT 1
lowertext
ada lovelace
(1 row)
#4 · CREATE FUNCTION
#5 · SELECT 1
lowertext
gotcha: Ada Lovelace
(1 row)
#6 · SELECT 1
lowertext
ada lovelace
(1 row)

this is CVE-2018-1058, and the real attack is worse: a function that runs with the caller's rights does whatever the attacker wrote, as you. the defences: since postgres 15, ordinary users no longer get CREATE on the public schema by default; SECURITY DEFINER functions should always SET search_path (to pg_catalog, pg_temp plus what they need); and code that runs with privileges should schema-qualify what it calls.

roles and GRANT

a role is a user if it can log in, a group if others are members of it, and often both. nothing is visible to a new role except what's been granted (and what's granted to PUBLIC, everyone):

sqlempty db
CREATE TABLE prices (sku text PRIMARY KEY, price numeric(8,2));
INSERT INTO prices VALUES ('TEA-01', 6.50);
CREATE ROLE grants_reader;
 
SET ROLE grants_reader;
SELECT * FROM prices;
CREATE TABLE public.scratch (x int);
RESET ROLE;
 
GRANT SELECT ON prices TO grants_reader;
SET ROLE grants_reader;
SELECT sku, price FROM prices;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · CREATE ROLE
#4 · SET
#5 · ERROR 42501
ERROR 42501: permission denied for table prices
#6 · ERROR 42501
ERROR 42501: permission denied for schema public
7 │ CREATE TABLE public.scratch (x int);
at line 7, column 14
#7 · RESET
#8 · GRANT
#9 · SET
#10 · SELECT 1
skutextpricenumeric
TEA-016.50
(1 row)

denied, then denied again (no CREATE on public, the postgres 15 default), then allowed. the layers: USAGE on a schema to see into it at all, then table rights (SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER), optionally per column. ALTER DEFAULT PRIVILEGES sets what tables created later get, so a reader role doesn't lose access every time a migration adds a table. the usual layout: an owner role that runs migrations and owns everything, an app role with only DML, a read-only role for reporting, and nobody connecting as a superuser.

row-level security

enable it on a table, add policies, and every query against that table gets the policy's condition added, for every role it applies to. here the condition reads the tenant from a setting the app sets per connection or transaction (SET app.tenant = 'acme'):

sql
ALTER TABLE notes ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_rows ON notes USING (tenant = current_setting('app.tenant', true));
as =
notes.sql
  1. 1SET app.tenant = 'acme';
  2. 2SET ROLE rls_clerk;
  3. 3SELECT id, tenant, body FROM notes ORDER BY id;
the result for clerk, tenant acme
idint4tenanttextbodytext
1acmerenew the lease
2acmeorder teapots
(2 rows)

the clerk, working for acme. no WHERE in the query; the policy adds one.

real output, postgres 18.6 (PGlite 0.5.12) · rls
the same SELECT ... FROM notes, as different roles. the clerk sees only its tenant's rows, and nothing with no tenant set (a NULL setting makes the policy never true). writing a row for another tenant is refused. the owner skips the policy until FORCE; a BYPASSRLS role and the superuser always skip it. every run is real, in this page's engine.

USING and WITH CHECK

a policy has two expressions. USING decides which existing rows a command can see: rows SELECT returns, and rows UPDATE and DELETE can touch. WITH CHECK decides which new rows may be written by INSERT and UPDATE. if a policy gives only USING, it's used for both, which is why the acme clerk couldn't insert a globex note.

predict the output
sql
CREATE POLICY see_own ON notes FOR SELECT
  USING (tenant = current_setting('app.tenant', true));
CREATE POLICY write_any ON notes FOR INSERT
  WITH CHECK (true);
-- as the acme clerk:
INSERT INTO notes VALUES (5, 'globex', 'hello');

the run below builds exactly those two policies and does it:

sqlempty db · session rls
CREATE ROLE rls_writer;
CREATE TABLE notes (id int PRIMARY KEY, tenant text NOT NULL, body text NOT NULL);
GRANT SELECT, INSERT ON notes TO rls_writer;
ALTER TABLE notes ENABLE ROW LEVEL SECURITY;
CREATE POLICY see_own ON notes FOR SELECT USING (tenant = current_setting('app.tenant', true));
CREATE POLICY write_any ON notes FOR INSERT WITH CHECK (true);
 
SET app.tenant = 'acme';
SET ROLE rls_writer;
INSERT INTO notes VALUES (5, 'globex', 'hello');
SELECT count(*) AS visible_to_me FROM notes;
RESET ROLE;
SELECT count(*) AS really_there FROM notes;
output, from postgres 18.6
#1 · CREATE ROLE
#2 · CREATE TABLE
#3 · GRANT
#4 · ALTER TABLE
#5 · CREATE POLICY
#6 · CREATE POLICY
#7 · SET
#8 · SET
#9 · INSERT 0 1
#10 · SELECT 1
visible_to_meint8
0
(1 row)
#11 · RESET
#12 · SELECT 1
really_thereint8
1
(1 row)

multiple policies for the same command are combined with OR (permissive, the default); AS RESTRICTIVE policies are ANDed on top, for rules like "and never rows marked archived".

who skips the policies

  • superusers, always.
  • roles with BYPASSRLS, always. meant for backups and auditors; pg_dump fails rather than silently dumping a filtered table unless it runs as one.
  • the table owner, unless the table has FORCE ROW LEVEL SECURITY. migrations usually run as the owner, and so does any app that connects as the owner, which is the common way RLS ends up doing nothing.
  • and anything reached through a view runs as the view's owner, unless the view is security_invoker (views).

policies cost what their condition costs: tenant = current_setting(...) is added to every scan, so the table wants an index that leads with tenant (and the planner treats current_setting as stable, so it can use it). a policy with a subquery runs that subquery for queries on the table, which can get expensive. and DDL like ALTER TABLE ... ENABLE ROW LEVEL SECURITY takes an ACCESS EXCLUSIVE lock, so on a busy table it waits in the lock queue like any other migration.

keylines

  • a schema is a namespace; search_path picks which one an unqualified name means.
  • a better-typed function earlier or later on the path wins: SET search_path in privileged functions.
  • roles get nothing until granted; since 15, not even CREATE on public.
  • RLS policies add a condition to every query: USING for rows you see, WITH CHECK for rows you write.
  • owners skip policies unless FORCE; superusers and BYPASSRLS roles always do.