Designing PostgreSQL RLS with permissive and restrictive policies
PostgreSQL RLS policies do not compete for precedence. For each command and role, PostgreSQL gathers the applicable policies and combines them by policy mode: permissive policies form an OR group, while restrictive polic
PostgreSQL RLS policies do not compete for precedence. For each command and role, PostgreSQL gathers the applicable policies and combines them by policy mode: permissive policies form an OR group, while restrictive policies form an AND group. The effective decision is therefore βat least one permissive rule passes, and every restrictive rule passes.β
A small tenant-records design makes the distinction concrete. Put tenant ownership in a permissive policy: it establishes the rows the current caller may consider. Put the active-record requirement in a restrictive policy: it narrows those candidate rows so archived records remain unavailable. A row belonging to the tenant but marked inactive is denied; an active row in another tenant is also denied.
This choice is useful when access has both an additive baseline and a non-negotiable constraint. Additional permissive policies can widen the candidate set for a role or use case. Additional restrictive policies can add guards that all must hold. But restrictive policies cannot grant access on their own: without an applicable permissive policy that passes, RLS default-denies.
The same composition rule matters differently for reads and writes. USING controls whether an existing row is visible or may be targeted. WITH CHECK controls whether the proposed row is allowed after a write. An UPDATE against another tenantβs row can be filtered out at the existing-row stage, while an update that changes an otherwise visible row into an inactive row can fail the proposed-row check.
The accompanying fixture models this boolean behavior rather than executing a PostgreSQL server. It is useful for making expected outcomes explicit, but it does not prove SQL parsing, roles and ownership bypasses, planner behavior, triggers, cross-table race conditions, or live database enforcement. Use it to reason about policy algebra; validate the complete security design in the actual database as well.
Working example
export const proofBoundary =
'This module models the documented Boolean composition of applicable RLS policies. It does not execute PostgreSQL, prove privileges, SQL parsing, triggers, or a live database policy decision.';
export function createExamplePolicies() {
return [
{
name: 'tenant_access',
mode: 'PERMISSIVE',
command: 'ALL',
using: (row, actor) => row.tenantId === actor.tenantId,
check: (row, actor) => row.tenantId === actor.tenantId,
},
{
name: 'active_records_only',
mode: 'RESTRICTIVE',
command: 'ALL',
using: (row) => row.active === true,
check: (row) => row.active === true,
},
];
}
export function exampleRows() {
return [
{ id: 1, tenantId: 'acme', active: true, title: 'Acme public record' },
{ id: 2, tenantId: 'acme', active: false, title: 'Acme archived record' },
{ id: 3, tenantId: 'globex', active: true, title: 'Globex public record' },
];
}
function policiesFor(command, policies) {
const normalizedCommand = command.toUpperCase();
if (!['SELECT', 'UPDATE'].includes(normalizedCommand)) {
throw new RangeError(`This example supports SELECT or UPDATE, not ${command}`);
}
return policies.filter(
(policy) => policy.command === 'ALL' || policy.command === normalizedCommand,
);
}
function expressionPasses(policy, phase, row, actor) {
const expression = phase === 'existing'
? policy.using
: (policy.check ?? policy.using);
return expression(row, actor) === true;
}
/**
* Applies PostgreSQL's same-command composition rule:
* (permissive_1 OR permissive_2 OR ...) AND restrictive_1 AND restrictive_2 ...
*/
export function rowAllowed({ command, phase = 'existing', row, actor, policies }) {
if (!row || !actor || !Array.isArray(policies)) {
throw new TypeError('row, actor, and policies are required');
}
if (!['existing', 'proposed'].includes(phase)) {
throw new RangeError(`Unknown policy phase: ${phase}`);
}
const applicable = policiesFor(command, policies);
const permissive = applicable.filter((policy) => policy.mode === 'PERMISSIVE');
const restrictive = applicable.filter((policy) => policy.mode === 'RESTRICTIVE');
// PostgreSQL default-denies when there is no applicable permissive policy.
return (
permissive.some((policy) => expressionPasses(policy, phase, row, actor)) &&
restrictive.every((policy) => expressionPasses(policy, phase, row, actor))
);
}
export function selectRows({ rows, actor, policies }) {
return rows.filter((row) =>
rowAllowed({ command: 'SELECT', phase: 'existing', row, actor, policies }),
);
}
export function updateRow({ rows, id, changes, actor, policies }) {
const index = rows.findIndex((row) => row.id === id);
if (index === -1) return { status: 'not-found', rows: [...rows] };
const existing = rows[index];
if (!rowAllowed({ command: 'UPDATE', phase: 'existing', row: existing, actor, policies })) {
// PostgreSQL ordinarily filters an inaccessible UPDATE target rather than updating it.
return { status: 'not-visible', rows: [...rows] };
}
const proposed = { ...existing, ...changes };
if (!rowAllowed({ command: 'UPDATE', phase: 'proposed', row: proposed, actor, policies })) {
// A failed WITH CHECK is an error in PostgreSQL; this model reports it explicitly.
return { status: 'check-violation', rows: [...rows] };
}
return {
status: 'updated',
rows: rows.map((row, rowIndex) => (rowIndex === index ? proposed : row)),
};
}
export function postgresFixtureSql() {
return `
CREATE TABLE tenant_records (
id integer PRIMARY KEY,
tenant_id text NOT NULL,
active boolean NOT NULL,
title text NOT NULL
);
ALTER TABLE tenant_records ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_access ON tenant_records
AS PERMISSIVE FOR ALL TO app_user
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true));
CREATE POLICY active_records_only ON tenant_records
AS RESTRICTIVE FOR ALL TO app_user
USING (active)
WITH CHECK (active);
`.trim();
}
Read the full article: https://chriseugenerodriguez.com/blog/postgresql-rls-policy-composition
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.