Mateusz Mańczak

Postgres permissions cheatsheet

#postgresql#databases#security#cheatsheet#ai-generated

A short reference of how users and permissions work in PostgreSQL. In Postgres there are only roles: a “user” is a role that can log in, a “group” is a role that other roles are members of. Related posts: psql cheatsheet and SQL syntax cheatsheet.

Roles#

CREATE ROLE app_user LOGIN PASSWORD 'change-me';
CREATE ROLE readonly NOLOGIN;
GRANT readonly TO app_user;
Syntax Description
CREATE ROLE name LOGIN PASSWORD '...' Create a role that can log in (a “user”)
CREATE USER name PASSWORD '...' Same as above, CREATE USER implies LOGIN
CREATE ROLE name NOLOGIN Create a role that is only a container of privileges (a “group”)
ALTER ROLE name PASSWORD '...' Change a password
ALTER ROLE name RENAME TO new_name Rename a role
ALTER ROLE name VALID UNTIL '2027-01-01' Password expiry
ALTER ROLE name CONNECTION LIMIT 10 Limit concurrent connections
ALTER ROLE name SET search_path = app, public Per-role setting default
ALTER ROLE name IN DATABASE db SET ... Per-role and per-database setting default
DROP ROLE IF EXISTS name Delete a role (it must own nothing, see Removing a role)
\du List roles in psql
\du+ name Role details with description

Role attributes#

Attribute Description
LOGIN / NOLOGIN Can / cannot start a session
SUPERUSER / NOSUPERUSER Bypasses every permission check, use sparingly
CREATEDB Can create databases
CREATEROLE Can create and manage other roles
REPLICATION Can start streaming replication
BYPASSRLS Ignores row-level security policies
INHERIT / NOINHERIT Automatically use privileges of roles it is a member of (default INHERIT)
ALTER ROLE app_user CREATEDB;
ALTER ROLE app_user NOCREATEDB;

Membership#

Syntax Description
GRANT group_role TO user_role Make user_role a member
GRANT group_role TO user_role WITH ADMIN OPTION Member can add other members
GRANT group_role TO user_role WITH INHERIT FALSE Member must SET ROLE to use the privileges (PostgreSQL 16+)
REVOKE group_role FROM user_role Remove a member
SET ROLE group_role Switch to another role for the session
RESET ROLE Switch back
SELECT rolname FROM pg_roles WHERE pg_has_role('app_user', oid, 'member') All roles a user belongs to

Privileges by object#

Object Privileges
Database CONNECT, CREATE, TEMPORARY
Schema USAGE, CREATE
Table / view SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER
Column SELECT, INSERT, UPDATE, REFERENCES
Sequence USAGE, SELECT, UPDATE
Function EXECUTE
Type / domain USAGE
Tablespace CREATE

ALL (or ALL PRIVILEGES) grants everything applicable to the object type. To reach a table a role needs USAGE on its schema and the privilege on the table itself.

GRANT and REVOKE#

GRANT CONNECT ON DATABASE mydb TO app_user;
GRANT USAGE ON SCHEMA public TO app_user;
GRANT SELECT, INSERT, UPDATE ON orders TO app_user;
GRANT USAGE ON SEQUENCE orders_id_seq TO app_user;
REVOKE DELETE ON orders FROM app_user;
Syntax Description
GRANT priv ON TABLE t TO role Grant on one table
GRANT priv ON ALL TABLES IN SCHEMA s TO role Grant on all existing tables in a schema
GRANT priv ON ALL SEQUENCES IN SCHEMA s TO role Same for sequences (needed for serial and identity inserts)
GRANT EXECUTE ON FUNCTION f(int) TO role Allow calling a function
GRANT SELECT (col1, col2) ON t TO role Column-level grant
GRANT priv ON t TO role WITH GRANT OPTION Role may pass the privilege on
GRANT priv ON t TO PUBLIC Grant to every role, current and future
REVOKE priv ON t FROM role Remove a privilege
REVOKE GRANT OPTION FOR priv ON t FROM role Remove only the right to grant
REVOKE priv ON t FROM role CASCADE Also revoke what the role granted onward

GRANT ... ON ALL TABLES only affects tables that exist right now. Use default privileges for tables created later.

Default privileges#

Set what future objects created by a given role get:

ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA public
  GRANT SELECT ON TABLES TO readonly;

ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA public
  GRANT USAGE, SELECT ON SEQUENCES TO readonly;
Syntax Description
ALTER DEFAULT PRIVILEGES GRANT ... ON TABLES TO r Applies to objects created by the current role
ALTER DEFAULT PRIVILEGES FOR ROLE x GRANT ... Applies to objects created by role x
... IN SCHEMA s ... Limit to one schema
ALTER DEFAULT PRIVILEGES ... REVOKE ... Remove a default
\ddp List default privileges in psql

Default privileges are tied to the role that creates the objects. If your migrations run as another role than you, the FOR ROLE part is the usual reason it “does not work”.

Ownership#

