Chapter 9 · Lesson 2 of 8
Databases and data

Postgres roles and permissions for an app user and a read-only user

A Postgres role is a login or a group that owns objects and holds privileges, so you create a limited role per app with GRANT instead of letting the app use the superuser.

By the end you will

Create an app role and a read-only role with the minimum grants, and inspect the result with \dp.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • A running Postgres you can reach as a superuser

Roles decide who can do what in Postgres

Create one role per job: the owner makes the tables, the app role gets only the rights it needs, and a read-only role can just SELECT.
  1. The owner role creates the tables, so it owns them.
  2. The owner runs GRANT SELECT, INSERT, UPDATE ON the tables TO the app role.
  3. The owner gives the read-only role only SELECT, so it cannot change data.
  4. The app connects as its own role and can read and write only what it was granted.
  5. The read-only role can run SELECT, and an INSERT is refused with permission denied.
Static diagram
  1. Owner rolecreate tablesDatabase
  2. Owner roleGRANTApp role
  3. Owner roleGRANT SELECTRead-only role
  4. App roleapp connectsDatabase
  5. Read-only roleread onlyDatabase

Give every app its own Postgres role that owns only its own database, and never let an app log in as the postgres superuser. With CREATE ROLE, GRANT and ALTER DEFAULT PRIVILEGES you decide exactly which databases, schemas and tables each login can read or change, so a leaked password or a bad query has a small blast radius.

How it works#

In Postgres there is one concept: the role. A role can own objects, hold privileges, and optionally log in. A role with the LOGIN attribute is what other systems call a user. A role without it works as a group: you grant privileges to the group and add login roles to it. CREATE USER is the same as CREATE ROLE ... LOGIN.

Access to a table is checked in layers. A role needs CONNECT on the database, USAGE on the schema that contains the table, and then the privilege on the table itself, such as SELECT or INSERT. Missing any layer gives permission denied. Roles are cluster-wide, but privileges are per database. The role PUBLIC is a pseudo-role meaning everyone, and some defaults are granted to it, which is why you sometimes revoke from PUBLIC.

The owner of an object can do everything with it and can grant to others. A superuser skips all checks, so an app running as superuser can drop other databases and read every table. That is why the app should not be one.

Step 1: Create the app role and database#

Connect as the superuser with sudo (see install Postgres and connect with psql):

sql
CREATE ROLE app LOGIN PASSWORD 'change-me';
CREATE DATABASE shop OWNER app;
REVOKE CONNECT ON DATABASE shop FROM PUBLIC;
GRANT CONNECT ON DATABASE shop TO app;

Replace change-me with a long random password and keep it as a secret in an environment variable (see environment variables and secrets), not in the repo. Because app owns the database, it can create tables and run migrations there. It cannot touch other databases. The default CONNECT privilege on a new database goes to PUBLIC, so the REVOKE line prevents other roles from connecting to shop.

Step 2: Handle the public schema#

Every new database has a schema named public. Before PostgreSQL 15, any role could create objects in it by default. PostgreSQL 15 changed this: CREATE on public is no longer granted to all roles, and the database owner owns the schema. Servers upgraded from older versions keep their old grants, so do not assume. Check from shop:

sql
\c shop
\dn+ public

If the access list shows =UC/... for PUBLIC, everyone can create objects there. Remove it:

sql
REVOKE CREATE ON SCHEMA public FROM PUBLIC;

This does not affect app, because the owner keeps its rights. Running it on an already restricted schema does no harm.

Step 3: Add a read-only role#

A read-only role suits dashboards, reporting tools and people who need to look at data. Run these in the target database, as the owner or a superuser:

sql
CREATE ROLE reporting LOGIN PASSWORD 'change-me-too';
GRANT CONNECT ON DATABASE shop TO reporting;
GRANT USAGE ON SCHEMA public TO reporting;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO reporting;
ALTER DEFAULT PRIVILEGES FOR ROLE app IN SCHEMA public
  GRANT SELECT ON TABLES TO reporting;

The GRANT SELECT ON ALL TABLES line covers tables that exist now. ALTER DEFAULT PRIVILEGES FOR ROLE app covers tables that app creates later, for example in a migration. Without it, the first new table gives permission denied for table ... to the reporting role. Add GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public only if the role must read sequence values.

Step 4: Grant write access to a separate role#

If you want migrations and runtime to use different roles, keep app as the owner for migrations and create a runtime role with limited rights:

