Sub topic 8
Creating Application Users with Least Privilege
This chapter assumes that the database server is installed, you can connect as a database administrator, and you know basic SQL and Linux networking. The goal is to give an application only the permissions it needs.
Roles, users, and host restrictions
A database role is an identity that can log in or own database objects. PostgreSQL uses roles for both users and groups. MySQL calls a login account a user, and an account includes both a name and a host pattern.
Do not let an application connect as postgres, root, or another administrative account. Create a separate account for each application. This makes access easier to audit and limits damage if a password is exposed.
| Database | Login identity | Host restriction |
|---|---|---|
| PostgreSQL | `appuser` role | Controlled by `pg_hba.conf` |
| MySQL | `'appuser'@'10.0.0.%'` | Included in the account name |
Create a restricted account
PostgreSQL separates database access from schema and table access. The following commands create an application-owned database and restrict the account to normal data operations:
-- Run as a PostgreSQL administrator
CREATE ROLE appuser LOGIN PASSWORD 'replace-with-a-secret';
CREATE DATABASE appdb OWNER appuser;
\c appdb
REVOKE ALL 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, UPDATE
ON ALL SEQUENCES IN SCHEMA public TO appuser;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO appuser;The default privileges matter because permissions granted to existing tables do not automatically apply to tables created later.
MySQL grants privileges at different scopes. This example permits the application to connect from one private subnet and to read and modify data in appdb:
-- Run as a MySQL administrator
CREATE DATABASE appdb;
CREATE USER 'appuser'@'10.0.0.%'
IDENTIFIED BY 'replace-with-a-secret';
GRANT SELECT, INSERT, UPDATE, DELETE
ON appdb.* TO 'appuser'@'10.0.0.%';
SHOW GRANTS FOR 'appuser'@'10.0.0.%';Do not grant DROP, ALTER, CREATE USER, FILE, or administrative privileges unless the application genuinely needs them. Use a separate migration account for schema changes.
Verify the effective permissions
Test with the application account, not only with an administrator account. A successful connection proves authentication, but each SQL operation must also be tested. Confirm that expected SELECT, INSERT, UPDATE, and DELETE statements work, while administrative statements fail.
Exercise
Why should an application use a separate account instead of the database administrator account?
Show answer
A separate account limits the application's permissions, makes activity attributable to that application, and reduces the damage caused by a stolen credential.