Skip to content
Visual explainer 2h to learn 3 steps

Roles, privileges & row-level security

Create least-privilege roles for apps and humans.

By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.

Topic 24 of 30

In short

In Postgres, users and groups are both roles. Give each app and person its own login role, grant privileges to group roles, and add row-level security when different users may see only their own rows.

Explained simply

Postgres decides who may do what with roles. A role can be a person, an application or a group. A role that is allowed to log in is what other systems call a user. A role that cannot log in is used as a group: you give it permissions, then add other roles as members.

A permission is called a privilege. SELECT lets a role read a table, INSERT lets it add rows, and so on. You hand them out with GRANT and take them back with REVOKE. Nothing is allowed until someone grants it, except for the owner of an object, who can do everything with it.

Least privilege means each role gets only what it needs. The web app can read and write data but cannot drop tables. An analyst can read but not change anything. The migration tool owns the tables. If one password leaks, the damage stays small.

Row-level security (RLS) goes one step further. GRANT decides which tables a role can touch; RLS decides which rows inside a table it can see or change. That is how one table can safely hold data for many customers.

Press Play on a diagram to walk through it one step at a time.

LayersPermission checks, outside in
  1. 1
    pg_hba.conf

    May this host and user connect at all?

  2. 2
    Database CONNECT

    May the role open this database?

  3. 3
    Schema USAGE

    May it see objects in the schema?

  4. 4
    Table privileges

    SELECT, INSERT, UPDATE, DELETE grants

  5. 5
    Row-level security

    Policies filter which rows are visible

MapExample role setup
Roles
  • app_owner
    • Owns tables, runs migrations
  • app_rw (group)
    • api_service (login)
  • app_ro (group)
    • analyst_ana (login)
    • bi_tool (login)
CompareWhat USING and WITH CHECK control
USING
  • Applies to rows that already exist
  • SELECT, UPDATE, DELETE
  • Hidden rows simply don't appear
  • No error, just fewer rows
WITH CHECK
  • Applies to rows being written
  • INSERT and the new row of UPDATE
  • Bad rows raise an error
  • Defaults to USING if omitted

In depth

Login roles, group roles and attributes

CREATE USER is simply CREATE ROLE with LOGIN. Roles also carry attributes that are separate from table privileges: SUPERUSER bypasses every check, CREATEDB and CREATEROLE allow creating databases and roles, REPLICATION allows streaming replication, and BYPASSRLS skips row-level security. Give these out rarely; an application role should have none of them.

Membership works with GRANT too: GRANT app_rw TO api_service makes api_service a member of app_rw, and by default members inherit the group's privileges. Use SET ROLE app_owner to act as a role you belong to, for example to run a migration.

Postgres also ships predefined roles for common jobs: pg_read_all_data and pg_write_all_data (PostgreSQL 14+), pg_monitor for monitoring tools, and pg_signal_backend to cancel other sessions' queries. In psql, \du lists roles and their attributes and \dp shows table privileges.

  • LOGIN = can connect; NOLOGIN = group
  • Avoid SUPERUSER for apps and people's daily work
  • pg_monitor for dashboards, pg_read_all_data for read-only staff
  • \du lists roles; \dp shows privileges

Owners, grants and the default privileges trap

Whoever creates an object owns it, and the owner can alter or drop it no matter what is granted. So the application should not own its tables: create them with a separate owner role (used only by migrations) and grant the app just SELECT, INSERT, UPDATE and DELETE.

Privileges are checked at several levels. A role needs CONNECT on the database, USAGE on the schema, and then privileges on each table. If tables use serial columns, inserting also needs USAGE on their sequences. Since PostgreSQL 15, ordinary users can no longer create objects in the public schema by default, which closes an old security hole.

The classic trap: GRANT ... ON ALL TABLES IN SCHEMA covers only tables that exist now. ALTER DEFAULT PRIVILEGES adds grants for tables created later, but only for tables created by the role that ran it, or by the role you name with FOR ROLE. Run it as, or for, the migration owner.

