Roles
Everyone at Pedal used to connect as postgres, the superuser. Then an intern's cleanup script dropped the payments table, and the logs could not even say who ran it. Access control in PostgreSQL starts with one idea: give every person and program its own role, with only the power it needs.
The rule
Everything is a role: users log in, groups hold privileges, nobody is superuser.
PostgreSQL has a single concept, the role. A role with the LOGIN attribute behaves like a user; a role without it behaves like a group. CREATE USER is just CREATE ROLE … LOGIN.
-- groups: no login, they only hold privileges
CREATE ROLE pedal_owner NOLOGIN;
CREATE ROLE analysts NOLOGIN;
-- logins: one per program and one per person
CREATE ROLE pedal_app LOGIN PASSWORD 'from-the-secret-store';
CREATE ROLE asha LOGIN PASSWORD 'asha-sets-her-own';
GRANT analysts TO asha; -- asha is now a member of analystsKey facts:
- Roles are cluster-wide: one role can be granted access to several databases.
- Attributes are powers of the role itself:
LOGIN,SUPERUSER,CREATEDB,CREATEROLE,REPLICATION,BYPASSRLS. Attributes are not passed on through group membership. - Membership passes on privileges. With the default
INHERIT, asha automatically has whateveranalystshas been granted. A member can alsoSET ROLE analyststo act as the group, for example so new objects are owned by it. - Superuser skips every permission check. Keep it for the
postgresrole and emergencies. - Predefined roles cover common jobs without superuser:
pg_monitorto read monitoring views,pg_read_all_datato read every table,pg_signal_backendto cancel other sessions' queries. - Passwords are stored as SCRAM-SHA-256 hashes by default.
\du in psql lists roles, their attributes and memberships.