diff --git a/Dockerfile b/Dockerfile index a689593..04f5f2a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -24,7 +24,12 @@ COPY test ./test CMD ["npm", "test"] 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 RUN npm prune --omit=dev diff --git a/compose.yaml b/compose.yaml index 7eb258f..213072e 100644 --- a/compose.yaml +++ b/compose.yaml @@ -63,24 +63,29 @@ services: postgres: image: postgres:17.2-alpine environment: - POSTGRES_USER: messenger + POSTGRES_USER: stand_operator 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: - 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: resources: - 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 + limits: {cpus: "1.0", memory: 512M} redis: image: redis:7.4.1-alpine @@ -158,20 +163,18 @@ services: condition: service_healthy migrate: + <<: *lockdown build: context: . target: migrate image: mtusi-messenger-lab7-migrate:dev - environment: - DATABASE_URL_FILE: /run/secrets/database_url 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: resources: - limits: { cpus: "0.5", memory: 512M } - depends_on: - postgres: - condition: service_healthy + limits: {cpus: "0.5", memory: 512M} api: build: @@ -185,7 +188,7 @@ services: SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} 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 S3_ENDPOINT: http://s3:9000 S3_REGION: ${S3_REGION:-us-east-1} @@ -223,7 +226,7 @@ services: 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}"] environment: - DATABASE_URL_FILE: /run/secrets/database_url + DATABASE_URL_FILE: /run/tls/database_url STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} S3_ENDPOINT: http://s3:9000 S3_REGION: ${S3_REGION:-us-east-1} @@ -232,6 +235,7 @@ services: S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key volumes: - { 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: resources: limits: { cpus: "0.25", memory: 128M } @@ -272,7 +276,7 @@ services: image: mtusi-messenger-lab7-api:dev command: ["node", "dist/relay.js"] environment: - DATABASE_URL_FILE: /run/secrets/database_url + DATABASE_URL_FILE: /run/tls/database_url BROKER_URL_FILE: /run/secrets/broker_url JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300} RELAY_FAULT: ${RELAY_FAULT:-} @@ -280,6 +284,7 @@ services: OTEL_SERVICE_NAME: messenger-relay volumes: - { 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: resources: limits: { cpus: "0.25", memory: 128M } @@ -300,7 +305,7 @@ services: image: mtusi-messenger-lab7-api:dev command: ["node", "dist/worker.js"] environment: - DATABASE_URL_FILE: /run/secrets/database_url + DATABASE_URL_FILE: /run/tls/database_url BROKER_URL_FILE: /run/secrets/broker_url S3_ENDPOINT: http://s3:9000 S3_REGION: ${S3_REGION:-us-east-1} @@ -317,6 +322,7 @@ services: OTEL_SERVICE_NAME: messenger-worker volumes: - { 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: resources: limits: { cpus: "1.0", memory: 768M } diff --git a/infra/bootstrap.py b/infra/bootstrap.py index b0cb7c3..915a5d6 100644 --- a/infra/bootstrap.py +++ b/infra/bootstrap.py @@ -59,12 +59,19 @@ def bundle(directory, name, pair): 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(): if (ROOT / "initialized").is_file(): print("Local identities already initialized") return os.umask(0o077) - names = ("operator", "lb", "checks", *ROLES) + names = ("operator", "lb", "checks", "postgres", "migrate", *ROLES) directories = {name: ROOT / name for name in names} for directory in directories.values(): directory.mkdir(exist_ok=True) @@ -94,8 +101,15 @@ def main(): foreign_dir.rmdir() 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") - owners = {"lb": 1000, **dict.fromkeys(ROLES, 1000)} + owners = {"lb": 1000, "postgres": 70, "migrate": 1000, **dict.fromkeys(ROLES, 1000)} for name, uid in owners.items(): own(directories[name], uid) (ROOT / "initialized").touch() diff --git a/infra/postgres/grants.sql b/infra/postgres/grants.sql new file mode 100644 index 0000000..ec0be05 --- /dev/null +++ b/infra/postgres/grants.sql @@ -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; diff --git a/infra/postgres/init.sh b/infra/postgres/init.sh new file mode 100644 index 0000000..b0bcc57 --- /dev/null +++ b/infra/postgres/init.sh @@ -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 diff --git a/infra/postgres/migrate.sh b/infra/postgres/migrate.sh new file mode 100644 index 0000000..11d1929 --- /dev/null +++ b/infra/postgres/migrate.sh @@ -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 diff --git a/infra/postgres/pg_hba.conf b/infra/postgres/pg_hba.conf new file mode 100644 index 0000000..b15d6bd --- /dev/null +++ b/infra/postgres/pg_hba.conf @@ -0,0 +1,3 @@ +local all all trust +hostssl messenger all all scram-sha-256 +hostssl postgres migrate all scram-sha-256