Skip to the workspace
Pebellslearn by building
Security  ›  Lesson

Roles

Roles 12 minPostgreSQL uses roles for both users and groups; login roles identify people and programs, group roles hold privileges, and attributes are not inherited.

postgresql dba / Roles

Explore each scene at your own pace.

01 · The rule

The rule

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 analysts

Key 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 whatever analysts has been granted. A member can also SET ROLE analysts to act as the group, for example so new objects are owned by it.
  • Superuser skips every permission check. Keep it for the postgres role and emergencies.
  • Predefined roles cover common jobs without superuser: pg_monitor to read monitoring views, pg_read_all_data to read every table, pg_signal_backend to cancel other sessions' queries.
  • Passwords are stored as SCRAM-SHA-256 hashes by default.

\du in psql lists roles, their attributes and memberships.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.