MapA least-privilege setup for one app
Database shop
  • shop_owner (NOLOGIN)
    • Owns schema and tables
    • Used via SET ROLE by migrations
  • shop_rw (group)
    • SELECT, INSERT, UPDATE, DELETE
    • Member: api_service (LOGIN)
  • shop_ro (group)
    • SELECT only
    • Members: analysts, BI tool
  • monitoring (LOGIN)
    • Member of pg_monitor
    • No table access needed

Row-level security policies

ALTER TABLE t ENABLE ROW LEVEL SECURITY switches RLS on. From then on, for roles that are not the owner, a table with no policies shows no rows at all: RLS is deny by default.

A policy has two kinds of conditions. USING filters which existing rows a role can see, update or delete. WITH CHECK decides which new or changed rows it may write; without it, an UPDATE could move a row out of the user's own reach. You can target commands (FOR SELECT, FOR INSERT, FOR UPDATE, FOR DELETE, or FOR ALL) and roles (TO shop_rw). Several permissive policies are combined with OR; a policy marked AS RESTRICTIVE must also pass, combined with AND.

Who bypasses RLS: superusers and roles with BYPASSRLS, always; the table owner, unless you also run ALTER TABLE t FORCE ROW LEVEL SECURITY. That is why testing as the owner shows every row. Index the columns your policies filter on, because the policy condition is added to every query.

  • Enabled with no policy: non-owners see nothing
  • USING filters reads; WITH CHECK guards writes
  • Permissive policies OR together; RESTRICTIVE ones AND
  • FORCE ROW LEVEL SECURITY applies it to the owner too

Who can connect: pg_hba.conf and passwords

Before any privilege matters, the server checks pg_hba.conf (host-based authentication). Each line names a connection type, database, user, client address and method, and the first matching line wins. For example: hostssl shop api_service 10.0.0.0/16 scram-sha-256 allows the app to connect over TLS from the private network with a password. local all postgres peer lets the postgres operating system user connect through the local socket without a password.

scram-sha-256 has been the default password hashing since PostgreSQL 14; md5 is outdated. After editing pg_hba.conf, reload with SELECT pg_reload_conf(); no restart is needed.

By default every role is a member of the special group PUBLIC, which has CONNECT on new databases. On a shared server, REVOKE CONNECT ON DATABASE shop FROM PUBLIC and grant it only to the roles that need it.

FlowFrom connection attempt to rows
  1. 1
    TCP or socket connect

    listen_addresses and port must allow it

  2. 2
    pg_hba.conf match

    First line matching type, db, user, address

  3. 3
    Authenticate

    scram-sha-256, peer, cert, ...

  4. 4
    Privilege checks

    CONNECT, schema USAGE, table grants

  5. 5
    RLS policies

    Filter rows per role

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Create login and group roles~40m
  2. 2
    Grant least-privilege permissions~40m
  3. 3
    Enable row-level security policies~40m

Key points

  • A role with LOGIN can connect; one without LOGIN acts as a group.
  • Grant to group roles, then add people and apps as members.
  • ALTER DEFAULT PRIVILEGES covers tables created in the future.
  • Table owners and superusers bypass RLS unless FORCE ROW LEVEL SECURITY is set.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
CREATE ROLE app_ro NOLOGIN;
GRANT CONNECT ON DATABASE shop TO app_ro;
GRANT USAGE ON SCHEMA public TO app_ro;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO app_ro;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO app_ro;

CREATE ROLE analyst_ana LOGIN PASSWORD 'change-me' IN ROLE app_ro;

ALTER TABLE notes ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_notes ON notes
  USING (owner_name = current_user);

Roles for an app, its migrations and analysts

Step 1: create an owner role that cannot log in, and make it own the schema. Step 2: create read-write and read-only groups. Step 3: grant table privileges now and default privileges for future tables created by the owner. Step 4: create login roles and add them to the groups. Migrations connect as a deployer login that is a member of shop_owner and run SET ROLE shop_owner first.

sql
CREATE ROLE shop_owner NOLOGIN;
CREATE ROLE shop_rw NOLOGIN;
CREATE ROLE shop_ro NOLOGIN;
CREATE SCHEMA app AUTHORIZATION shop_owner;
GRANT USAGE ON SCHEMA app TO shop_rw, shop_ro;

ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA app
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO shop_rw;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA app
  GRANT SELECT ON TABLES TO shop_ro;

CREATE ROLE api_service LOGIN PASSWORD 'use-a-secret-manager' IN ROLE shop_rw;
CREATE ROLE deployer   LOGIN PASSWORD 'another-secret'       IN ROLE shop_owner;
CREATE ROLE ana        LOGIN PASSWORD 'and-another'          IN ROLE shop_ro;

Multi-tenant isolation with RLS

A SaaS app keeps every customer's invoices in one table with a tenant_id column. Step 1: enable RLS; the app role is not the table owner, so policies apply to it. Step 2: one policy compares tenant_id with a custom setting the app sets per transaction. Step 3: the app runs SET LOCAL app.tenant_id = '42' at the start of each transaction (SET LOCAL lasts only until COMMIT, which is also safe with poolers). A forgotten WHERE tenant_id = ... in app code can no longer leak another customer's data, and a missing setting returns no rows.

sql
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON invoices
  FOR ALL TO shop_rw
  USING (tenant_id = current_setting('app.tenant_id', true)::bigint)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::bigint);

CREATE INDEX ON invoices (tenant_id);

-- in the app, per transaction:
BEGIN;
SET LOCAL app.tenant_id = '42';
SELECT * FROM invoices;   -- only tenant 42's rows
COMMIT;

Quick reference

  • CREATE ROLE name LOGIN PASSWORD '...'; CREATE USER is the same with LOGIN implied
  • GRANT group_role TO member_role; members inherit the group's privileges
  • GRANT SELECT ON ALL TABLES IN SCHEMA app TO shop_ro; existing tables only
  • ALTER DEFAULT PRIVILEGES FOR ROLE owner IN SCHEMA app GRANT ... ON TABLES TO ...;
  • ALTER TABLE t ENABLE ROW LEVEL SECURITY; plus FORCE to apply it to the owner
  • REVOKE CONNECT ON DATABASE shop FROM PUBLIC; lock down a shared server
  • \du roles, \dp table privileges, \dn+ schema privileges in psql
  • SELECT pg_reload_conf(); apply pg_hba.conf changes without a restart

Common mistakes

  • Letting the application connect as a superuser.
  • Granting on existing tables only, so new tables are inaccessible.
  • Testing RLS as the table owner, who bypasses the policies.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You granted SELECT ON ALL TABLES IN SCHEMA app TO shop_ro last month. A new table created yesterday gives shop_ro "permission denied". Why?

Question 2

2RLS is enabled on a table but no policy exists. What does a normal app role see?

Question 3

3You test your RLS policy while connected as the table owner and see every row. Why?

Question 4

4What does WITH CHECK do in a policy?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a read-only login role report_user that can read every current table in the public schema of database shop.

  2. Exercise 2medium

    Check whether api_service can delete from orders, and list every privilege on orders.

  3. Exercise 3hard

    notes(id, owner text, body). Let members of shop_rw read and edit only their own notes (owner = current_user), and stop them from creating notes for someone else.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between a user and a role in PostgreSQL?
There is no real difference. A user is a role with the LOGIN attribute, and CREATE USER is just CREATE ROLE with LOGIN.
Should my application connect as postgres?
No. postgres is a superuser that bypasses every check, including RLS. Create a dedicated login role with only the table privileges the app needs.
Does row-level security slow queries down?
The policy condition is added to each query like an extra WHERE. With an index on the filtered column the cost is usually small; complex policies with subqueries cost more.

Go deeper

ShareXLinkedInWhatsApp