Roles, privileges and row-level security
A database is a vault for your most valuable data. PostgreSQL has a precise permission system: who can connect, which tables they can read, which columns they can update, and even which rows they can see.
Roles
In PostgreSQL, users and groups are both roles. A role with LOGIN can connect (a "user"); a role without it is a group you grant permissions to.
The postgres role is a superuser: it bypasses every permission check. Never let your application connect as a superuser.
GRANT and REVOKE
New roles can do almost nothing. You grant exactly what's needed, the principle of least privilege:
SET ROLE is a quick way to test permissions. Typical grants:
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO app_user; -- for serial/identity columns
REVOKE DELETE ON invoices FROM app_user; -- invoices can never be deleted by the app
-- Tables created in the future get these privileges too:
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;Column-level privileges
You can grant access to only some columns:
Row-level security (RLS)
Grants control tables and columns. Row-level security controls rows: each user sees only the rows a policy allows. It's the foundation of many multi-tenant SaaS apps, where one table holds every company's data.
CREATE TABLE documents (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id integer NOT NULL,
title text NOT NULL
);
INSERT INTO documents (tenant_id, title) VALUES
(1, 'Acme roadmap'), (1, 'Acme salaries'), (2, 'Globex launch plan'), (3, 'Initech TPS reports');
CREATE ROLE web_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON documents TO web_app;How it works:
USING (…)filters which existing rows are visible (forSELECT,UPDATE,DELETE).WITH CHECK (…)validates new or changed rows (INSERT,UPDATE).- The app sets
app.tenant_idfor each request, typically withSET LOCALinside the request's transaction. - With RLS enabled and no matching policy, a role sees nothing: it's deny-by-default.
Even if a developer forgets a WHERE tenant_id = … somewhere, one tenant can never see another's data.
⚠️ Superusers and the table owner bypass RLS (unless you use
ALTER TABLE … FORCE ROW LEVEL SECURITY). Make sure the app connects as a separate, non-owner role, asweb_appdoes above.
SQL injection: never build SQL with strings
The most common database vulnerability isn't in Postgres, it's in app code that glues user input into SQL:
// ❌ NEVER: user input becomes part of the SQL
const email = req.query.email; // attacker sends: ' OR '1'='1
await db.query(`SELECT * FROM users WHERE email = '${email}'`);
// becomes: SELECT * FROM users WHERE email = '' OR '1'='1' → returns every user
// ✅ ALWAYS: parameters are sent separately and never parsed as SQL
await db.query('SELECT * FROM users WHERE email = $1', [email]);Every Postgres driver (node-postgres, psycopg, JDBC…) and ORM supports parameters. Use them, always, even for values you think are safe.
Connection security
- pg_hba.conf ("host-based authentication") controls which roles can connect from which addresses, and how they authenticate. Allow only your app servers' network.
- Use scram-sha-256 passwords (the modern default;
md5is deprecated) or certificate auth. - Require TLS for connections over a network:
sslmode=requireorverify-fullin the connection string. - Keep the database off the public internet: put it in a private network.
- Store credentials in a secrets manager or environment variables, never in git.
Practice
- Create a role
reporterthat canSELECTfromordersandproductsbut notcustomers. Test it withSET ROLE. - Add a second RLS policy so tenant 1 users can also read (not write) documents with
tenant_id = 3. (Hint: policies are combined with OR; useFOR SELECT.)
1.What's the difference between a role with LOGIN and one without?
2.In an RLS policy, what does WITH CHECK control?
3.Which code is safe from SQL injection?