feat: add openbao and scoped service policies
This commit is contained in:
+1
-1
@@ -44,4 +44,4 @@ COPY contracts/openapi.json ./contracts/openapi.json
|
||||
USER node
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["node", "dist/main.js"]
|
||||
CMD ["node", "dist/stand.js"]
|
||||
|
||||
+123
-202
@@ -4,10 +4,28 @@ x-lockdown: &lockdown
|
||||
security_opt: [no-new-privileges:true]
|
||||
cap_drop: [ALL]
|
||||
|
||||
x-otel: &otel
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
x-runtime: &runtime
|
||||
<<: *lockdown
|
||||
image: mtusi-messenger-lab7-api:dev
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
init: true
|
||||
restart: unless-stopped
|
||||
|
||||
x-runtime-env: &runtime-env
|
||||
BAO_ADDR: https://openbao:8200
|
||||
NODE_EXTRA_CA_CERTS: /run/tls/ca.crt
|
||||
|
||||
x-s3-env: &s3-env
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_REGION: us-east-1
|
||||
|
||||
x-otel-env: &otel-env
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab
|
||||
|
||||
services:
|
||||
bootstrap:
|
||||
@@ -23,42 +41,38 @@ services:
|
||||
cap_add: [CHOWN, DAC_OVERRIDE, FOWNER]
|
||||
volumes:
|
||||
- ./infra/bootstrap.py:/work/bootstrap.py:ro
|
||||
- pki:/state
|
||||
- secrets:/state
|
||||
- baodata:/bao-data
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 96M}
|
||||
|
||||
secrets-init:
|
||||
image: alpine:3.20.3
|
||||
openbao:
|
||||
<<: *lockdown
|
||||
image: openbao/openbao:2.4.4@sha256:595c83b42614a4d2b044608e4593c05b019c5db25bc9c185d8fff3ac96c03ddd
|
||||
user: "100:1000"
|
||||
entrypoint: [bao]
|
||||
command: ["server", "-config=/bao/config/server.hcl"]
|
||||
ports:
|
||||
- "127.0.0.1:${BAO_PORT:-8200}:8200"
|
||||
volumes:
|
||||
- secrets:/secrets
|
||||
command:
|
||||
- sh
|
||||
- -ec
|
||||
- |
|
||||
cd /secrets
|
||||
mkdir -p postgres redis api migrate s3 s3-init reconciler broker rabbitmq relay worker grafana
|
||||
for entry in pg_password:postgres:24 redis_password:redis:24 s3_root_user:s3:10 s3_root_password:s3:20 s3_access_key_id:api:10 s3_secret_access_key:api:20 broker_password:broker:24 admin_password:grafana:16; do
|
||||
file=$${entry%%:*}; rest=$${entry#*:}; dir=$${rest%%:*}; size=$${rest##*:}
|
||||
[ -s "$$dir/$$file" ] || head -c "$$size" /dev/urandom | od -An -tx1 | tr -d ' \n' > "$$dir/$$file"
|
||||
done
|
||||
rm -f s3-init/* rabbitmq/* relay/* worker/*
|
||||
cp s3/s3_root_user s3/s3_root_password api/s3_access_key_id api/s3_secret_access_key s3-init/
|
||||
db_url() { printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=%s&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=%s&options=-c%%20statement_timeout%%3D5000' "$$(cat postgres/pg_password)" "$$1" "$$2"; }
|
||||
db_url 10 api > api/database_url
|
||||
db_url 5 worker > worker/database_url
|
||||
db_url 3 relay > relay/database_url
|
||||
printf 'redis://:%s@redis:6379/0' "$$(cat redis/redis_password)" > api/cache_url
|
||||
printf 'postgresql://messenger:%s@postgres:5432/messenger' "$$(cat postgres/pg_password)" > migrate/database_url
|
||||
printf 'amqp://messenger:%s@rabbitmq:5672/' "$$(cat broker/broker_password)" > worker/broker_url
|
||||
cp worker/broker_url relay/
|
||||
printf 'default_user = messenger\ndefault_pass = %s\nloopback_users = none\nlog.console = true\nlisteners.tcp.default = 5672\n' "$$(cat broker/broker_password)" > rabbitmq/10-messenger.conf
|
||||
cp api/database_url api/s3_access_key_id api/s3_secret_access_key reconciler/
|
||||
cp api/s3_access_key_id api/s3_secret_access_key worker/
|
||||
chmod 0444 postgres/* redis/* api/* migrate/* s3/* s3-init/* reconciler/* broker/* rabbitmq/* relay/* worker/* grafana/*
|
||||
- ./infra/openbao/server.hcl:/bao/config/server.hcl:ro
|
||||
- baodata:/bao/data
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: openbao}}
|
||||
environment:
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/tls/ca.crt
|
||||
healthcheck:
|
||||
test: ["CMD", "bao", "status"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 15
|
||||
depends_on:
|
||||
bootstrap: {condition: service_completed_successfully}
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.1", memory: 32M }
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
|
||||
postgres:
|
||||
image: postgres:17.2-alpine
|
||||
@@ -74,7 +88,7 @@ services:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./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}}
|
||||
- {type: volume, source: secrets, 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
|
||||
@@ -87,27 +101,19 @@ services:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 512M}
|
||||
|
||||
redis:
|
||||
image: redis:7.4.1-alpine
|
||||
user: redis
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- exec redis-server --save '' --appendonly no --maxmemory 64mb --maxmemory-policy allkeys-lru --requirepass "$$(cat /run/secrets/redis_password)"
|
||||
migrate:
|
||||
<<: *lockdown
|
||||
build:
|
||||
context: .
|
||||
target: migrate
|
||||
image: mtusi-messenger-lab7-migrate:dev
|
||||
volumes:
|
||||
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: redis } }
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: migrate}}
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.25", memory: 128M }
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "redis-cli --no-auth-warning -a \"$$(cat /run/secrets/redis_password)\" ping | grep -q PONG"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
depends_on:
|
||||
secrets-init:
|
||||
condition: service_completed_successfully
|
||||
restart: unless-stopped
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
s3:
|
||||
<<: *lockdown
|
||||
@@ -119,7 +125,7 @@ services:
|
||||
MINIO_BROWSER: "off"
|
||||
volumes:
|
||||
- s3data:/data
|
||||
- {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: s3}}
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: s3}}
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fsS", "--cacert", "/run/tls/ca.crt", "https://s3:9000/minio/health/live"]
|
||||
interval: 3s
|
||||
@@ -140,101 +146,13 @@ services:
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
volumes:
|
||||
- ./infra/s3/init.sh:/work/init.sh:ro
|
||||
- {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: s3-init}}
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: s3-init}}
|
||||
depends_on:
|
||||
s3: {condition: service_healthy}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 192M}
|
||||
|
||||
migrate:
|
||||
<<: *lockdown
|
||||
build:
|
||||
context: .
|
||||
target: migrate
|
||||
image: mtusi-messenger-lab7-migrate:dev
|
||||
volumes:
|
||||
- {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}
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
image: mtusi-messenger-lab7-api:dev
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
SHUTDOWN_DELAY_MS: 3000
|
||||
DATABASE_URL_FILE: /run/tls/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
NODE_EXTRA_CA_CERTS: /run/tls/ca.crt
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/tls/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/tls/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
<<: *otel
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
volumes:
|
||||
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: api } }
|
||||
- { type: volume, source: pki, target: /run/tls, read_only: true, volume: { subpath: api } }
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: { cpus: "0.5", memory: 256M }
|
||||
stop_grace_period: 10s
|
||||
depends_on:
|
||||
bootstrap:
|
||||
condition: service_completed_successfully
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_started
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
restart: unless-stopped
|
||||
|
||||
reconciler:
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
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/tls/database_url
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
NODE_EXTRA_CA_CERTS: /run/tls/ca.crt
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/tls/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/tls/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 }
|
||||
healthcheck:
|
||||
disable: true
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
restart: unless-stopped
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32
|
||||
hostname: rabbitmq
|
||||
@@ -246,7 +164,7 @@ services:
|
||||
- rabbitmqdata:/var/lib/rabbitmq
|
||||
- ./infra/rabbitmq/10-messenger.conf:/etc/rabbitmq/conf.d/10-messenger.conf:ro
|
||||
- ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
|
||||
- {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: rabbitmq}}
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: rabbitmq}}
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
|
||||
interval: 5s
|
||||
@@ -261,78 +179,81 @@ services:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
relay:
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
image: mtusi-messenger-lab7-api:dev
|
||||
command: ["node", "dist/relay.js"]
|
||||
api:
|
||||
<<: *runtime
|
||||
environment:
|
||||
NODE_EXTRA_CA_CERTS: /run/tls/ca.crt
|
||||
DATABASE_URL_FILE: /run/tls/database_url
|
||||
BROKER_URL_FILE: /run/tls/broker_url
|
||||
AMQP_TOPOLOGY_PREPROVISIONED: "true"
|
||||
JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300}
|
||||
RELAY_FAULT: ${RELAY_FAULT:-}
|
||||
<<: *otel
|
||||
OTEL_SERVICE_NAME: messenger-relay
|
||||
<<: [*runtime-env, *s3-env, *otel-env]
|
||||
BAO_ROLE: api
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
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 } }
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: api}}
|
||||
depends_on:
|
||||
openbao: {condition: service_healthy}
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-init: {condition: service_completed_successfully}
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 384M}
|
||||
|
||||
relay:
|
||||
<<: *runtime
|
||||
environment:
|
||||
<<: [*runtime-env, *otel-env]
|
||||
BAO_ROLE: relay
|
||||
OTEL_SERVICE_NAME: messenger-relay
|
||||
AMQP_TOPOLOGY_PREPROVISIONED: "true"
|
||||
volumes:
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: relay}}
|
||||
depends_on:
|
||||
openbao: {condition: service_healthy}
|
||||
migrate: {condition: service_completed_successfully}
|
||||
rabbitmq: {condition: service_healthy}
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.25", memory: 128M }
|
||||
healthcheck:
|
||||
disable: true
|
||||
stop_grace_period: 10s
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
limits: {cpus: "0.25", memory: 192M}
|
||||
|
||||
worker:
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
image: mtusi-messenger-lab7-api:dev
|
||||
command: ["node", "dist/worker.js"]
|
||||
<<: *runtime
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/tls/database_url
|
||||
BROKER_URL_FILE: /run/tls/broker_url
|
||||
<<: [*runtime-env, *s3-env, *otel-env]
|
||||
BAO_ROLE: worker
|
||||
OTEL_SERVICE_NAME: messenger-worker
|
||||
AMQP_TOPOLOGY_PREPROVISIONED: "true"
|
||||
NODE_EXTRA_CA_CERTS: /run/tls/ca.crt
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/tls/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/tls/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-90}
|
||||
WORKER_FAULT: ${WORKER_FAULT:-}
|
||||
<<: *otel
|
||||
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 } }
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: worker}}
|
||||
depends_on:
|
||||
openbao: {condition: service_healthy}
|
||||
migrate: {condition: service_completed_successfully}
|
||||
rabbitmq: {condition: service_healthy}
|
||||
s3-init: {condition: service_completed_successfully}
|
||||
stop_grace_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 768M}
|
||||
healthcheck:
|
||||
disable: true
|
||||
stop_grace_period: 30s
|
||||
|
||||
reconciler:
|
||||
<<: *runtime
|
||||
command: ["node", "dist/stand.js", "--apply", "--loop"]
|
||||
environment:
|
||||
<<: [*runtime-env, *s3-env]
|
||||
BAO_ROLE: reconciler
|
||||
volumes:
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: reconciler}}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
restart: unless-stopped
|
||||
openbao: {condition: service_healthy}
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-init: {condition: service_completed_successfully}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 192M}
|
||||
|
||||
lb:
|
||||
<<: *lockdown
|
||||
@@ -342,7 +263,7 @@ services:
|
||||
- "127.0.0.1:${HTTPS_PORT:-8443}:8443"
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: lb}}
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: lb}}
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/"]
|
||||
interval: 3s
|
||||
@@ -440,7 +361,7 @@ services:
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
depends_on:
|
||||
secrets-init:
|
||||
bootstrap:
|
||||
condition: service_completed_successfully
|
||||
prometheus:
|
||||
condition: service_healthy
|
||||
@@ -458,7 +379,7 @@ services:
|
||||
working_dir: /work
|
||||
volumes:
|
||||
- .:/work:ro
|
||||
- {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: checks}}
|
||||
- {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: checks}}
|
||||
depends_on:
|
||||
bootstrap: {condition: service_completed_successfully}
|
||||
deploy:
|
||||
@@ -466,6 +387,8 @@ services:
|
||||
limits: {cpus: "0.5", memory: 128M}
|
||||
|
||||
volumes:
|
||||
secrets:
|
||||
baodata:
|
||||
pgdata:
|
||||
s3data:
|
||||
rabbitmqdata:
|
||||
@@ -473,8 +396,6 @@ volumes:
|
||||
lokidata:
|
||||
tempodata:
|
||||
grafanadata:
|
||||
secrets:
|
||||
pki:
|
||||
|
||||
networks:
|
||||
telemetry:
|
||||
|
||||
+26
-16
@@ -97,11 +97,14 @@ def broker_definitions(relay_password, worker_password):
|
||||
|
||||
|
||||
def main():
|
||||
os.chmod("/bao-data", 0o700)
|
||||
os.chown("/bao-data", 100, 1000)
|
||||
if (ROOT / "initialized").is_file():
|
||||
print("Local identities already initialized")
|
||||
return
|
||||
os.umask(0o077)
|
||||
names = ("operator", "lb", "checks", "postgres", "migrate", "s3", "s3-init", "rabbitmq", *ROLES)
|
||||
names = ("operator", "postgres", "migrate", "s3", "s3-init", "rabbitmq", "lb", "openbao",
|
||||
"grafana", "checks", *ROLES)
|
||||
directories = {name: ROOT / name for name in names}
|
||||
for directory in directories.values():
|
||||
directory.mkdir(exist_ok=True)
|
||||
@@ -132,34 +135,41 @@ def main():
|
||||
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))
|
||||
s3 = directories["s3"]
|
||||
s3_key, s3_crt = leaf(s3, "s3", server_ca)
|
||||
s3_key.rename(s3 / "private.key")
|
||||
s3_crt.rename(s3 / "public.crt")
|
||||
leaf(directories["rabbitmq"], "rabbitmq", server_ca)
|
||||
leaf(directories["openbao"], "openbao", server_ca, extra_san=",DNS:localhost,IP:127.0.0.1")
|
||||
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))
|
||||
write(directories["grafana"] / "admin_password", secrets.token_hex(20))
|
||||
for filename, value in {"root_user": secrets.token_hex(10),
|
||||
"root_password": secrets.token_hex(24)}.items():
|
||||
write(s3 / filename, value)
|
||||
write(directories["s3-init"] / filename, value)
|
||||
|
||||
for role in ("api", "worker", "reconciler"):
|
||||
password = secrets.token_hex(24)
|
||||
write(directories[role] / "s3_access_key_id", f"messenger-{role}")
|
||||
write(directories[role] / "s3_secret_access_key", password)
|
||||
write(directories["s3-init"] / f"{role}_password", password)
|
||||
leaf(directories["rabbitmq"], "rabbitmq", server_ca)
|
||||
relay_password, worker_password = secrets.token_hex(24), secrets.token_hex(24)
|
||||
write(directories["rabbitmq"] / "definitions.json",
|
||||
json.dumps(broker_definitions(relay_password, worker_password)))
|
||||
for role, password in (("relay", relay_password), ("worker", worker_password)):
|
||||
write(directories[role] / "broker_url", f"amqps://{role}:{password}@rabbitmq:5671/%2Fmessenger")
|
||||
configuration = {}
|
||||
for role, limit in ROLES.items():
|
||||
_, cert = leaf(directories[role], f"{role}.bao.lab7.internal", client_ca, "client")
|
||||
values = {"DATABASE_URL": db_url(role, passwords[role], limit)}
|
||||
if role != "relay":
|
||||
values.update(S3_ACCESS_KEY_ID=f"messenger-{role}",
|
||||
S3_SECRET_ACCESS_KEY=secrets.token_hex(24))
|
||||
write(directories["s3-init"] / f"{role}_password", values["S3_SECRET_ACCESS_KEY"])
|
||||
if role in ("relay", "worker"):
|
||||
password = relay_password if role == "relay" else worker_password
|
||||
values["BROKER_URL"] = f"amqps://{role}:{password}@rabbitmq:5671/%2Fmessenger"
|
||||
configuration[role] = {"certificate": cert.read_text(), "values": values}
|
||||
write(operator / "roles.json", json.dumps(configuration))
|
||||
shutil.copyfile(api / "api.crt", checks / "api.crt")
|
||||
owners = {"lb": 1000, "rabbitmq": 100, "postgres": 70, "migrate": 1000, **dict.fromkeys(ROLES, 1000)}
|
||||
owners = {"postgres": 70, "rabbitmq": 100, "openbao": 100, "grafana": 472,
|
||||
"lb": 1000, "migrate": 1000, **dict.fromkeys(ROLES, 1000)}
|
||||
for name, uid in owners.items():
|
||||
own(directories[name], uid)
|
||||
(ROOT / "initialized").touch()
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
ui = false
|
||||
disable_mlock = true
|
||||
api_addr = "https://openbao:8200"
|
||||
|
||||
storage "file" {
|
||||
path = "/bao/data"
|
||||
}
|
||||
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
tls_cert_file = "/run/tls/openbao.crt"
|
||||
tls_key_file = "/run/tls/openbao.key"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
path "messenger/data/ROLE" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/revoke-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Initialize, unseal and provision the local OpenBao without printing credentials."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def from_bootstrap(filename):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "run", "--rm", "--no-deps", "--entrypoint", "cat", "bootstrap",
|
||||
f"/state/operator/{filename}"],
|
||||
cwd=ROOT, check=True, capture_output=True,
|
||||
)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def request(address, context, path, body=None, token=None):
|
||||
content = json.dumps(body).encode() if body is not None else None
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
req = Request(address + "/v1/" + path, data=content, headers=headers)
|
||||
try:
|
||||
with urlopen(req, context=context, timeout=5) as response:
|
||||
return json.loads(response.read() or "{}")
|
||||
except HTTPError as error:
|
||||
raise RuntimeError(f"OpenBao {path}: HTTP {error.code}") from None
|
||||
|
||||
|
||||
def wait_for_listener(address, context):
|
||||
for _ in range(30):
|
||||
try:
|
||||
return request(address, context, "sys/init")["initialized"]
|
||||
except ssl.SSLCertVerificationError:
|
||||
raise
|
||||
except URLError as error:
|
||||
if isinstance(error.reason, ssl.SSLCertVerificationError):
|
||||
raise
|
||||
time.sleep(1)
|
||||
raise RuntimeError("OpenBao listener did not become available")
|
||||
|
||||
|
||||
def save_operator_file(path, state):
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w",
|
||||
encoding="utf-8") as file:
|
||||
json.dump(state, file)
|
||||
file.flush()
|
||||
os.fsync(file.fileno())
|
||||
|
||||
|
||||
def configure(address, context, token):
|
||||
mounts = request(address, context, "sys/mounts", token=token)
|
||||
if "messenger/" not in mounts:
|
||||
request(address, context, "sys/mounts/messenger",
|
||||
{"type": "kv", "options": {"version": "2"}}, token)
|
||||
auth = request(address, context, "sys/auth", token=token)
|
||||
if "cert/" not in auth:
|
||||
request(address, context, "sys/auth/cert", {"type": "cert"}, token)
|
||||
|
||||
roles = json.loads(from_bootstrap("roles.json"))
|
||||
template = (ROOT / "infra/openbao/service.hcl").read_text(encoding="utf-8")
|
||||
for role, config in roles.items():
|
||||
policy = "messenger-" + role
|
||||
request(address, context, "sys/policies/acl/" + policy,
|
||||
{"policy": template.replace("ROLE", role)}, token)
|
||||
request(address, context, "auth/cert/certs/" + role, {
|
||||
"certificate": config["certificate"],
|
||||
"allowed_dns_sans": [role + ".bao.lab7.internal"],
|
||||
"token_policies": [policy],
|
||||
"token_ttl": "15m",
|
||||
"token_explicit_max_ttl": "15m",
|
||||
"token_no_default_policy": True,
|
||||
}, token)
|
||||
request(address, context, "messenger/data/" + role, {"data": config["values"]}, token)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("init", "unseal"))
|
||||
parser.add_argument("--address", default="https://localhost:8200")
|
||||
parser.add_argument("--operator-file", type=Path,
|
||||
default=Path(os.environ.get("LAB7_OPERATOR_FILE", ROOT / "secrets/operator.json")))
|
||||
parser.add_argument("--ca-file", type=Path, default=ROOT / "secrets/ca.crt")
|
||||
args = parser.parse_args()
|
||||
address = args.address.rstrip("/")
|
||||
parsed = urlsplit(address)
|
||||
if parsed.scheme != "https" or parsed.hostname not in ("localhost", "127.0.0.1") or parsed.path:
|
||||
parser.error("--address must be a local HTTPS origin")
|
||||
|
||||
if args.action == "init":
|
||||
args.ca_file.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
args.ca_file.write_bytes(from_bootstrap("ca.crt"))
|
||||
context = ssl.create_default_context(cafile=str(args.ca_file))
|
||||
initialized = wait_for_listener(address, context)
|
||||
if not initialized:
|
||||
if args.action != "init" or args.operator_file.exists():
|
||||
raise RuntimeError("Use init with a new operator file to initialize this storage")
|
||||
state = request(address, context, "sys/init", {"secret_shares": 3, "secret_threshold": 2})
|
||||
save_operator_file(args.operator_file, state)
|
||||
else:
|
||||
state = json.loads(args.operator_file.read_text(encoding="utf-8"))
|
||||
for share in state["keys_base64"][:2]:
|
||||
if not request(address, context, "sys/seal-status")["sealed"]:
|
||||
break
|
||||
request(address, context, "sys/unseal", {"key": share})
|
||||
if request(address, context, "sys/seal-status")["sealed"]:
|
||||
raise RuntimeError("OpenBao is still sealed")
|
||||
if args.action == "init":
|
||||
configure(address, context, state["root_token"])
|
||||
print("OpenBao is unsealed. Service policies and KV paths are provisioned.")
|
||||
else:
|
||||
print("OpenBao is unsealed.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except subprocess.CalledProcessError:
|
||||
raise SystemExit("Could not read bootstrap material from Docker Compose.") from None
|
||||
except (OSError, RuntimeError) as error:
|
||||
raise SystemExit(str(error)) from None
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { readFileSync, writeFileSync } from 'fs';
|
||||
import { Agent, request } from 'https';
|
||||
|
||||
const keys = {
|
||||
api: ['DATABASE_URL', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY'],
|
||||
worker: [
|
||||
'DATABASE_URL', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'BROKER_URL',
|
||||
],
|
||||
relay: ['DATABASE_URL', 'BROKER_URL'],
|
||||
reconciler: ['DATABASE_URL', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY'],
|
||||
} as const;
|
||||
|
||||
const entrypoints = { api: './main', worker: './worker', relay: './relay', reconciler: './reconcile' };
|
||||
type Role = keyof typeof keys;
|
||||
const tls = '/run/tls';
|
||||
|
||||
function bao(
|
||||
address: URL,
|
||||
agent: Agent,
|
||||
path: string,
|
||||
body?: object,
|
||||
token?: string,
|
||||
): Promise<{ auth?: { client_token: string }; data?: { data: Record<string, string> } }> {
|
||||
const json = body === undefined ? undefined : JSON.stringify(body);
|
||||
const headers = {
|
||||
...(json === undefined ? {} : { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(json) }),
|
||||
...(token === undefined ? {} : { 'X-Vault-Token': token }),
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = request(new URL(path, address), {
|
||||
agent, headers, method: json === undefined ? 'GET' : 'POST', timeout: 5000,
|
||||
}, (response) => {
|
||||
if (!response.statusCode || response.statusCode >= 300) {
|
||||
response.resume();
|
||||
reject(new Error('OpenBao returned HTTP ' + response.statusCode));
|
||||
return;
|
||||
}
|
||||
response.setEncoding('utf8');
|
||||
let text = '';
|
||||
response.on('data', (chunk: string) => { text += chunk; });
|
||||
response.on('error', reject);
|
||||
response.on('end', () => {
|
||||
try {
|
||||
resolve(text ? JSON.parse(text) : {});
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.on('timeout', () => req.destroy(new Error('OpenBao request timed out')));
|
||||
req.end(json);
|
||||
});
|
||||
}
|
||||
|
||||
async function start(): Promise<void> {
|
||||
const role = process.env.BAO_ROLE as Role;
|
||||
if (!Object.prototype.hasOwnProperty.call(keys, role)) {
|
||||
throw new Error('Unknown service role');
|
||||
}
|
||||
const address = new URL(process.env.BAO_ADDR ?? 'https://openbao:8200');
|
||||
if (address.protocol !== 'https:') {
|
||||
throw new Error('OpenBao requires HTTPS');
|
||||
}
|
||||
const agent = new Agent({
|
||||
ca: readFileSync(tls + '/ca.crt'),
|
||||
cert: readFileSync(tls + '/' + role + '.bao.lab7.internal.crt'),
|
||||
key: readFileSync(tls + '/' + role + '.bao.lab7.internal.key'),
|
||||
minVersion: 'TLSv1.2',
|
||||
});
|
||||
try {
|
||||
const token = (await bao(address, agent, '/v1/auth/cert/login', { name: role })).auth?.client_token;
|
||||
if (!token) {
|
||||
throw new Error('OpenBao did not issue a service token');
|
||||
}
|
||||
try {
|
||||
const secret = (await bao(address, agent, '/v1/messenger/data/' + role, undefined, token)).data?.data;
|
||||
for (const key of keys[role]) {
|
||||
const value = secret?.[key];
|
||||
if (typeof value !== 'string' || !value) {
|
||||
throw new Error('Missing required service credential');
|
||||
}
|
||||
process.env[key] = value;
|
||||
}
|
||||
if (process.argv[2] === '--check-policy') {
|
||||
const other = role === 'api' ? 'worker' : 'api';
|
||||
await expectForbidden(bao(address, agent, '/v1/messenger/data/' + other, undefined, token));
|
||||
await expectForbidden(bao(address, agent, '/v1/sys/policies/acl/lab7-denied',
|
||||
{ policy: '' }, token));
|
||||
console.log('PASS: ' + role + ' can read its own path; foreign path and policy writes return 403');
|
||||
return;
|
||||
}
|
||||
} finally {
|
||||
await bao(address, agent, '/v1/auth/token/revoke-self', {}, token);
|
||||
}
|
||||
} finally {
|
||||
agent.destroy();
|
||||
}
|
||||
// Load instrumentation and credential consumers after retrieving their configuration.
|
||||
if (role === 'api') {
|
||||
const instance = randomUUID();
|
||||
process.env.INSTANCE_ID = instance;
|
||||
writeFileSync('/tmp/messenger-instance-id', instance, { mode: 0o600 });
|
||||
}
|
||||
if (process.argv[2] === '--replay' && role === 'worker') {
|
||||
process.argv.splice(2, 1);
|
||||
require('./replay');
|
||||
return;
|
||||
}
|
||||
require(entrypoints[role]);
|
||||
}
|
||||
|
||||
async function expectForbidden(operation: Promise<unknown>): Promise<void> {
|
||||
try {
|
||||
await operation;
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === 'OpenBao returned HTTP 403') {
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
throw new Error('OpenBao unexpectedly authorized a forbidden operation');
|
||||
}
|
||||
|
||||
start().catch((error: unknown) => {
|
||||
console.error('Service could not start with its OpenBao identity',
|
||||
error instanceof Error && /^OpenBao returned HTTP \d+$/.test(error.message) ? error.message : '');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in New Issue
Block a user