#!/usr/bin/env python3 """Create local synthetic credentials and the PKI of the stand in ./secrets (ignored by Git). .venv/Scripts/python scripts/init_secrets.py (Linux/macOS: .venv/bin/python) Idempotent: existing files are kept, so re-running never changes passwords of a database that already has data. Prints only file names, never values. Delete ./secrets together with the volumes (`docker compose down -v`) to start over. Lab 7: one credential per service and role (contracts/trust-matrix.md): PostgreSQL postgres (superuser: initdb + operator via `docker compose exec`, never over the network), messenger_migrate (owner of the schema), messenger_api / _relay / _worker (GRANT only what the service does, migrations/0007_least_privilege.sql), messenger_jobctl / _auditor (operator tools). Every URL has sslmode=verify-full. Valkey ACL user `api` (session:* and ratelimit:* keys, a few commands), `default` user off. S3 admin (s3-init only) / api / worker / auditor key pairs. RabbitMQ relay (publish only) / worker (consume only), amqps:// (TLS 5671). The application services do not mount these files from lab 7 step 5 on: they read their own values from OpenBao (scripts/bao_operator.py copies them there), see docs/OPERATOR.md. """ from __future__ import annotations import base64 import hashlib import json import os import secrets import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SECRETS = ROOT / "secrets" CA = "/run/secrets/internal-ca.crt" # path INSIDE the containers DB_ROLES = ("migrate", "api", "relay", "worker", "jobctl", "auditor") def write(name: str, value: str) -> None: path = SECRETS / name if path.exists(): print(f"keep secrets/{name}") return path.write_text(value + "\n", encoding="utf-8", newline="\n") # Readable by the container users (postgres, valkey, seaweedfs, rabbitmq, app uid 10001) # through the compose bind mount; the folder ./secrets itself is 0700 for the host user. os.chmod(path, 0o644) print(f"created secrets/{name}") def read(name: str) -> str: return (SECRETS / name).read_text(encoding="utf-8").strip() def rabbit_hash(password: str) -> str: """RabbitMQ `rabbit_password_hashing_sha256`: base64(salt + sha256(salt + password)), 4-byte salt. The broker stores and compares only this hash; the plain password is in the client's URL.""" salt = secrets.token_bytes(4) return base64.b64encode(salt + hashlib.sha256(salt + password.encode("utf-8")).digest()).decode("ascii") def main() -> int: SECRETS.mkdir(exist_ok=True) os.chmod(SECRETS, 0o700) # PostgreSQL: superuser (no network login, pg_hba) + one login role per service. write("postgres_password", secrets.token_urlsafe(24)) # [A-Za-z0-9_-]: safe inside URLs for role in DB_ROLES: write(f"pg_{role}_password", secrets.token_urlsafe(24)) write(f"database_url_{role}", f"postgresql://messenger_{role}:{read(f'pg_{role}_password')}@postgres:5432/" f"messenger?sslmode=verify-full&sslrootcert={CA}") # Valkey: ACL user `api` (infra/valkey/start.sh); TLS only (rediss). write("valkey_api_password", secrets.token_urlsafe(24)) write("cache_url", f"rediss://api:{read('valkey_api_password')}@valkey:6379/0") # S3 key pairs (SeaweedFS identities, infra/seaweedfs/start.sh): admin = bucket bootstrap only; # api = Write staging + Read final; worker = Read/Write both; auditor = Read + List (no Write). for who in ("admin", "api", "worker", "auditor"): write(f"s3_{who}_access_key_id", "AK" + secrets.token_hex(9).upper()) write(f"s3_{who}_secret_access_key", secrets.token_hex(20)) # RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume the jobs # queue; neither may declare/delete anything (configure "^$"). write("rabbitmq_relay_password", secrets.token_urlsafe(24)) write("rabbitmq_worker_password", secrets.token_urlsafe(24)) users = { "users": [{"name": who, "password_hash": rabbit_hash(read(f"rabbitmq_{who}_password")), "hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []} for who in ("relay", "worker")], "permissions": [ {"user": "relay", "vhost": "/", "configure": "^$", "write": "^messenger\\.jobs$", "read": "^$"}, {"user": "worker", "vhost": "/", "configure": "^$", "write": "^$", "read": "^messenger\\.attachment-jobs$"}, ], } write("rabbitmq_users.json", json.dumps(users, indent=1)) for who in ("relay", "worker"): # AMQP heartbeat 10 s: a frozen client loses its connection after ~2 missed heartbeats, and # the broker returns its unacked messages to the queue for the other consumers. write(f"broker_url_{who}", f"amqps://{who}:{read(f'rabbitmq_{who}_password')}@broker:5671/?heartbeat=10") # Grafana admin (UI on https://localhost:3000 and the evidence scripts, via its datasource proxy). write("grafana_admin_password", secrets.token_urlsafe(18)) # Lab 7: local PKI (two CAs + service certificates) in ./secrets/pki. sys.path.insert(0, str(Path(__file__).resolve().parent)) import init_pki return init_pki.main() if __name__ == "__main__": sys.exit(main())