PortGate

Resources · Security guides · Security guide

One database user per application, with only the rights it needs

Apps should not connect as root or postgres. Create one user per app, grant it one database, and keep migration rights separate where you can.

Check command

grep -E '^DB_USERNAME=' /var/www/*/shared/.env /var/www/*/.env 2>/dev/null

Copied.

When every app connects as root or postgres, an SQL injection in one app reads and drops every database on the server, and can sometimes read files or run commands through database features. A dedicated user per app limits the damage to that app's own data.

Check what your apps use

grep -E '^DB_USERNAME=' /var/www/*/shared/.env /var/www/*/.env 2>/dev/null

root, postgres, admin or the same username for several apps are the cases to fix.

PostgreSQL

CREATE ROLE shop LOGIN PASSWORD 'generate-a-long-random-one';
CREATE DATABASE shop OWNER shop;
REVOKE ALL ON DATABASE shop FROM PUBLIC;

Owning its database lets the app run migrations. It cannot see other databases, create roles, or read server files. In PostgreSQL 15 and later, ordinary users can no longer create objects in the public schema of databases they do not own, which closes an old cross-database gap.

MySQL and MariaDB

CREATE USER 'shop'@'localhost' IDENTIFIED BY 'generate-a-long-random-one';
GRANT ALL PRIVILEGES ON shop.* TO 'shop'@'localhost';

'localhost' means the user can only connect from this host. Do not grant FILE, SUPER, PROCESS or *.* rights to an application user: FILE alone lets SQL injection read files like /etc/passwd or write into the web root.

Separate migrations from the running app (optional)

For apps where data matters most, use two users: one that owns the schema and runs migrations during deploys, and one the app uses at runtime with SELECT, INSERT, UPDATE, DELETE only. An injection in the running app then cannot drop tables.

-- PostgreSQL runtime user
CREATE ROLE shop_app LOGIN PASSWORD '...';
GRANT CONNECT ON DATABASE shop TO shop_app;
GRANT USAGE ON SCHEMA public TO shop_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO shop_app;
ALTER DEFAULT PRIVILEGES FOR ROLE shop IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO shop_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO shop_app;

After the change

Update DB_USERNAME and DB_PASSWORD, clear and rebuild the config cache, and confirm the app works. Then change the old shared password, because it has been sitting in several .env files.