ENGINEERING NOTE / 15 POSTGRESQLARCHITECTURE

Row-Level Security as the Second Lock, and the Grants I Kept Out of It

Row-level security is easy to switch on and easy to get subtly wrong. In two multi-tenant apps I'm building in my own time it is the second lock behind the application's checks. The most useful decision was about what not to put in the policies.

10 MIN READ

ROW-LEVEL-SECURITYMULTI-TENANCYSECURITYSCHEMA-DESIGN

TABLE OF CONTENTS
  1. The lock has to apply to everyone who can turn it
  2. Tenant context lives in the transaction, not the connection
  3. FORCE binds the migrator too, and that is the point
  4. The decision: sharing grants stay out of the policies
  5. Constraints see what policies hide
  6. Policies and the planner
  7. Measuring the policy cost
  8. The second app, and the same restraint
  9. What carries over

I’m building two multi-tenant applications in my own time: an asset register and a staffing tool. Both keep every tenant in one shared PostgreSQL database, and both use row-level security (RLS). In neither is RLS the only check. Every operation passes a permission check in the application’s domain layer first. RLS is there for the day that layer has a bug: one forgotten WHERE tenant_id = … should return nothing, not another tenant’s data.

That framing — RLS as the second lock, not the first — shaped most of the choices below. The one I would defend hardest is a refusal: per-person sharing grants are not part of the table policies.

The lock has to apply to everyone who can turn it§

RLS has two well-known escape hatches, and both have to be closed deliberately.

The first is ownership. By default a table’s owner is not subject to its policies. ENABLE ROW LEVEL SECURITY alone does nothing to a connection that owns the tables. So the application roles own nothing. A separate migrator role owns the schema, and every table is set to FORCE ROW LEVEL SECURITY as well, so the policies bind the owner too.

The second is role attributes. Superusers and roles with BYPASSRLS skip policies entirely, and FORCE does not change that. None of the roles the application connects as is a superuser or has BYPASSRLS, and that includes the migrator.

ALTER ROLE app_migrator LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB;
ALTER ROLE app_api      LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB;
ALTER ROLE app_worker   LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB;

ALTER TABLE items ENABLE ROW LEVEL SECURITY;
ALTER TABLE items FORCE  ROW LEVEL SECURITY;

A rule like that is only as good as the next migration that forgets it, so the asset register has schema guard tests that read the catalogue rather than trusting the migration code. Every table in the application schema has to show relrowsecurity and relforcerowsecurity. The only exceptions are written into the test, each with a reason. All three roles have to show rolsuper, rolbypassrls, rolcreaterole and rolcreatedb as false, and every table has to be owned by the migrator.

SELECT relname, relrowsecurity, relforcerowsecurity
FROM   pg_class
WHERE  relnamespace = 'public'::regnamespace
AND    relkind IN ('r', 'p');

There are two exceptions. One is the migration bookkeeping table, which the application roles cannot read at all. The other is the session table, which the API has to look up by a hash of the cookie value before any tenant context exists. Both are named in the test.

Tenant context lives in the transaction, not the connection§

Each transaction starts by setting the caller’s identity from the authenticated session:

SELECT set_config('app.user_id',   $1, true),
       set_config('app.tenant_id', $2, true);

The third argument, is_local = true, makes the setting transaction-local. It is the function form of SET LOCAL, and the staffing tool uses SET LOCAL itself. At commit or rollback the value is gone. That is what makes the design safe behind a pooler in transaction mode: PgBouncer in that mode hands a server connection to a different client after each transaction. A session-level SET would stay on that connection and arrive with the next client’s first query. A transaction-local one cannot.

Policies never read the setting directly. They call a small function:

CREATE FUNCTION app.current_tenant_id() RETURNS uuid
LANGUAGE sql STABLE PARALLEL SAFE
SET search_path = pg_catalog
AS $$ SELECT nullif(current_setting('app.tenant_id', true), '')::uuid $$;

The two details in that one line matter more than they look:

  • current_setting(..., true) returns NULL rather than raising an error when the setting has never been defined.
  • After a transaction-local value has been set once on a connection and that transaction has ended, the setting is usually still defined for the rest of the session, but empty. A pooled connection therefore tends to return '', not NULL. nullif turns both into NULL.

Every policy compares with =, and x = NULL is never true, so a missing or empty context returns zero rows. It is not an error, and it is not everything. A malformed value fails the ::uuid cast and the statement errors, which also fails closed.

CREATE POLICY items_own ON item_ownership FOR SELECT TO app_api, app_worker
  USING (tenant_id = (SELECT app.current_tenant_id()));

