Day 6: Setting Up PostgreSQL Databases, Roles, Schemas and Privileges for an Application
1. Objective
A hands-on PostgreSQL lab for DBAs: create a database with its own owner, a dedicated schema, a group role and a least-privilege application user. On pg17-prod01 (PostgreSQL 17 on Oracle Linux 9) we build hrdb, owned by hr_owner, with schema hr, a group role hr_rw and an application login hr_app that can read and change data, but cannot create or drop anything. This builds on Day 3 (postgresql.conf and pg_hba.conf essentials).
2. The concept in two minutes
Users and roles are the same thing. In PostgreSQL a user is a role with the LOGIN attribute. A role without LOGIN acts as a group: grant privileges to the group once, then grant the group to as many users as you need. Access stays tidy when people and applications come and go.
Access works in three layers. To read a table, a role needs CONNECT on the database, USAGE on the schema and a privilege such as SELECT on the table. Miss one layer and the query fails.
- Every new database lets
PUBLIC(every role) connect by default, so we revoke that. GRANT ... ON ALL TABLESonly covers tables that exist now. For tables created later we useALTER DEFAULT PRIVILEGES, which applies to objects created by the role that set it.- Since PostgreSQL 15, ordinary roles can no longer create objects in the
publicschema, so we give the application its own schema.
▶ Watch on YouTube: https://youtu.be/B7N-x-1yo5Q
3. Architecture
4. Prerequisites
| Item | Lab value |
|---|---|
| Host | pg17-prod01.dba365.lab · 192.168.56.21 |
| OS | Oracle Linux 9 · 2 vCPU · 4 GB RAM · 20 GB disk |
| Software | PostgreSQL 17 from the PGDG repository, service postgresql-17 running, PGDATA /var/lib/pgsql/17/data |
| OS users | root to log in, postgres for every database step |
| Builds on | Day 3: postgresql.conf and pg_hba.conf essentials (default local all all peer line still in place) |
5. Implementation
All steps run on pg17-prod01. Log in as root, switch to the postgres OS user once, and stay there until the end. No password is ever typed on a command line: \password prompts for it, so it does not land in shell history or the server log.
Step 1 — Owner role and database (pg17-prod01 · OS user postgres)
[root@pg17-prod01 ~]# su - postgres
[postgres@pg17-prod01 ~]$ psql
postgres=# CREATE ROLE hr_owner LOGIN;
CREATE ROLE
postgres=# \password hr_owner
Enter new password for user "hr_owner":
Enter it again:
postgres=# CREATE DATABASE hrdb OWNER hr_owner;
CREATE DATABASE
postgres=# REVOKE CONNECT ON DATABASE hrdb FROM PUBLIC;
REVOKE
postgres=# \q
What this does: creates the owner login, sets its password at a prompt, creates hrdb owned by it, and removes the default right of every role to connect to hrdb.
Step 2 — pg_hba.conf rule for hrdb (pg17-prod01 · OS user postgres)
[postgres@pg17-prod01 ~]$ cd /var/lib/pgsql/17/data
[postgres@pg17-prod01 data]$ cp -p pg_hba.conf pg_hba.conf.day6.bak
[postgres@pg17-prod01 data]$ sed -i '/^local\s\+all\s\+all\s\+peer/i\
> local hrdb all scram-sha-256' pg_hba.conf
[postgres@pg17-prod01 data]$ grep '^local' pg_hba.conf
local hrdb all scram-sha-256
local all all peer
local replication all peer
[postgres@pg17-prod01 data]$ psql -c "SELECT pg_reload_conf();"
pg_reload_conf
----------------
t
(1 row)
What this does: keeps a backup, inserts one SCRAM password rule for hrdb above the default peer line (the first matching line wins), and reloads the file without a restart. Type the > line without the >; it is the shell's continuation prompt. sed is used so the lab is repeatable; on a real server you can make the same edit in vi. We do not touch the default line.
Step 3 — Schema and search_path (pg17-prod01 · OS user postgres · database role hr_owner)
[postgres@pg17-prod01 data]$ psql -d hrdb -U hr_owner
Password for user hr_owner:
hrdb=> CREATE SCHEMA hr;
CREATE SCHEMA
hrdb=> ALTER ROLE hr_owner IN DATABASE hrdb SET search_path = hr;
ALTER ROLE
hrdb=> \q
[postgres@pg17-prod01 data]$ psql -d hrdb -U hr_owner -c "SHOW search_path;"
Password for user hr_owner:
search_path
-------------
hr
(1 row)
What this does: creates schema hr owned by hr_owner and makes hr its default search path in hrdb only. The setting applies from the next connection, which is why we reconnect to check it.
Step 4 — Group role and application user (pg17-prod01 · OS user postgres)
[postgres@pg17-prod01 data]$ psql
postgres=# CREATE ROLE hr_rw NOLOGIN;
CREATE ROLE
postgres=# CREATE ROLE hr_app LOGIN;
CREATE ROLE
postgres=# \password hr_app
Enter new password for user "hr_app":
Enter it again:
postgres=# GRANT hr_rw TO hr_app;
GRANT ROLE
postgres=# GRANT CONNECT ON DATABASE hrdb TO hr_rw;
GRANT
postgres=# \q
What this does: creates the group hr_rw (no login), the application login hr_app, makes hr_app a member (it inherits the group's privileges by default) and lets the group connect to hrdb.
Step 5 — Schema access and default privileges (pg17-prod01 · OS user postgres · database role hr_owner)
[postgres@pg17-prod01 data]$ psql -d hrdb -U hr_owner
Password for user hr_owner:
hrdb=> GRANT USAGE ON SCHEMA hr TO hr_rw;
GRANT
hrdb=> ALTER DEFAULT PRIVILEGES IN SCHEMA hr
hrdb-> GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO hr_rw;
ALTER DEFAULT PRIVILEGES
hrdb=> ALTER DEFAULT PRIVILEGES IN SCHEMA hr
hrdb-> GRANT USAGE ON SEQUENCES TO hr_rw;
ALTER DEFAULT PRIVILEGES
hrdb=> CREATE TABLE employees (emp_id int GENERATED ALWAYS AS IDENTITY
hrdb(> PRIMARY KEY, full_name text NOT NULL, dept text);
CREATE TABLE
hrdb=> \q
What this does: lets hr_rw see objects in hr, and pre-grants data access on every table and sequence that hr_owner creates in hr from now on. It must run as hr_owner, because default privileges only apply to objects created by the role that set them. employees lands in hr through the search path.
Step 6 — Test as the application user (pg17-prod01 · OS user postgres · database role hr_app)
[postgres@pg17-prod01 data]$ psql -d hrdb -U hr_app
Password for user hr_app:
hrdb=> INSERT INTO hr.employees (full_name, dept) VALUES ('Test User', 'IT');
INSERT 0 1
hrdb=> SELECT emp_id, full_name, dept FROM hr.employees;
emp_id | full_name | dept
--------+-----------+------
1 | Test User | IT
(1 row)
hrdb=> CREATE TABLE hr.t1 (id int);
ERROR: permission denied for schema hr
LINE 1: CREATE TABLE hr.t1 (id int);
^
hrdb=> DROP TABLE hr.employees;
ERROR: must be owner of table employees
hrdb=> \q
What this does: proves the access model: hr_app reads and writes rows through hr_rw without any extra grant, but cannot create objects in hr or drop a table it does not own.
6. What each step does (summary)
- Step 1: owner role + database,
PUBLICcan no longer connect. - Step 2: password (SCRAM) authentication for
hrdbover the local socket. Lab note: we only add alocal(Unix socket) rule; remote access fromdba-admin01needs ahost/hostsslline as in Day 3. - Step 3: dedicated schema;
search_pathset per role and per database. - Step 4: group role carries the privileges; users only get membership.
- Step 5: default privileges make future tables usable without re-granting.
- Step 6: positive and negative tests of the application user.
7. Validation
Run as postgres on pg17-prod01, connecting as hr_owner (the hrdb rule asks every role for a password):
[postgres@pg17-prod01 data]$ psql -d hrdb -U hr_owner
Password for user hr_owner:
hrdb=> SELECT rolname, rolcanlogin FROM pg_roles
hrdb-> WHERE rolname IN ('hr_owner', 'hr_rw', 'hr_app') ORDER BY 1;
rolname | rolcanlogin
----------+-------------
hr_app | t
hr_owner | t
hr_rw | f
(3 rows)
hrdb=> SELECT has_database_privilege('hr_app', 'hrdb', 'CONNECT') AS can_connect,
hrdb-> has_schema_privilege('hr_app', 'hr', 'CREATE') AS can_create,
hrdb-> has_table_privilege('hr_app', 'hr.employees', 'SELECT') AS can_select;
can_connect | can_create | can_select
-------------+------------+------------
t | f | t
(1 row)
hrdb=> SELECT defaclobjtype, defaclacl FROM pg_default_acl ORDER BY 1;
defaclobjtype | defaclacl
---------------+-----------------------
S | {hr_rw=U/hr_owner}
r | {hr_rw=arwd/hr_owner}
(2 rows)
hrdb=> \q
Expected: hr_rw cannot log in, hr_app can connect and select but not create, and two default ACLs exist (r = tables with arwd = SELECT, INSERT, UPDATE, DELETE; S = sequences with U = USAGE). If other default privileges exist on your server, you will see extra rows.
8. Troubleshooting
| Error / symptom | Cause | Fix |
|---|---|---|
FATAL: Peer authentication failed for user "hr_app" | The hrdb line is below local all all peer, or the file was not reloaded. Peer requires the OS user name to match the role. | Move the line above the peer line, run SELECT pg_reload_conf(); and check SELECT * FROM pg_hba_file_rules; (also shows syntax errors). |
FATAL: permission denied for database "hrdb" · DETAIL: User does not have CONNECT privilege. | PUBLIC was revoked and the role is not in hr_rw, or CONNECT was not granted to hr_rw. | As postgres: GRANT hr_rw TO <role>; and GRANT CONNECT ON DATABASE hrdb TO hr_rw; |
FATAL: password authentication failed for user "hr_app" | Wrong password, or no password set yet. This also hits postgres itself when connecting to hrdb, because the rule covers all roles. | As postgres in the postgres database: \password hr_app. For admin work in hrdb, connect as hr_owner, or add local hrdb postgres peer above the hrdb line and reload. |
ERROR: permission denied for table employees for hr_app | The table was created by another role (for example postgres), so hr_owner's default privileges did not apply. | Create objects as hr_owner; fix existing ones with ALTER TABLE hr.employees OWNER TO hr_owner; or GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA hr TO hr_rw; |
FATAL: role "hr_rw" is not permitted to log in | Someone tried to connect with the group role. | Expected behaviour. Connect as a member login such as hr_app; keep groups NOLOGIN. |
9. Production considerations
Lab vs production
- Security: application traffic arrives over TCP, so use a line such as
hostssl hrdb hr_app <app-server-ip>/32 scram-sha-256, one per real application server, rather than a whole subnet orlocal … all. Keeppassword_encryption = scram-sha-256(the default) and never usemd5ortrust. Store passwords in a vault, not in scripts; considerVALID UNTILandCONNECTION LIMITon application logins. - Least privilege:
PUBLICstill hasTEMPORARYon new databases; revoke it if the application does not need temp tables. Use a separate migration/deploy role (member of the owner) instead of giving the application DDL rights. Add a read-only group (hr_ro) for reporting. - Sizing: role changes cost nothing, but plan
max_connectionsand use a pooler for many application sessions. - HA and backup: roles are cluster-wide and are not in a
pg_dumpofhrdb; back them up withpg_dumpall --globals-onlybefore and after the change. On a streaming replica,pg_hba.confmust be changed on each node. - Rollback plan: as postgres:
cp -p pg_hba.conf.day6.bak pg_hba.confthenSELECT pg_reload_conf();. To remove the lab:DROP DATABASE hrdb;thenDROP ROLE hr_app; DROP ROLE hr_rw; DROP ROLE hr_owner;. If a role still owns objects in another database, runREASSIGN OWNEDandDROP OWNEDthere first.
10. Practice exercise
- Create a read-only group
hr_roand a reporting loginhr_reportthat can onlySELECTfrom tables inhr, including tables created tomorrow. Hint: you needCONNECT,USAGE, aGRANT … ON ALL TABLES IN SCHEMAfor today's table, and a secondALTER DEFAULT PRIVILEGESrun ashr_owner. - Create a table in
hraspostgresand show thathr_appcannot read it. Hint: look atALTER DEFAULT PRIVILEGES FOR ROLE, or change the owner.
Next lab
Day 7: Exadata Cloud@Customer explained: field notes — an experience post on the architecture: infrastructure, VM clusters, control plane, and what the customer and Oracle each manage. Earlier labs: all DBA365 labs · PostgreSQL labs (incl. Day 3).
Need a clean role and privilege model on your own PostgreSQL servers? Our Remote DBA Support team can review and set it up with you.
Comments
Post a Comment