Sub topic 8
Creating application users with least privilege
This chapter assumes you have a running PostgreSQL or MySQL server, can open an administrative SQL session (sudo -u postgres psql or sudo mysql), and know basic SQL. You should also know how pg_hba.conf and listen addresses limit who can reach the server, which earlier chapters covered.
Why applications should not use the admin account
An application that connects as postgres or MySQL root can drop tables, read every database and create other users. A single SQL injection bug or leaked configuration file then becomes a full compromise of the server.
Least privilege means each account gets only the rights its job needs. A web application usually needs to read and write rows in its own tables. It does not need to create tables, change schemas, or touch other databases.
A common design uses three kinds of accounts:
| Account | Purpose | Typical rights |
|---|---|---|
| Administrator | Server maintenance by a human | Superuser, used rarely |
| Owner or migration account | Creates and alters tables during deployments | Full control of one database |
| Application account | Runtime queries | SELECT, INSERT, UPDATE, DELETE on that database's tables |
PostgreSQL: roles and the public schema
PostgreSQL has one concept, the role. A role with the LOGIN attribute acts as a user. Grants form two layers: privileges on the database (such as CONNECT), and privileges on objects inside it (schemas, tables, sequences).
By default, every role belongs to the pseudo-role PUBLIC, and PUBLIC can connect to any database. Remove that default first.
-- Run as a superuser, for example: sudo -u postgres psql
CREATE ROLE app_owner NOLOGIN;
CREATE ROLE appuser LOGIN PASSWORD 'change-me';
CREATE DATABASE appdb OWNER app_owner;
REVOKE ALL ON DATABASE appdb FROM PUBLIC;
GRANT CONNECT ON DATABASE appdb TO appuser;app_owner cannot log in. Your migration tool can use a separate login role that is a member of app_owner, or you can add LOGIN to it if you prefer one account. Either way, the runtime account appuser does not own the tables.
Grants on tables happen inside the database, so switch to it first.
\c appdb
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO appuser;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO appuser;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO appuser;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO appuser;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT USAGE, SELECT ON SEQUENCES TO appuser;Three details matter here:
GRANT ... ON ALL TABLESonly affects tables that exist now. Tables created later get no grants unless you setALTER DEFAULT PRIVILEGES. A common symptom after a deployment ispermission denied for table.ALTER DEFAULT PRIVILEGES FOR ROLE app_ownerapplies only to objects created by that role. If a different role creates tables, name that role instead.- Columns with
serialor identity types need sequence rights. WithoutUSAGEon the sequence, anINSERTfails even when the table grant is correct.
Since PostgreSQL 15, ordinary roles can no longer create objects in the public schema by default. On older versions the REVOKE CREATE line above is important, and on newer ones it is harmless.
MySQL: accounts are user plus host
In MySQL, an account is a pair: user name and the host it connects from. 'appuser'@'10.0.0.%' and 'appuser'@'localhost' are different accounts with separate passwords and grants.
-- Run as an administrator: sudo mysql
CREATE DATABASE appdb;
CREATE USER 'appuser'@'10.0.0.%' IDENTIFIED BY 'change-me';
GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'appuser'@'10.0.0.%';appdb.* covers every table in appdb, including tables created later, so MySQL needs no equivalent of default privileges. The host pattern is a second layer of restriction on top of the bind address and firewall. Use the narrowest pattern that works. A single address such as 'appuser'@'10.0.0.20' is stricter than a subnet pattern.
Avoid 'appuser'@'%', which accepts any source address. Also avoid GRANT ALL PRIVILEGES ON *.*, which gives server-wide rights and often includes GRANT OPTION, the ability to pass those rights on.
MySQL 8.0 and later support roles, which let you define a privilege set once and attach it to several accounts:
CREATE ROLE 'app_rw';
GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app_rw';
GRANT 'app_rw' TO 'appuser'@'10.0.0.%';
SET DEFAULT ROLE 'app_rw' TO 'appuser'@'10.0.0.%';Without SET DEFAULT ROLE, the role is not active when the user logs in, and queries fail with a privilege error.
Read-only and reporting accounts
Give analysts and dashboards their own accounts with SELECT only. In PostgreSQL 14 and later, the built-in role pg_read_all_data grants read access to every table:
CREATE ROLE reporter LOGIN PASSWORD 'change-me-too';
GRANT pg_read_all_data TO reporter;That role reads all databases' tables the role can reach, so combine it with CONNECT grants and pg_hba.conf limits. For tighter control, grant SELECT on named tables. In MySQL, grant only SELECT ON appdb.*.
Handling passwords
- Do not type real passwords into
psqlormysqlon the command line, because they end up in shell history. Inpsql, run\password appuserto be prompted. In MySQL, put the password in the statement inside an interactive session, and keep~/.mysql_historyrestricted. - Generate long random passwords and store them in the application's secret store or a file readable only by the service user.
- In PostgreSQL, make sure
password_encryption = scram-sha-256is set before you set the password, so it is stored as a SCRAM verifier. It is the default in PostgreSQL 14 and later. Thescram-sha-256method inpg_hba.confonly works with SCRAM-stored passwords.
Verifying what an account can do
Always test as the application account, from the application's network location, not as the admin.
# PostgreSQL: should connect, read, and fail on DDL
psql -h 10.0.0.5 -U appuser -d appdb -c 'SELECT 1'
psql -h 10.0.0.5 -U appuser -d appdb -c 'CREATE TABLE t (id int)'
# MySQL: list grants and try a forbidden action
mysql -h 10.0.0.5 -u appuser -p -e 'SHOW GRANTS FOR CURRENT_USER()'
mysql -h 10.0.0.5 -u appuser -p appdb -e 'DROP TABLE users'The CREATE TABLE and DROP TABLE commands should fail with a permission error. In psql, \du lists roles, \dp lists table privileges, and \l shows database privileges. In MySQL, SHOW GRANTS FOR 'appuser'@'10.0.0.%' lists everything granted.
Common errors
permission denied for table ordersin PostgreSQL: the table was created after the grants ran, or by a role not covered by your default privileges.permission denied for schema public: the role lacksUSAGEon the schema.FATAL: no pg_hba.conf entry for host ...: this is an authentication rule problem, not a grant problem. The account exists but the address, database or user does not match any line.- MySQL
Access denied for user 'appuser'@'10.0.0.7': the host pattern does not match, or the client reaches the server through a different address than you assumed. Check which account you are matched to withSELECT CURRENT_USER(). - MySQL
ERROR 1044on a database: the account has no grant on that database.
Exercises
Exercise
After a deployment, the application fails in PostgreSQL with "permission denied for table invoices", a table the migration tool just created. Table grants worked for older tables. What is the likely cause and the fix?
Show answer
The grants were made with GRANT ... ON ALL TABLES, which only covers tables that existed at the time. Run the grant again for the new table, and prevent a repeat with ALTER DEFAULT PRIVILEGES FOR ROLE <the role that creates tables> IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO appuser.
Exercise
In MySQL, you created 'appuser'@'10.0.0.%' but a connection from 10.0.0.7 is rejected with "Access denied". Name two checks that narrow down the cause.
Show answer
Confirm the client's address actually matches the host pattern (the connection may arrive from a different address, such as through NAT or a proxy), and run SELECT CURRENT_USER() or SHOW GRANTS to see which account the server matched. Also confirm the password was set on this exact user-and-host account, since 'appuser'@'localhost' is a separate account.
Exercise
Why is it better for the application's runtime account not to own its tables?
Show answer
An owner can alter or drop its tables and manage their privileges. If the runtime account is compromised, for example through SQL injection, the attacker is limited to reading and changing rows. Schema changes are done by a separate owner or migration account used only during deployments.