Wrapping the call in a scalar subquery turns it into an InitPlan. It runs once per statement instead of being treated as a per-row expression.

VERIFIED What the isolation tests assert, run as the real application roles
no context set                      -> 0 rows, every RLS table, API and worker role
context set to ''                   -> 0 rows, every RLS table
context set to 'not-a-uuid'         -> error (invalid input syntax for type uuid)
same connection, next transaction,
context never set                 -> 0 rows; current_tenant_id() IS NULL
write to another tenant's row       -> insufficient privilege / policy violation

At its first review the asset register had 61 of these isolation tests. They connect as the actual database roles, not as a superuser. One of them reproduces the pooler case directly: the same connection, a new transaction, and no context set.

FORCE binds the migrator too, and that is the point§

FORCE ROW LEVEL SECURITY has a consequence that is easy to miss. The migrator owns the tables, so a SECURITY DEFINER function, which runs as its owner, runs as the migrator. Under FORCE the migrator is subject to policies like everyone else. Without a policy for it, a definer function sees no rows.

The lazy fix would be to give the migrator BYPASSRLS. I didn’t. Instead the migrator gets narrow, per-command policies, each named definer_*, for exactly what definer code needs: insert into the ownership table, select from users, and so on. The policy set then states plainly which tables privileged code may touch, and how.

Each definer function is hardened the same way:

CREATE FUNCTION app.record_first_owner() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
BEGIN
  INSERT INTO public.item_ownership (item_id, tenant_id, valid_from)
  VALUES (NEW.id, NEW.registered_by_tenant_id, NEW.created_at);
  RETURN NULL;
END $$;
  • search_path is pinned on the function, with pg_temp listed explicitly and last. If pg_temp is not listed, PostgreSQL searches it first, and anyone who can create a temporary table could then shadow an unqualified name inside privileged code.
  • Every object is schema-qualified anyway, so the path is a second defence rather than the only one.
  • EXECUTE is revoked from PUBLIC. The default privileges for the migrator revoke it for every new function, and access is granted to specific roles one function at a time.

The schema guard tests check the first and third rules against pg_proc: every SECURITY DEFINER function in the application schema must have a search_path=pg_catalog… entry in proconfig, and PUBLIC must not be able to execute it. Views have to be created with security_invoker = true. Otherwise a view checks permissions as its owner, and with these roles that would mean the migrator.

The decision: sharing grants stay out of the policies§

The asset register has something the staffing tool doesn’t: records that are not purely tenant-owned. An asset outlives a change of owner, so its table policies already reach through an ownership table with an EXISTS. The plan was to add per-person sharing the same way. The current owner shares one asset with one named person until a chosen date, and every policy on the asset, its history, its documents and its fields would gain an EXISTS against a grants table.

I built it differently. The core table policies did not change. A person with a grant reads only through a small set of SECURITY DEFINER functions. Each is keyed on the caller’s user id and returns only selected columns, and only while the grant is active, unexpired, and the sharing tenant is still the current owner.

CREATE FUNCTION app.my_grant(p_grant_id uuid)
RETURNS TABLE (id uuid, item_id uuid, tenant_id uuid, show_history boolean, valid_until date)
LANGUAGE sql STABLE SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
  SELECT g.id, g.item_id, g.tenant_id, g.show_history, g.valid_until
    FROM public.access_grants g
    JOIN public.item_ownership o
      ON o.item_id = g.item_id AND o.tenant_id = g.tenant_id AND o.valid_to IS NULL
   WHERE g.id = p_grant_id
     AND g.grantee_user_id = app.current_user_id()
     AND g.status = 'active'
     AND g.valid_until >= current_date
$$;
REVOKE ALL ON FUNCTION app.my_grant(uuid) FROM PUBLIC;

Every other shared-read function starts from that one and picks its columns explicitly.

The grant tables are tenant-owned and follow the ordinary pattern. Only the granting tenant can see or change them, and only while it is the owner. The grantee has no access to those tables at all. When the grantee is allowed to add an entry, a definer function writes it, setting a column the application role cannot set. A trigger accepts such a row only while there is an active grant that allows entries.

The decision has a cost, and the design record states it:

  • The grantee does not use the ordinary endpoints. There is a separate set for shared items.
  • Every new thing a grantee should see needs a new function.
  • It is scoped to one asset per grant. If grants ever need to cover many assets at once, such as a whole fleet for a service company, the decision has to be reopened and the policy cost measured again.

Constraints see what policies hide§

Ownership is a period, not a flag. The ownership table holds (item_id, tenant_id, valid_from, valid_to), and an exclusion constraint makes overlapping periods for the same asset impossible:

CREATE EXTENSION IF NOT EXISTS btree_gist;

