feat: enforce postgres tls and separate database roles

This commit is contained in:
2026-11-30 16:36:14 +03:00
parent ea50b60f7f
commit 1d6b745015
7 changed files with 104 additions and 27 deletions
+6 -1
View File
@@ -24,7 +24,12 @@ COPY test ./test
CMD ["npm", "test"] CMD ["npm", "test"]
FROM build AS migrate FROM build AS migrate
CMD ["sh", "-c", "DATABASE_URL=\"$(cat \"$DATABASE_URL_FILE\")\" exec npx prisma migrate deploy"] RUN apt-get update \
&& apt-get install -y --no-install-recommends postgresql-client \
&& rm -rf /var/lib/apt/lists/*
COPY infra/postgres/migrate.sh infra/postgres/grants.sql ./infra/postgres/
USER node
CMD ["sh", "/app/infra/postgres/migrate.sh"]
FROM build AS prod-deps FROM build AS prod-deps
RUN npm prune --omit=dev RUN npm prune --omit=dev
+30 -24
View File
@@ -63,24 +63,29 @@ services:
postgres: postgres:
image: postgres:17.2-alpine image: postgres:17.2-alpine
environment: environment:
POSTGRES_USER: messenger POSTGRES_USER: stand_operator
POSTGRES_DB: messenger POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/pg_password POSTGRES_PASSWORD_FILE: /run/tls/operator_password
command: ["postgres", "-c", "ssl=on", "-c", "ssl_cert_file=/run/tls/postgres.crt",
"-c", "ssl_key_file=/run/tls/postgres.key", "-c", "ssl_min_protocol_version=TLSv1.2",
"-c", "hba_file=/etc/postgresql/pg_hba.conf"]
security_opt: [no-new-privileges:true]
volumes: volumes:
- pgdata:/var/lib/postgresql/data - pgdata:/var/lib/postgresql/data
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: postgres } } - ./infra/postgres/init.sh:/docker-entrypoint-initdb.d/roles.sh:ro
- ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
- {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: postgres}}
healthcheck:
test: ["CMD", "pg_isready", "-d", "host=postgres dbname=messenger user=migrate sslmode=verify-full sslrootcert=/run/tls/ca.crt"]
interval: 3s
timeout: 3s
retries: 15
depends_on:
bootstrap: {condition: service_completed_successfully}
restart: unless-stopped
deploy: deploy:
resources: resources:
limits: { cpus: "1.0", memory: 512M } limits: {cpus: "1.0", memory: 512M}
healthcheck:
test: ["CMD", "pg_isready", "-U", "messenger", "-d", "messenger"]
interval: 5s
timeout: 3s
retries: 10
depends_on:
secrets-init:
condition: service_completed_successfully
restart: unless-stopped
redis: redis:
image: redis:7.4.1-alpine image: redis:7.4.1-alpine
@@ -158,20 +163,18 @@ services:
condition: service_healthy condition: service_healthy
migrate: migrate:
<<: *lockdown
build: build:
context: . context: .
target: migrate target: migrate
image: mtusi-messenger-lab7-migrate:dev image: mtusi-messenger-lab7-migrate:dev
environment:
DATABASE_URL_FILE: /run/secrets/database_url
volumes: volumes:
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: migrate } } - {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: migrate}}
depends_on:
postgres: {condition: service_healthy}
deploy: deploy:
resources: resources:
limits: { cpus: "0.5", memory: 512M } limits: {cpus: "0.5", memory: 512M}
depends_on:
postgres:
condition: service_healthy
api: api:
build: build:
@@ -185,7 +188,7 @@ services:
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
SHUTDOWN_DELAY_MS: 3000 SHUTDOWN_DELAY_MS: 3000
DATABASE_URL_FILE: /run/secrets/database_url DATABASE_URL_FILE: /run/tls/database_url
CACHE_URL_FILE: /run/secrets/cache_url CACHE_URL_FILE: /run/secrets/cache_url
S3_ENDPOINT: http://s3:9000 S3_ENDPOINT: http://s3:9000
S3_REGION: ${S3_REGION:-us-east-1} S3_REGION: ${S3_REGION:-us-east-1}
@@ -223,7 +226,7 @@ services:
image: mtusi-messenger-lab7-api:dev image: mtusi-messenger-lab7-api:dev
command: ["node", "dist/reconcile.js", "--apply", "--loop", "--grace-seconds=${RECONCILE_GRACE_SECONDS:-3600}", "--interval-seconds=${RECONCILE_INTERVAL_SECONDS:-300}"] command: ["node", "dist/reconcile.js", "--apply", "--loop", "--grace-seconds=${RECONCILE_GRACE_SECONDS:-3600}", "--interval-seconds=${RECONCILE_INTERVAL_SECONDS:-300}"]
environment: environment:
DATABASE_URL_FILE: /run/secrets/database_url DATABASE_URL_FILE: /run/tls/database_url
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
S3_ENDPOINT: http://s3:9000 S3_ENDPOINT: http://s3:9000
S3_REGION: ${S3_REGION:-us-east-1} S3_REGION: ${S3_REGION:-us-east-1}
@@ -232,6 +235,7 @@ services:
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
volumes: volumes:
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: reconciler } } - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: reconciler } }
- { type: volume, source: pki, target: /run/tls, read_only: true, volume: { subpath: reconciler } }
deploy: deploy:
resources: resources:
limits: { cpus: "0.25", memory: 128M } limits: { cpus: "0.25", memory: 128M }
@@ -272,7 +276,7 @@ services:
image: mtusi-messenger-lab7-api:dev image: mtusi-messenger-lab7-api:dev
command: ["node", "dist/relay.js"] command: ["node", "dist/relay.js"]
environment: environment:
DATABASE_URL_FILE: /run/secrets/database_url DATABASE_URL_FILE: /run/tls/database_url
BROKER_URL_FILE: /run/secrets/broker_url BROKER_URL_FILE: /run/secrets/broker_url
JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300} JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300}
RELAY_FAULT: ${RELAY_FAULT:-} RELAY_FAULT: ${RELAY_FAULT:-}
@@ -280,6 +284,7 @@ services:
OTEL_SERVICE_NAME: messenger-relay OTEL_SERVICE_NAME: messenger-relay
volumes: volumes:
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: relay } } - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: relay } }
- { type: volume, source: pki, target: /run/tls, read_only: true, volume: { subpath: relay } }
deploy: deploy:
resources: resources:
limits: { cpus: "0.25", memory: 128M } limits: { cpus: "0.25", memory: 128M }
@@ -300,7 +305,7 @@ services:
image: mtusi-messenger-lab7-api:dev image: mtusi-messenger-lab7-api:dev
command: ["node", "dist/worker.js"] command: ["node", "dist/worker.js"]
environment: environment:
DATABASE_URL_FILE: /run/secrets/database_url DATABASE_URL_FILE: /run/tls/database_url
BROKER_URL_FILE: /run/secrets/broker_url BROKER_URL_FILE: /run/secrets/broker_url
S3_ENDPOINT: http://s3:9000 S3_ENDPOINT: http://s3:9000
S3_REGION: ${S3_REGION:-us-east-1} S3_REGION: ${S3_REGION:-us-east-1}
@@ -317,6 +322,7 @@ services:
OTEL_SERVICE_NAME: messenger-worker OTEL_SERVICE_NAME: messenger-worker
volumes: volumes:
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: worker } } - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: worker } }
- { type: volume, source: pki, target: /run/tls, read_only: true, volume: { subpath: worker } }
deploy: deploy:
resources: resources:
limits: { cpus: "1.0", memory: 768M } limits: { cpus: "1.0", memory: 768M }
+16 -2
View File
@@ -59,12 +59,19 @@ def bundle(directory, name, pair):
write(directory / name, pair[1].read_text() + pair[0].read_text()) write(directory / name, pair[1].read_text() + pair[0].read_text())
def db_url(role, password, limit):
return (f"postgresql://{role}:{password}@postgres:5432/messenger?"
f"sslmode=require&sslaccept=strict&sslcert=/run/tls/ca.crt&connection_limit={limit}"
"&pool_timeout=5&connect_timeout=5&socket_timeout=10"
f"&application_name={role}&options=-c%20statement_timeout%3D5000")
def main(): def main():
if (ROOT / "initialized").is_file(): if (ROOT / "initialized").is_file():
print("Local identities already initialized") print("Local identities already initialized")
return return
os.umask(0o077) os.umask(0o077)
names = ("operator", "lb", "checks", *ROLES) names = ("operator", "lb", "checks", "postgres", "migrate", *ROLES)
directories = {name: ROOT / name for name in names} directories = {name: ROOT / name for name in names}
for directory in directories.values(): for directory in directories.values():
directory.mkdir(exist_ok=True) directory.mkdir(exist_ok=True)
@@ -94,8 +101,15 @@ def main():
foreign_dir.rmdir() foreign_dir.rmdir()
shutil.copyfile(foreign_ca[1], checks / "foreign-ca.crt") shutil.copyfile(foreign_ca[1], checks / "foreign-ca.crt")
leaf(directories["postgres"], "postgres", server_ca)
passwords = {role: secrets.token_hex(24) for role in (*ROLES, "migrate", "operator")}
for role, password in passwords.items():
write(directories["postgres"] / f"{role}_password", password)
write(directories["migrate"] / "database_url", db_url("migrate", passwords["migrate"], 2))
for role, limit in ROLES.items():
write(directories[role] / "database_url", db_url(role, passwords[role], limit))
shutil.copyfile(api / "api.crt", checks / "api.crt") shutil.copyfile(api / "api.crt", checks / "api.crt")
owners = {"lb": 1000, **dict.fromkeys(ROLES, 1000)} owners = {"lb": 1000, "postgres": 70, "migrate": 1000, **dict.fromkeys(ROLES, 1000)}
for name, uid in owners.items(): for name, uid in owners.items():
own(directories[name], uid) own(directories[name], uid)
(ROOT / "initialized").touch() (ROOT / "initialized").touch()
+15
View File
@@ -0,0 +1,15 @@
GRANT SELECT, INSERT ON users, chats, chat_members, messages, message_attachments,
idempotency_keys, attachments, attachment_jobs, job_events, outbox TO api;
GRANT SELECT, INSERT, DELETE ON sessions TO api;
GRANT DELETE ON idempotency_keys TO api;
GRANT SELECT ON attachment_variants TO api;
GRANT SELECT, UPDATE ON attachments, attachment_jobs TO worker, relay;
GRANT SELECT, INSERT ON job_events TO worker, relay;
GRANT SELECT, INSERT ON attachment_variants TO worker;
GRANT SELECT, INSERT ON outbox TO worker;
GRANT SELECT, INSERT, UPDATE ON outbox TO relay;
GRANT USAGE ON SEQUENCE job_events_id_seq, outbox_id_seq TO api, worker, relay;
GRANT SELECT, UPDATE (staging_key, updated_at) ON attachments TO reconciler;
GRANT SELECT ON attachment_variants TO reconciler;
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
set -eu
export MIGRATE_PASSWORD="$(cat /run/tls/migrate_password)"
export API_PASSWORD="$(cat /run/tls/api_password)"
export WORKER_PASSWORD="$(cat /run/tls/worker_password)"
export RELAY_PASSWORD="$(cat /run/tls/relay_password)"
export RECONCILER_PASSWORD="$(cat /run/tls/reconciler_password)"
psql -X -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<'SQL'
\getenv migrate_password MIGRATE_PASSWORD
\getenv api_password API_PASSWORD
\getenv worker_password WORKER_PASSWORD
\getenv relay_password RELAY_PASSWORD
\getenv reconciler_password RECONCILER_PASSWORD
CREATE ROLE migrate LOGIN PASSWORD :'migrate_password';
CREATE ROLE api LOGIN PASSWORD :'api_password';
CREATE ROLE worker LOGIN PASSWORD :'worker_password';
CREATE ROLE relay LOGIN PASSWORD :'relay_password';
CREATE ROLE reconciler LOGIN PASSWORD :'reconciler_password';
ALTER DATABASE messenger OWNER TO migrate;
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
GRANT CONNECT ON DATABASE messenger TO api, worker, relay, reconciler;
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO api, worker, relay, reconciler;
SQL
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
DATABASE_URL="$(cat /run/tls/database_url)"
export DATABASE_URL
npx prisma migrate deploy
PGPASSWORD="$(node -p 'new URL(process.env.DATABASE_URL).password')"
export PGPASSWORD
psql -X -v ON_ERROR_STOP=1 \
'host=postgres dbname=messenger user=migrate sslmode=verify-full sslrootcert=/run/tls/ca.crt' \
-f /app/infra/postgres/grants.sql
+3
View File
@@ -0,0 +1,3 @@
local all all trust
hostssl messenger all all scram-sha-256
hostssl postgres migrate all scram-sha-256