sql
CREATE ROLE app_rw LOGIN PASSWORD 'change-me-three';
GRANT CONNECT ON DATABASE shop TO app_rw;
GRANT USAGE ON SCHEMA public TO app_rw;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_rw;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app_rw;
ALTER DEFAULT PRIVILEGES FOR ROLE app IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_rw;
ALTER DEFAULT PRIVILEGES FOR ROLE app IN SCHEMA public
  GRANT USAGE, SELECT ON SEQUENCES TO app_rw;

The runtime role can read and write rows but cannot drop or alter tables. Sequences matter because an INSERT into a table with a serial or identity column needs USAGE on its sequence.

Check it worked#

sql
\du            -- roles and attributes
\l             -- databases, owners and access privileges
\dp            -- table privileges in the current database

Then prove it by logging in as the limited role and trying a write:

bash
psql -h 127.0.0.1 -U reporting -d shop -c "INSERT INTO items(name) VALUES ('x');"

The expected result is ERROR: permission denied for table items. A SELECT should succeed.

Edge cases and gotchas#

  • Default privileges are per creator. ALTER DEFAULT PRIVILEGES FOR ROLE app applies only to objects that app creates. Tables created by the superuser are not covered.
  • Passwords in SQL end up in logs. A statement with PASSWORD '...' can appear in server logs and in ~/.psql_history. In psql use \password app to type it without echo.
  • Dropping a role fails while it owns objects. Use REASSIGN OWNED BY old TO new; and DROP OWNED BY old; first, then DROP ROLE old;. Check twice, because DROP OWNED removes objects.
  • Grants on the database do not reach tables. GRANT ALL ON DATABASE gives connect, create and temp rights, not table access.
  • Superuser is not a feature flag for convenience. Do not give SUPERUSER, CREATEDB or CREATEROLE to an app role unless the app genuinely creates databases.
  • Docker image defaults. The POSTGRES_USER you set becomes a superuser. Create a second, limited role for the app rather than using that one.

Troubleshooting#

SymptomLikely causeFix
ERROR: permission denied for table itemsNo table privilegeGRANT SELECT ON items TO reporting;
ERROR: permission denied for schema publicNo USAGE on the schemaGRANT USAGE ON SCHEMA public TO reporting;
FATAL: permission denied for database "shop"No CONNECT privilegeGRANT CONNECT ON DATABASE shop TO reporting;
ERROR: permission denied for sequence items_id_seqInsert without sequence privilegeGRANT USAGE, SELECT ON SEQUENCE items_id_seq TO app_rw;
ERROR: permission denied to create roleCurrent role lacks CREATEROLERun as a superuser
ERROR: role "app" already existsRole name takenUse ALTER ROLE app PASSWORD '...' or pick another name
ERROR: role "old" cannot be dropped because some objects depend on itRole still owns objectsREASSIGN OWNED BY old TO app; then DROP OWNED BY old;
New table not readable by the read-only roleDefault privileges missing or set for another creatorRe-run ALTER DEFAULT PRIVILEGES FOR ROLE <creator> ...

Quick reference#

sql
CREATE ROLE app LOGIN PASSWORD 'change-me';
CREATE DATABASE shop OWNER app;
REVOKE CONNECT ON DATABASE shop FROM PUBLIC;
GRANT CONNECT ON DATABASE shop TO reporting;
GRANT USAGE ON SCHEMA public TO reporting;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO reporting;
ALTER DEFAULT PRIVILEGES FOR ROLE app IN SCHEMA public
  GRANT SELECT ON TABLES TO reporting;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
\du  \l  \dp  \dn+

Next#

Continue with database connection strings explained to put the new role into a URL your app can use.

Try it: Create an app role and a database it owns

Run as the postgres superuser. Create a login role, a database it owns, and inspect it.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1What does CREATE USER app differ from CREATE ROLE app in?
2A role has SELECT on a table but gets permission denied for schema public. What is missing?
3Why run ALTER DEFAULT PRIVILEGES for a read-only role?
4Which psql command shows table privileges?

Frequently asked questions

What is the difference between a role and a user in PostgreSQL?

There is no difference in storage. CREATE USER is CREATE ROLE with LOGIN already set, so a user is a role that can log in.

Should my app connect as the postgres superuser?

No. A superuser bypasses every permission check, so a SQL injection or a bad migration can do anything. Give the app a role that owns only its own database.

How do I create a read-only user in Postgres?

Create a login role, grant CONNECT on the database, USAGE on the schema and SELECT on the tables, then use ALTER DEFAULT PRIVILEGES so new tables are covered too.

Why can my new role still create tables in the public schema?

Before PostgreSQL 15, every role had CREATE on the public schema by default. Revoke it explicitly if your server is older or was upgraded from an older version.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios