Sub topic 14
Designing a least-privilege setup
This chapter assembles the pieces from earlier chapters into one working layout for an application. It assumes you know how GRANT and REVOKE work, how group roles and inheritance behave, what PUBLIC grants by default, and how ALTER DEFAULT PRIVILEGES works. It also assumes you can read a psql session. The examples target PostgreSQL 15 or later. Version differences are noted where they matter.
The principle and the layout
Least privilege means each role can do what its job requires and nothing else. In PostgreSQL this comes down to four decisions:
- Who owns the objects.
- Which group roles carry privileges.
- Which login roles belong to which groups.
- What new objects receive automatically.
The standard layout uses three group roles that cannot log in, plus separate login roles for people and services.
| Role | Type | Purpose |
|---|---|---|
| `app_owner` | group, `NOLOGIN` | Owns the database, schema, and tables. Runs migrations. |
| `app_readonly` | group, `NOLOGIN` | `SELECT` only. For analysts and dashboards. |
| `app_writer` | group, `NOLOGIN` | `SELECT`, `INSERT`, `UPDATE`. For the application. |
| `migrator` | login | Member of `app_owner`. Used by the migration tool. |
| `app_user` | login | Member of `app_writer`. Used by the running application. |
| `alice` | login | Member of `app_readonly`. A human with read access. |
The owner has no login, so nobody can connect as it directly. The application never owns tables, so a bug or SQL injection in the application cannot run DROP TABLE or ALTER TABLE.
Step 1: Create the roles
Create the group roles first, then the database owned by app_owner.
CREATE ROLE app_owner NOLOGIN;
CREATE ROLE app_readonly NOLOGIN;
CREATE ROLE app_writer NOLOGIN;
CREATE DATABASE appdb OWNER app_owner;Give group roles no attributes beyond NOLOGIN. Do not give them CREATEDB, CREATEROLE, or SUPERUSER. Attributes are not inherited through membership in the way privileges are, but a role with CREATEROLE can still alter other roles, so grant it sparingly.
Step 2: Close the defaults
Connect to appdb before running the rest of the script (in psql, \c appdb). A new database lets PUBLIC connect and create temporary tables. Remove that, then grant CONNECT back only to the groups that need it.
REVOKE ALL ON DATABASE appdb FROM PUBLIC;
GRANT CONNECT ON DATABASE appdb TO app_readonly, app_writer;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;The last line has no effect on PostgreSQL 15 and later, where PUBLIC no longer has CREATE on the public schema. It is harmless there, and it matters on older servers. Run it anyway so the script behaves the same on every version.
The owner keeps its own rights. As database owner, app_owner can connect without an explicit grant, because owners hold all privileges on their objects.
Step 3: Create the schema and grant on existing objects
Create the schema owned by app_owner, create tables as that role, then grant to the groups.
CREATE SCHEMA shop AUTHORIZATION app_owner;
SET ROLE app_owner;
CREATE TABLE shop.orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
sales_rep name NOT NULL,
total numeric(10,2) NOT NULL
);
RESET ROLE;
GRANT USAGE ON SCHEMA shop TO app_readonly, app_writer;
GRANT SELECT ON ALL TABLES IN SCHEMA shop TO app_readonly;
GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA shop TO app_writer;Two details matter here. USAGE on the schema is required before any table grant has an effect, because a role must be able to look up names in the schema. And ALL TABLES IN SCHEMA covers only tables that exist when the command runs. Tables created tomorrow are not covered. Step 4 fixes that.
Note that app_writer has no DELETE and no TRUNCATE. If the application deletes rows, grant DELETE explicitly. Do not grant it just in case.
Step 4: Set defaults for future objects
ALTER DEFAULT PRIVILEGES applies to objects created later by a named role. Name app_owner, because that role will create the tables.
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA shop
GRANT SELECT ON TABLES TO app_readonly;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA shop
GRANT SELECT, INSERT, UPDATE ON TABLES TO app_writer;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA shop
GRANT USAGE ON SEQUENCES TO app_writer;Sequence USAGE is needed by tables that use serial columns or call nextval directly. The identity column in shop.orders does not depend on it, but future tables may.
Step 5: Create the login roles
Login roles get no direct privileges. They get membership.
CREATE ROLE migrator LOGIN PASSWORD 'change-me';
CREATE ROLE app_user LOGIN PASSWORD 'change-me';
CREATE ROLE alice LOGIN PASSWORD 'change-me';
GRANT app_owner TO migrator;
GRANT app_writer TO app_user;
GRANT app_readonly TO alice;Replace the placeholder passwords, and keep real ones in a secret store, not in scripts. By default these memberships inherit, so alice can run SELECT on shop.orders immediately.
The migration gotcha
Default privileges attach to the role that creates the object. If migrator creates a table while logged in as itself, migrator owns it and the defaults for app_owner do not apply. The groups then get no access.
Make the migration tool switch roles at the start of each session:
SET ROLE app_owner;
CREATE TABLE shop.refunds (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id bigint NOT NULL REFERENCES shop.orders (id),
amount numeric(10,2) NOT NULL
);
RESET ROLE;SET ROLE app_owner works because migrator is a member of app_owner. On PostgreSQL 16 and later, the membership must have SET enabled, which is the default for a plain GRANT.
Verify the result
Do not trust the script. Query the effective state.
SELECT has_table_privilege('alice', 'shop.orders', 'SELECT') AS alice_select,
has_table_privilege('alice', 'shop.orders', 'INSERT') AS alice_insert,
has_table_privilege('app_user', 'shop.orders', 'UPDATE') AS app_update,
has_table_privilege('app_user', 'shop.orders', 'DELETE') AS app_delete,
has_table_privilege('app_user', 'shop.refunds', 'INSERT') AS refunds_insert,
has_schema_privilege('alice', 'public', 'CREATE') AS alice_create_public;
SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE table_schema = 'shop' AND table_name = 'refunds'
ORDER BY grantee, privilege_type;Expected output for the first query is true, false, true, false, true, false. The refunds_insert column confirms that default privileges worked for the table created in the previous section. Run \ddp in psql to list the default privilege rules themselves.
Common failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| `permission denied for schema shop` | Table grant exists but schema `USAGE` is missing | `GRANT USAGE ON SCHEMA shop TO ...` |
| New table is unreadable by groups | Table was created by a role other than `app_owner` | Run migrations after `SET ROLE app_owner`, or add defaults `FOR ROLE` the actual creator |
| Old tables work, new ones fail | Only `ALL TABLES` was granted, with no default privileges | Add `ALTER DEFAULT PRIVILEGES` |
| Unknown role can connect | `PUBLIC` still has `CONNECT` | `REVOKE ALL ON DATABASE appdb FROM PUBLIC` |
| `alice` cannot use a grant given to her group | Member role created with `NOINHERIT` (or `INHERIT FALSE` on 16+) | Use `SET ROLE app_readonly`, or enable inheritance |
Tightening further
Three tools narrow access beyond table-level grants:
- Column grants, such as
GRANT SELECT (id, customer) ON shop.orders TO alice, hide sensitive columns. Note that a column-onlySELECTfails forSELECT *. - Row-level security restricts which rows a role sees. The policy
USING (sales_rep = current_user)onshop.orders, appliedTO app_readonly, shows each reader only their own orders once you runALTER TABLE shop.orders ENABLE ROW LEVEL SECURITY. The table owner is exempt unless you setFORCE ROW LEVEL SECURITY. - Predefined roles (PostgreSQL 14 and later) such as
pg_monitorgive monitoring access without granting on each catalog view. Prefer them over superuser for monitoring tools.
Audit checklist
Review a setup against this list:
- No application login role owns tables or has
SUPERUSER,CREATEROLE, orCREATEDB. PUBLIChas noCONNECTon the database and noCREATEon any schema.- Every table grant has a matching schema
USAGEgrant. - Default privileges exist for every role that creates objects.
has_table_privilegechecks pass for each login role, positive and negative.
Exercise
A new migration run by migrator (logged in directly, without SET ROLE) creates shop.invoices. app_user then gets permission denied for table invoices. Why did this happen, and what are two ways to fix it?
Show answer
migrator owns the new table, so the default privileges defined FOR ROLE app_owner did not apply. Fix it by running the migration after SET ROLE app_owner and changing the table's owner with ALTER TABLE shop.invoices OWNER TO app_owner plus the missing grants. Or add ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA shop GRANT SELECT, INSERT, UPDATE ON TABLES TO app_writer so future tables from migrator are covered. The first approach keeps ownership consistent and is preferred.
Exercise
Write a query that returns true only if alice can read shop.orders but cannot create objects in the shop schema.
Show answer
SELECT hastableprivilege('alice', 'shop.orders', 'SELECT') AND NOT hasschemaprivilege('alice', 'shop', 'CREATE') AS ok;