feat: add openbao and scoped service policies

This commit is contained in:
2026-11-30 16:36:14 +03:00
parent cd336d8472
commit c7a7ffaffe
7 changed files with 433 additions and 220 deletions
+1 -1
View File
@@ -44,4 +44,4 @@ COPY contracts/openapi.json ./contracts/openapi.json
USER node USER node
EXPOSE 8080 EXPOSE 8080
CMD ["node", "dist/main.js"] CMD ["node", "dist/stand.js"]
+124 -203
View File
@@ -4,10 +4,28 @@ x-lockdown: &lockdown
security_opt: [no-new-privileges:true] security_opt: [no-new-privileges:true]
cap_drop: [ALL] cap_drop: [ALL]
x-otel: &otel x-runtime: &runtime
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} <<: *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_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab
services: services:
bootstrap: bootstrap:
@@ -23,42 +41,38 @@ services:
cap_add: [CHOWN, DAC_OVERRIDE, FOWNER] cap_add: [CHOWN, DAC_OVERRIDE, FOWNER]
volumes: volumes:
- ./infra/bootstrap.py:/work/bootstrap.py:ro - ./infra/bootstrap.py:/work/bootstrap.py:ro
- pki:/state - secrets:/state
- baodata:/bao-data
deploy: deploy:
resources: resources:
limits: {cpus: "1.0", memory: 96M} limits: {cpus: "1.0", memory: 96M}
secrets-init: openbao:
image: alpine:3.20.3 <<: *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: volumes:
- secrets:/secrets - ./infra/openbao/server.hcl:/bao/config/server.hcl:ro
command: - baodata:/bao/data
- sh - {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: openbao}}
- -ec environment:
- | BAO_ADDR: https://openbao:8200
cd /secrets BAO_CACERT: /run/tls/ca.crt
mkdir -p postgres redis api migrate s3 s3-init reconciler broker rabbitmq relay worker grafana healthcheck:
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 test: ["CMD", "bao", "status"]
file=$${entry%%:*}; rest=$${entry#*:}; dir=$${rest%%:*}; size=$${rest##*:} interval: 3s
[ -s "$$dir/$$file" ] || head -c "$$size" /dev/urandom | od -An -tx1 | tr -d ' \n' > "$$dir/$$file" timeout: 3s
done retries: 15
rm -f s3-init/* rabbitmq/* relay/* worker/* depends_on:
cp s3/s3_root_user s3/s3_root_password api/s3_access_key_id api/s3_secret_access_key s3-init/ bootstrap: {condition: service_completed_successfully}
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"; } restart: unless-stopped
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/*
deploy: deploy:
resources: resources:
limits: { cpus: "0.1", memory: 32M } limits: {cpus: "0.5", memory: 256M}
postgres: postgres:
image: postgres:17.2-alpine image: postgres:17.2-alpine
@@ -74,7 +88,7 @@ services:
- pgdata:/var/lib/postgresql/data - pgdata:/var/lib/postgresql/data
- ./infra/postgres/init.sh:/docker-entrypoint-initdb.d/roles.sh:ro - ./infra/postgres/init.sh:/docker-entrypoint-initdb.d/roles.sh:ro
- ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf: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: healthcheck:
test: ["CMD", "pg_isready", "-d", "host=postgres dbname=messenger user=migrate sslmode=verify-full sslrootcert=/run/tls/ca.crt"] test: ["CMD", "pg_isready", "-d", "host=postgres dbname=messenger user=migrate sslmode=verify-full sslrootcert=/run/tls/ca.crt"]
interval: 3s interval: 3s
@@ -87,27 +101,19 @@ services:
resources: resources:
limits: {cpus: "1.0", memory: 512M} limits: {cpus: "1.0", memory: 512M}
redis: migrate:
image: redis:7.4.1-alpine <<: *lockdown
user: redis build:
command: context: .
- sh target: migrate
- -c image: mtusi-messenger-lab7-migrate:dev
- exec redis-server --save '' --appendonly no --maxmemory 64mb --maxmemory-policy allkeys-lru --requirepass "$$(cat /run/secrets/redis_password)"
volumes: 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: deploy:
resources: resources:
limits: { cpus: "0.25", memory: 128M } limits: {cpus: "0.5", memory: 512M}
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
s3: s3:
<<: *lockdown <<: *lockdown
@@ -119,7 +125,7 @@ services:
MINIO_BROWSER: "off" MINIO_BROWSER: "off"
volumes: volumes:
- s3data:/data - 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: healthcheck:
test: ["CMD", "curl", "-fsS", "--cacert", "/run/tls/ca.crt", "https://s3:9000/minio/health/live"] test: ["CMD", "curl", "-fsS", "--cacert", "/run/tls/ca.crt", "https://s3:9000/minio/health/live"]
interval: 3s interval: 3s
@@ -140,101 +146,13 @@ services:
S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
volumes: volumes:
- ./infra/s3/init.sh:/work/init.sh:ro - ./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: depends_on:
s3: {condition: service_healthy} s3: {condition: service_healthy}
deploy: deploy:
resources: resources:
limits: {cpus: "0.25", memory: 192M} 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: rabbitmq:
image: rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32 image: rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32
hostname: rabbitmq hostname: rabbitmq
@@ -246,7 +164,7 @@ services:
- rabbitmqdata:/var/lib/rabbitmq - rabbitmqdata:/var/lib/rabbitmq
- ./infra/rabbitmq/10-messenger.conf:/etc/rabbitmq/conf.d/10-messenger.conf:ro - ./infra/rabbitmq/10-messenger.conf:/etc/rabbitmq/conf.d/10-messenger.conf:ro
- ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins: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: healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"] test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
interval: 5s interval: 5s
@@ -261,78 +179,81 @@ services:
resources: resources:
limits: {cpus: "0.5", memory: 512M} limits: {cpus: "0.5", memory: 512M}
relay: api:
build: <<: *runtime
context: .
target: runtime
image: mtusi-messenger-lab7-api:dev
command: ["node", "dist/relay.js"]
environment: environment:
NODE_EXTRA_CA_CERTS: /run/tls/ca.crt <<: [*runtime-env, *s3-env, *otel-env]
DATABASE_URL_FILE: /run/tls/database_url BAO_ROLE: api
BROKER_URL_FILE: /run/tls/broker_url OTEL_SERVICE_NAME: messenger-api
AMQP_TOPOLOGY_PREPROVISIONED: "true" SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300} MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
RELAY_FAULT: ${RELAY_FAULT:-} MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
<<: *otel
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/tls, read_only: true, volume: {subpath: api}}
- { type: volume, source: pki, target: /run/tls, read_only: true, volume: { subpath: relay } } 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: deploy:
resources: resources:
limits: { cpus: "0.25", memory: 128M } limits: {cpus: "0.25", memory: 192M}
healthcheck:
disable: true
stop_grace_period: 10s
depends_on:
migrate:
condition: service_completed_successfully
rabbitmq:
condition: service_healthy
restart: unless-stopped
worker: worker:
build: <<: *runtime
context: .
target: runtime
image: mtusi-messenger-lab7-api:dev
command: ["node", "dist/worker.js"]
environment: environment:
DATABASE_URL_FILE: /run/tls/database_url <<: [*runtime-env, *s3-env, *otel-env]
BROKER_URL_FILE: /run/tls/broker_url BAO_ROLE: worker
OTEL_SERVICE_NAME: messenger-worker
AMQP_TOPOLOGY_PREPROVISIONED: "true" 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_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} 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: volumes:
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: worker } } - {type: volume, source: secrets, target: /run/tls, read_only: true, volume: {subpath: worker}}
- { type: volume, source: pki, 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: deploy:
resources: resources:
limits: { cpus: "1.0", memory: 768M } limits: {cpus: "1.0", memory: 768M}
healthcheck:
disable: true reconciler:
stop_grace_period: 30s <<: *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: depends_on:
migrate: openbao: {condition: service_healthy}
condition: service_completed_successfully migrate: {condition: service_completed_successfully}
rabbitmq: s3-init: {condition: service_completed_successfully}
condition: service_healthy deploy:
s3-init: resources:
condition: service_completed_successfully limits: {cpus: "0.25", memory: 192M}
restart: unless-stopped
lb: lb:
<<: *lockdown <<: *lockdown
@@ -342,7 +263,7 @@ services:
- "127.0.0.1:${HTTPS_PORT:-8443}:8443" - "127.0.0.1:${HTTPS_PORT:-8443}:8443"
volumes: volumes:
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro - ./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: healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/"] test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/"]
interval: 3s interval: 3s
@@ -440,7 +361,7 @@ services:
timeout: 3s timeout: 3s
retries: 20 retries: 20
depends_on: depends_on:
secrets-init: bootstrap:
condition: service_completed_successfully condition: service_completed_successfully
prometheus: prometheus:
condition: service_healthy condition: service_healthy
@@ -458,7 +379,7 @@ services:
working_dir: /work working_dir: /work
volumes: volumes:
- .:/work:ro - .:/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: depends_on:
bootstrap: {condition: service_completed_successfully} bootstrap: {condition: service_completed_successfully}
deploy: deploy:
@@ -466,6 +387,8 @@ services:
limits: {cpus: "0.5", memory: 128M} limits: {cpus: "0.5", memory: 128M}
volumes: volumes:
secrets:
baodata:
pgdata: pgdata:
s3data: s3data:
rabbitmqdata: rabbitmqdata:
@@ -473,8 +396,6 @@ volumes:
lokidata: lokidata:
tempodata: tempodata:
grafanadata: grafanadata:
secrets:
pki:
networks: networks:
telemetry: telemetry:
+26 -16
View File
@@ -97,11 +97,14 @@ def broker_definitions(relay_password, worker_password):
def main(): def main():
os.chmod("/bao-data", 0o700)
os.chown("/bao-data", 100, 1000)
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", "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} 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)
@@ -132,34 +135,41 @@ def main():
shutil.copyfile(foreign_ca[1], checks / "foreign-ca.crt") shutil.copyfile(foreign_ca[1], checks / "foreign-ca.crt")
leaf(directories["postgres"], "postgres", server_ca) 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 = directories["s3"]
s3_key, s3_crt = leaf(s3, "s3", server_ca) s3_key, s3_crt = leaf(s3, "s3", server_ca)
s3_key.rename(s3 / "private.key") s3_key.rename(s3 / "private.key")
s3_crt.rename(s3 / "public.crt") 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), for filename, value in {"root_user": secrets.token_hex(10),
"root_password": secrets.token_hex(24)}.items(): "root_password": secrets.token_hex(24)}.items():
write(s3 / filename, value) write(s3 / filename, value)
write(directories["s3-init"] / 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) relay_password, worker_password = secrets.token_hex(24), secrets.token_hex(24)
write(directories["rabbitmq"] / "definitions.json", write(directories["rabbitmq"] / "definitions.json",
json.dumps(broker_definitions(relay_password, worker_password))) json.dumps(broker_definitions(relay_password, worker_password)))
for role, password in (("relay", relay_password), ("worker", worker_password)): configuration = {}
write(directories[role] / "broker_url", f"amqps://{role}:{password}@rabbitmq:5671/%2Fmessenger") 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") 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(): for name, uid in owners.items():
own(directories[name], uid) own(directories[name], uid)
(ROOT / "initialized").touch() (ROOT / "initialized").touch()
+14
View File
@@ -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"
}
+7
View File
@@ -0,0 +1,7 @@
path "messenger/data/ROLE" {
capabilities = ["read"]
}
path "auth/token/revoke-self" {
capabilities = ["update"]
}
+131
View File
@@ -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
View File
@@ -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;
});