Reviewing PostgreSQL RLS: find the policy-composition failure first

Reviewing PostgreSQL RLS: find the policy-composition failure first

●3 ●58
calendar_today • schedule3 min read
— Originally published at chriseugenerodriguez.com

A common RLS review failure is approving two policies because each one sounds safe in isolation. Consider a tenant rule that permits rows from the caller’s tenant and an active-record rule intended to hide archived rows. If both policies are permissive, either passing rule can admit the row. The active-record condition is no longer an unconditional narrowing guard.

Prerequisites are modest: a table with row-level security enabled, a way to identify the caller’s tenant, and clarity about which condition defines ordinary access versus which condition is inviolable. The example uses tenant-owned records with an active flag.

The implementation decision is to make tenant access permissive and the active requirement restrictive. PostgreSQL combines applicable permissive policies with OR, then requires every applicable restrictive policy to pass. In review terms, read the final expression as: a row needs one admission path, then it must survive all narrowing guards.

The expected result is straightforward. A current-tenant active row is visible. A current-tenant inactive row is denied because the restrictive condition fails. An active row from a different tenant is denied because no permissive admission path passes. On UPDATE, evaluate the existing row for target visibility and the proposed row for write acceptance; a visible row can still be rejected if the new values violate the restrictive write condition.

One limitation matters: the supplied fixture is a recorded application model of documented policy algebra, not a browser or external PostgreSQL-engine reproduction. It does not establish engine-specific behavior such as policy parsing, ownership bypass, planner interactions, triggers, or cross-table race conditions. Treat the fixture as a focused reasoning aid, then verify the full policy setup against the database environment you deploy.

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

Want more #architecture deep dives?

Join 6,168+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

The Sovereign Vault — A Comprehensive Guide to Protocol-Driven AI

Ken W. Algerverified - Jun 4

Stop trusting verdicts your policy no longer supports

VEACESLAV - Dec 1

Local-First: The Browser as the Vault

Pocket Portfolio - Apr 20

Short links that outlive the vendor: a newsroom URL shortener on WordPress and AWS

jaafarabazid - Nov 10

Don’t Over-Engineer: Why the Best Code is Code You Didn’t Write (YAGNI)

Mohamed Ahmed - Oct 3
chevron_left
1.2k Points • 61 Badges
Santa Monica, CA • chriseugenerodriguez.com
46Posts
0Comments
11Connections
10 years fe

Related Jobs

View all jobs →

Commenters (This Week)

12 comments
5 comments
5 comments

Contribute meaningful comments to climb the leaderboard and earn badges!