On this page
  1. Security, Roles & Row-Level Security
  2. Contents
  3. Least-Privilege Roles
  4. Multi-Tenant Row-Level Security (RLS)

Security, Roles & Row-Level Security

Prev: Indexes & EXPLAIN ANALYZE | Up: postgresql | Next: mongodb
Rel: DDL & Constraints, Web Security Mitigations
Ref: PostgreSQL — Row Security Policies
Tags: #public #databases #postgresql #security #rls


Contents


Least-Privilege Roles

Never run application traffic as a superuser (postgres). Separate a migration role (DDL owner) from a runtime app role granted only SELECT, INSERT, UPDATE, DELETE on specific tables:

CREATE ROLE app_runtime LOGIN PASSWORD 'replace_me';
GRANT USAGE ON SCHEMA app TO app_runtime;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA app TO app_runtime;

Multi-Tenant Row-Level Security (RLS)

RLS enforces per-row visibility inside the database engine itself, preventing cross-tenant data leaks even if an application query forgets a WHERE tenant_id = ... clause:

ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON documents
  USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

Set the session variable per transaction (SET LOCAL app.current_tenant_id = '...';) so connection pools never leak tenant context across requests.

Linked from

Related notes