Files
mtusi2026lab7/scripts/gen-secrets.sh
T
ejur22 d995f98446
Skeleton contracts / contracts (pull_request) Canceled after 0s
Lab 7
2026-11-27 20:47:58 +03:00

65 lines
2.7 KiB
Bash

#!/bin/sh
set -eu
# Generate local (gitignored) compose secrets with random credentials.
# Writes database, cache and S3 credentials plus the SeaweedFS S3 config that
# declares the limited "messenger-api" identity (separate from root).
cd "$(dirname "$0")/.."
mkdir -p secrets
BUCKET="${S3_BUCKET:-messenger-attachments}"
rand() { head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n'; }
PASSWORD=$(rand)
ROOT_KEY="root$(rand)"
ROOT_SECRET=$(rand)
API_KEY="api$(rand)"
API_SECRET=$(rand)
BROKER_PASSWORD=$(rand)
API_DB_PASSWORD=$(rand)
WORKER_DB_PASSWORD=$(rand)
# --- PostgreSQL: verify-full TLS against the project CA (lab7) ---
printf '%s' "$PASSWORD" > secrets/database_password
printf '%s' "postgresql://messenger:${PASSWORD}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/ca.crt" > secrets/database_url
printf '%s' "redis://valkey:6379/0" > secrets/cache_url
printf '%s' "$BROKER_PASSWORD" > secrets/broker_password
# Internal broker is TLS + EXTERNAL auth (client certificate), so the URL
# carries no password; the CN of the client cert is the RabbitMQ user.
printf '%s' "amqps://broker:5671/%2F" > secrets/broker_url
# Least-privilege database roles (lab7): api vs worker have separate logins.
# migrate.py applies the grants; these files only carry the password/URL.
printf '%s' "$API_DB_PASSWORD" > secrets/database_api_password
printf '%s' "postgresql://messenger_api:${API_DB_PASSWORD}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/ca.crt" > secrets/database_api_url
printf '%s' "$WORKER_DB_PASSWORD" > secrets/database_worker_password
printf '%s' "postgresql://messenger_worker:${WORKER_DB_PASSWORD}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/ca.crt" > secrets/database_worker_url
printf '%s' "$ROOT_KEY" > secrets/s3_root_access_key_id
printf '%s' "$ROOT_SECRET" > secrets/s3_root_secret_access_key
printf '%s' "$API_KEY" > secrets/s3_access_key_id
printf '%s' "$API_SECRET" > secrets/s3_secret_access_key
# The API/worker identity may only Read/Write/List/Delete THIS bucket; root
# (Admin) is used solely by the one-shot s3-init bootstrap.
cat > secrets/s3_config.json <<EOF
{
"identities": [
{
"name": "root",
"credentials": [{"accessKey": "${ROOT_KEY}", "secretKey": "${ROOT_SECRET}"}],
"actions": ["Admin", "Read", "Write", "List", "Tagging", "Delete"]
},
{
"name": "messenger-api",
"credentials": [{"accessKey": "${API_KEY}", "secretKey": "${API_SECRET}"}],
"actions": ["Read:${BUCKET}", "Write:${BUCKET}", "List:${BUCKET}", "Delete:${BUCKET}"]
}
]
}
EOF
chmod 600 secrets/* 2>/dev/null || true
echo "Wrote ./secrets/{database_password,database_url,database_{api,worker}_*,cache_url,broker_*,s3_*,s3_config.json} (not committed)."