Syntax Description
ALTER TABLE t OWNER TO role Change the owner of a table
ALTER DATABASE db OWNER TO role Change the owner of a database
ALTER SCHEMA s OWNER TO role Change the owner of a schema
REASSIGN OWNED BY old_role TO new_role Transfer ownership of all objects in the current database

The owner implicitly has all privileges on the object and can DROP or ALTER it. Owners do not need extra grants, superusers bypass everything.

The public schema#

Before PostgreSQL 15 every role could create objects in public. From 15 on, CREATE on public is no longer granted to everyone. On older versions, or to be explicit:

REVOKE CREATE ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON DATABASE mydb FROM PUBLIC;

The second line removes the default CONNECT and TEMPORARY that every role gets on a new database.

Common recipes#

Read-only role:

CREATE ROLE readonly NOLOGIN;
GRANT CONNECT ON DATABASE mydb TO readonly;
GRANT USAGE ON SCHEMA public TO readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;

CREATE ROLE reporting LOGIN PASSWORD 'change-me';
GRANT readonly TO reporting;

Application role with read and write access:

CREATE ROLE readwrite NOLOGIN;
GRANT CONNECT ON DATABASE mydb TO readwrite;
GRANT USAGE ON SCHEMA public TO readwrite;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO readwrite;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO readwrite;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO readwrite;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
  GRANT USAGE, SELECT ON SEQUENCES TO readwrite;

Row-level security#

Restrict which rows a role can see or change:

ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY own_documents ON documents
  FOR ALL
  TO app_user
  USING (owner = current_user)
  WITH CHECK (owner = current_user);
Syntax Description
ALTER TABLE t ENABLE ROW LEVEL SECURITY Turn RLS on, with no policy nobody (except owner) sees any row
ALTER TABLE t FORCE ROW LEVEL SECURITY Apply RLS to the table owner too
ALTER TABLE t DISABLE ROW LEVEL SECURITY Turn it off
CREATE POLICY p ON t FOR SELECT USING (expr) Which existing rows are visible
CREATE POLICY p ON t FOR INSERT WITH CHECK (expr) Which new rows may be inserted
FOR UPDATE USING (...) WITH CHECK (...) Which rows may be changed, and what they may become
CREATE POLICY p ON t AS RESTRICTIVE ... Must pass in addition to permissive policies (default is PERMISSIVE, any one passes)
DROP POLICY p ON t Remove a policy
\dp t Show privileges and policies on a table

Superusers and roles with BYPASSRLS ignore policies.

Inspecting permissions#

Syntax Description
\du Roles and their attributes
\l Databases with owners and privileges
\dn+ Schemas with owners and privileges
\dp (or \z) Privileges on tables, views and sequences
\dp schema.table Privileges on one table
\ddp Default privileges
\df+ func Function owner and privileges
SELECT has_table_privilege('app_user', 'orders', 'SELECT') Check one privilege
SELECT has_schema_privilege('app_user', 'public', 'USAGE') Check schema access
SELECT has_database_privilege('app_user', 'mydb', 'CONNECT') Check database access
SELECT has_column_privilege('app_user', 'orders', 'total', 'SELECT') Check column access
SELECT current_user, session_user Effective and original login role

Reading the \dp output: app_user=arwd/owner means role app_user got a (INSERT), r (SELECT), w (UPDATE), d (DELETE) granted by owner. An empty role name before = means PUBLIC.

Letter Privilege
r SELECT (read)
a INSERT (append)
w UPDATE (write)
d DELETE
D TRUNCATE
x REFERENCES
t TRIGGER
U USAGE
C CREATE
c CONNECT
T TEMPORARY
X EXECUTE
* Appended to a letter when granted WITH GRANT OPTION

List table privileges as a query:

SELECT grantee, table_schema, table_name, privilege_type
FROM information_schema.role_table_grants
WHERE grantee = 'app_user'
ORDER BY table_schema, table_name, privilege_type;

Removing a role#

A role that owns objects or holds privileges cannot be dropped. Clean it up first, in each database:

REASSIGN OWNED BY old_role TO new_role;
DROP OWNED BY old_role;
DROP ROLE old_role;

DROP OWNED BY also revokes the role’s privileges on objects it does not own, but it drops the objects it owns, so run REASSIGN OWNED first.

Authentication: pg_hba.conf#

Roles and privileges decide what you can do after connecting. pg_hba.conf decides who may connect and how. Each line has the form:

# TYPE  DATABASE  USER      ADDRESS         METHOD
local   all       postgres                  peer
host    mydb      app_user  10.0.0.0/24     scram-sha-256
hostssl all       all       0.0.0.0/0       scram-sha-256
Field Values
TYPE local (Unix socket), host (TCP), hostssl (TCP with TLS), hostnossl
DATABASE Database name, all, replication
USER Role name, all, +group (members of a group role)
ADDRESS CIDR range or hostname (not used for local)
METHOD scram-sha-256, peer, md5, trust, reject, cert…