forked from mtusi2026/mtusi2026lab7
30 lines
1.8 KiB
Bash
30 lines
1.8 KiB
Bash
#!/bin/sh
|
|
# Runs ONCE, when the volume pgdata is initialised (docker-entrypoint-initdb.d), as OS user postgres
|
|
# over the local socket. Creates one login role per service; the passwords come from Docker secret
|
|
# files and are passed to psql as variables (never on a command line, never printed).
|
|
# messenger_migrate owns the database objects (applies migrations, service `migrate`)
|
|
# messenger_api / messenger_relay / messenger_worker GRANTs in migrations/0007_least_privilege.sql
|
|
# messenger_jobctl / messenger_auditor operator tools (profile tools)
|
|
# Nobody but `postgres` (no network login, see pg_hba.conf) is a superuser.
|
|
set -eu
|
|
for role in migrate api relay worker jobctl auditor; do
|
|
pw="$(tr -d '\r\n' < "/run/secrets/pg_${role}_password")"
|
|
psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres -v role="messenger_${role}" -v pw="$pw" <<'SQL'
|
|
CREATE ROLE :"role" LOGIN PASSWORD :'pw' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;
|
|
SQL
|
|
done
|
|
psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres <<'SQL'
|
|
ALTER DATABASE messenger OWNER TO messenger_migrate;
|
|
-- Only the service roles may connect to the application database.
|
|
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
|
|
GRANT CONNECT ON DATABASE messenger TO messenger_migrate, messenger_api, messenger_relay, messenger_worker,
|
|
messenger_jobctl, messenger_auditor;
|
|
SQL
|
|
psql -v ON_ERROR_STOP=1 --username postgres --dbname messenger <<'SQL'
|
|
-- PostgreSQL 15+: schema public belongs to pg_database_owner (= messenger_migrate now), and
|
|
-- PUBLIC has no CREATE on it. Make it explicit: only the owner creates objects.
|
|
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
|
|
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_relay, messenger_worker, messenger_jobctl, messenger_auditor;
|
|
SQL
|
|
echo "initdb: service roles created"
|