CREATE TABLE item_ownership (
  id          uuid PRIMARY KEY,
  item_id     uuid NOT NULL REFERENCES items (id),
  tenant_id   uuid NOT NULL REFERENCES tenants (id),
  valid_from  timestamptz NOT NULL DEFAULT now(),
  valid_to    timestamptz,
  CHECK (valid_to IS NULL OR valid_to > valid_from),
  CONSTRAINT item_ownership_no_overlap
    EXCLUDE USING gist (item_id WITH =, tstzrange(valid_from, valid_to) WITH &&)
);

btree_gist is needed for the = on a uuid inside a GiST index. The point that matters for RLS is that constraint enforcement does not go through policies. A tenant cannot see another tenant’s ownership rows, but the exclusion check still sees them. “Two current owners” is a constraint violation, not something the application has to avoid by being careful. The ownership table is also read-only to the application roles. The first owner is written by a definer trigger when the asset is registered, and a transfer goes through its own function.

Policies and the planner§

RLS predicates are applied as security barrier quals. The planner will not evaluate a user-supplied condition that uses a function or operator not marked LEAKPROOF before the policy condition, because such a function could reveal values from rows the policy would have filtered out. In practice this means a query’s own conditions can lose index use they would otherwise get.

The staffing tool hit this on its change history. A cursor written as -id > -x would not be used as an index condition under RLS, because the unary minus operator is not leakproof. The fix was in how the query was written, not in the policy. Both apps also repeat the tenant condition in their own queries, even though RLS applies anyway, so the planner can pick the tenant-leading indexes directly. The policy remains the lock. The explicit filter is for the plan.

Measuring the policy cost§

The original plan said to measure the policies on at least 100,000 assets before building anything else on top of them, and to fall back to a denormalised visibility table if they proved too slow. The benchmark seeds 100,000 assets across 200 tenants. One tenant owns a fifth of them, and a tenth of the assets have changed hands once. It then runs the API’s own queries as the application role inside a tenant context. Each figure is the median, over seven runs, of planning time plus execution time from EXPLAIN (ANALYZE).

RESULT RLS benchmark, 100,000 assets / 200 tenants, PostgreSQL 16 in a development container — indicative
query                                                   median
asset list, first page (tenant owning ~18,000 assets)   2.0 ms
asset card by id                                        0.7 ms
another tenant's asset by id (empty result)             0.6 ms
public lookup by token                                  0.4 ms
count(*) of everything the tenant can see               ~95 ms
LIST AND CARD
≈1–2 ms
POLICY REMOVED
28 ms per list
VISIBILITY TABLE
not needed yet

The list and the card came in at about 1–2 ms, so the denormalised visibility table was not needed. The run also found one expensive policy. It let a product model follow the asset to the next owner, and it cost 28 ms on the list. I removed it, and that hand-over will be done by the transfer function instead. After the grants were built as functions, the same benchmark showed the list and the card unchanged within noise. That was the expected result, since the core policies had not changed, but it was measured rather than assumed. The benchmark is rerun on the same container before and after each schema change that touches these paths.

The second app, and the same restraint§

The staffing tool is simpler: every tenant table has a tenant_id defaulting to the current tenant, and a single tenant_isolation policy with the same expression in USING and WITH CHECK. Inserts without a context fail, and reads without one return zero rows. Its own tests check that, along with cross-tenant reads, updates and inserts.

Finer scoping, such as which units a supervisor may see, is enforced in the API for now. Moving it into RLS is deferred until its performance is known. That is the same rule as the grants: a predicate goes into a policy only when it is cheap for every query and simple enough that a mistake in it is not a whole-table leak.

What carries over§

  1. Close both bypasses. The application roles own nothing, FORCE ROW LEVEL SECURITY is set on every table, and no role has BYPASSRLS. Check all three against the catalogue in tests.
  2. Keep context in the transaction. Use set_config(..., true) or SET LOCAL, and read it through a function that turns both “unset” and “empty” into NULL, so a missing context means zero rows.
  3. Treat FORCE on the owner as a feature. Give definer code narrow per-command policies instead of a bypass. Pin search_path with pg_temp last, qualify every object, and revoke EXECUTE from PUBLIC.
  4. Keep policies boring. Tenant equality and ownership belong in them. Exceptions for a few users, like sharing, go in narrow functions that return named columns.
  5. Measure the policies on realistic volume before building on them, and rerun the benchmark when they change.

RLS is valuable because it is indiscriminate: it applies to every query, whoever wrote it. That is also the reason to keep it small. Every clause in a policy is paid for by every query and trusted by every table, so the exceptions belong somewhere narrower.