lab7: OpenBao 2.7.3 (не dev, raft на volume, TLS, audit), AppRole и scoped policy для api/relay/worker, секреты только из OpenBao, скрипт оператора и проверка allow/deny
This commit is contained in:
+87
-36
@@ -28,13 +28,22 @@
|
||||
# `storage` (s3), `queue` (broker), `telemetry`. The API is NOT on `queue`.
|
||||
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab7}
|
||||
|
||||
# Lab 7: how a service gets its secrets: AppRole login to OpenBao with ITS role_id/secret_id
|
||||
# (Docker secrets of that service only), read ITS path messenger/data/<service>, revoke the token.
|
||||
# database_url, cache_url, broker_url and the S3 key pair are NOT mounted as files into api, relay,
|
||||
# worker any more (src/messenger/bao.py).
|
||||
x-bao-env: &bao-env
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/secrets/internal-ca.crt
|
||||
BAO_ROLE_ID_FILE: /run/secrets/bao_role_id
|
||||
BAO_SECRET_ID_FILE: /run/secrets/bao_secret_id
|
||||
BAO_STARTUP_TIMEOUT_SECONDS: ${BAO_STARTUP_TIMEOUT_SECONDS:-60}
|
||||
|
||||
x-api-env: &api-env
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
SESSION_STORE: ${SESSION_STORE:-valkey}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
DB_POOL_MIN: ${DB_POOL_MIN:-1}
|
||||
DB_POOL_MAX: ${DB_POOL_MAX:-10}
|
||||
DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3}
|
||||
@@ -51,8 +60,6 @@ x-api-env: &api-env
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
@@ -98,8 +105,6 @@ x-otel-env: &otel-env
|
||||
x-pipeline-env: &pipeline-env
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
BROKER_URL_FILE: /run/secrets/broker_url
|
||||
DB_POOL_MAX: ${PIPELINE_DB_POOL_MAX:-6}
|
||||
DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333}
|
||||
@@ -336,8 +341,9 @@ services:
|
||||
BUILD_REVISION: ${BUILD_REVISION:-dev}
|
||||
image: ${API_IMAGE:-mtusi-messenger:lab7}
|
||||
environment:
|
||||
<<: [*api-env, *otel-env]
|
||||
<<: [*api-env, *otel-env, *bao-env]
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
BAO_SECRET_PATH: messenger/data/api
|
||||
# Lab 7: the only network listener is mTLS on 8443 (tls.py); plaintext health on loopback.
|
||||
APP_PORT: 8443
|
||||
APP_HEALTH_PORT: 8081
|
||||
@@ -346,10 +352,8 @@ services:
|
||||
TLS_CLIENT_CA_FILE: /run/secrets/internal-ca.crt
|
||||
MTLS_ALLOWED_CLIENTS: ${MTLS_ALLOWED_CLIENTS:-lb}
|
||||
secrets:
|
||||
- {source: database_url_api, target: database_url}
|
||||
- cache_url
|
||||
- {source: s3_api_access_key_id, target: s3_access_key_id}
|
||||
- {source: s3_api_secret_access_key, target: s3_secret_access_key}
|
||||
- {source: bao_api_role_id, target: bao_role_id}
|
||||
- {source: bao_api_secret_id, target: bao_secret_id}
|
||||
- {source: pki_api_crt, target: service.crt}
|
||||
- {source: pki_api_key, target: service.key}
|
||||
- {source: pki_internal_ca, target: internal-ca.crt}
|
||||
@@ -373,9 +377,11 @@ services:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
openbao:
|
||||
condition: service_healthy # healthy = unsealed (see the openbao healthcheck)
|
||||
stop_grace_period: 15s # > DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS (11 s)
|
||||
restart: unless-stopped
|
||||
networks: [edge, data, storage, telemetry]
|
||||
networks: [edge, data, storage, telemetry, vault]
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
@@ -422,13 +428,14 @@ services:
|
||||
image: ${API_IMAGE:-mtusi-messenger:lab7}
|
||||
command: ["python", "-m", "messenger.relay"]
|
||||
environment:
|
||||
<<: [*pipeline-env, *otel-env]
|
||||
<<: [*pipeline-env, *otel-env, *bao-env]
|
||||
OTEL_SERVICE_NAME: messenger-relay
|
||||
BAO_SECRET_PATH: messenger/data/relay
|
||||
RELAY_POLL_SECONDS: ${RELAY_POLL_SECONDS:-0.5}
|
||||
FAULT_POINTS: ${RELAY_FAULT_POINTS:-}
|
||||
secrets:
|
||||
- {source: database_url_relay, target: database_url}
|
||||
- {source: broker_url_relay, target: broker_url}
|
||||
- {source: bao_relay_role_id, target: bao_role_id}
|
||||
- {source: bao_relay_secret_id, target: bao_secret_id}
|
||||
- {source: pki_relay_crt, target: service.crt}
|
||||
- {source: pki_relay_key, target: service.key}
|
||||
- {source: pki_internal_ca, target: internal-ca.crt}
|
||||
@@ -445,9 +452,11 @@ services:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
openbao:
|
||||
condition: service_healthy
|
||||
stop_grace_period: 10s
|
||||
restart: unless-stopped
|
||||
networks: [data, queue, telemetry]
|
||||
networks: [data, queue, telemetry, vault]
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${RELAY_CPUS:-0.5}", memory: 256m}
|
||||
@@ -458,10 +467,9 @@ services:
|
||||
image: ${API_IMAGE:-mtusi-messenger:lab7}
|
||||
command: ["python", "-m", "messenger.worker"]
|
||||
environment:
|
||||
<<: [*pipeline-env, *otel-env]
|
||||
<<: [*pipeline-env, *otel-env, *bao-env]
|
||||
OTEL_SERVICE_NAME: messenger-worker
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
BAO_SECRET_PATH: messenger/data/worker
|
||||
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
|
||||
WORKER_SHUTDOWN_SECONDS: ${WORKER_SHUTDOWN_SECONDS:-20}
|
||||
IMAGE_MAX_MEMORY_MB: ${IMAGE_MAX_MEMORY_MB:-768}
|
||||
@@ -470,10 +478,8 @@ services:
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
|
||||
FAULT_POINTS: ${WORKER_FAULT_POINTS:-}
|
||||
secrets:
|
||||
- {source: database_url_worker, target: database_url}
|
||||
- {source: broker_url_worker, target: broker_url}
|
||||
- {source: s3_worker_access_key_id, target: s3_access_key_id}
|
||||
- {source: s3_worker_secret_access_key, target: s3_secret_access_key}
|
||||
- {source: bao_worker_role_id, target: bao_role_id}
|
||||
- {source: bao_worker_secret_id, target: bao_secret_id}
|
||||
- {source: pki_worker_crt, target: service.crt}
|
||||
- {source: pki_worker_key, target: service.key}
|
||||
- {source: pki_internal_ca, target: internal-ca.crt}
|
||||
@@ -494,9 +500,11 @@ services:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
openbao:
|
||||
condition: service_healthy
|
||||
stop_grace_period: 30s # > WORKER_SHUTDOWN_SECONDS (20 s) + release
|
||||
restart: unless-stopped
|
||||
networks: [data, storage, queue, telemetry]
|
||||
networks: [data, storage, queue, telemetry, vault]
|
||||
deploy:
|
||||
replicas: ${WORKER_REPLICAS:-1}
|
||||
resources:
|
||||
@@ -585,6 +593,41 @@ services:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128m}
|
||||
|
||||
# ------------------------------------------------------------------ secrets (lab 7)
|
||||
# OpenBao, NOT dev mode: file storage on the volume baodata, TLS listener (infra/openbao/config.hcl),
|
||||
# starts SEALED. Operator: scripts/bao_operator.py bootstrap | unseal (docs/OPERATOR.md); the root
|
||||
# token and the unseal shares stay with the operator, outside the repository and all containers.
|
||||
# Reachable only on the internal network `vault` (api, relay, worker). Image user: openbao (non-root).
|
||||
openbao:
|
||||
image: openbao/openbao:2.7.3@sha256:b9418c63e2185157d8ee8689a8a93265d5aadad677d6320156172bd42ad3b10b
|
||||
command: ["server"] # entrypoint: bao server -config=/openbao/config (no -dev)
|
||||
environment:
|
||||
# For the operator CLI inside the container (docker compose exec): TLS to itself, verified.
|
||||
BAO_ADDR: https://127.0.0.1:8200
|
||||
BAO_CACERT: /run/secrets/internal-ca.crt
|
||||
secrets:
|
||||
- {source: pki_openbao_crt, target: openbao.crt}
|
||||
- {source: pki_openbao_key, target: openbao.key}
|
||||
- {source: pki_internal_ca, target: internal-ca.crt}
|
||||
volumes:
|
||||
- ./infra/openbao/config.hcl:/openbao/config/lab.hcl:ro
|
||||
- baodata:/openbao/file
|
||||
healthcheck:
|
||||
# `bao status` exits 0 only when initialized AND unsealed (2 = sealed): the application
|
||||
# services wait for this (depends_on service_healthy) - a sealed OpenBao starts no new replica.
|
||||
test: ["CMD", "bao", "status"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
stop_grace_period: 15s
|
||||
restart: unless-stopped
|
||||
networks: [vault]
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256m}
|
||||
memswap_limit: 256m
|
||||
|
||||
# ------------------------------------------------------------------ observability (lab 6)
|
||||
# Receives OTLP from api/relay/worker, limits memory, batches, forwards to the three stores.
|
||||
# Distroless image (no shell). Lab 7: receiver HTTPS + client certificate required, exporters mTLS.
|
||||
@@ -752,6 +795,8 @@ networks:
|
||||
telemetry:
|
||||
internal: true # OTLP + stores: apps, collector, prometheus, loki, tempo, grafana
|
||||
ui: # only Grafana: publishes 127.0.0.1:3000
|
||||
vault:
|
||||
internal: true # OpenBao: reachable only by api, relay, worker
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
@@ -762,6 +807,7 @@ volumes:
|
||||
lokidata:
|
||||
tempodata:
|
||||
grafanadata:
|
||||
baodata: # OpenBao storage (encrypted by its barrier key)
|
||||
|
||||
# Every value is a file in ./secrets (scripts/init_secrets.py, git-ignored), mounted read-only
|
||||
# under /run/secrets ONLY into the services listed above.
|
||||
@@ -782,20 +828,12 @@ secrets:
|
||||
file: ./secrets/pg_auditor_password
|
||||
database_url_migrate:
|
||||
file: ./secrets/database_url_migrate
|
||||
database_url_api:
|
||||
file: ./secrets/database_url_api
|
||||
database_url_relay:
|
||||
file: ./secrets/database_url_relay
|
||||
database_url_worker:
|
||||
file: ./secrets/database_url_worker
|
||||
database_url_jobctl:
|
||||
file: ./secrets/database_url_jobctl
|
||||
database_url_auditor:
|
||||
file: ./secrets/database_url_auditor
|
||||
valkey_api_password:
|
||||
file: ./secrets/valkey_api_password
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
s3_admin_access_key_id:
|
||||
file: ./secrets/s3_admin_access_key_id
|
||||
s3_admin_secret_access_key:
|
||||
@@ -814,10 +852,6 @@ secrets:
|
||||
file: ./secrets/s3_auditor_secret_access_key
|
||||
rabbitmq_users:
|
||||
file: ./secrets/rabbitmq_users.json
|
||||
broker_url_relay:
|
||||
file: ./secrets/broker_url_relay
|
||||
broker_url_worker:
|
||||
file: ./secrets/broker_url_worker
|
||||
grafana_admin_password:
|
||||
file: ./secrets/grafana_admin_password
|
||||
# Lab 7 PKI (scripts/init_pki.py). Each service mounts only its own certificate/key and the CA it
|
||||
@@ -886,6 +920,23 @@ secrets:
|
||||
file: ./secrets/pki/grafana-ui.crt
|
||||
pki_grafana_ui_key:
|
||||
file: ./secrets/pki/grafana-ui.key
|
||||
pki_openbao_crt:
|
||||
file: ./secrets/pki/openbao.crt
|
||||
pki_openbao_key:
|
||||
file: ./secrets/pki/openbao.key
|
||||
# AppRole credentials, written by scripts/bao_operator.py bootstrap (the first secret of a service).
|
||||
bao_api_role_id:
|
||||
file: ./secrets/bao/api_role_id
|
||||
bao_api_secret_id:
|
||||
file: ./secrets/bao/api_secret_id
|
||||
bao_relay_role_id:
|
||||
file: ./secrets/bao/relay_role_id
|
||||
bao_relay_secret_id:
|
||||
file: ./secrets/bao/relay_secret_id
|
||||
bao_worker_role_id:
|
||||
file: ./secrets/bao/worker_role_id
|
||||
bao_worker_secret_id:
|
||||
file: ./secrets/bao/worker_secret_id
|
||||
pki_foreign_lb_crt: # test only: foreign CA, SAN lb
|
||||
file: ./secrets/pki/foreign-lb.crt
|
||||
pki_foreign_lb_key:
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# OpenBao 2.7 server of the lab 7 stand (compose service `openbao`). NOT dev mode:
|
||||
# * persistent storage: integrated storage (Raft, ONE node - OpenBao 2.7 has no "file" backend
|
||||
# any more) on the named volume baodata (/openbao/file). Everything in it is encrypted by the
|
||||
# barrier key; it starts SEALED after every start and is unsealed by the operator
|
||||
# (scripts/bao_operator.py unseal). Single node = no replication: losing the volume loses the
|
||||
# secrets (they can be re-created from ./secrets by `bootstrap` on a fresh instance).
|
||||
# * TLS listener only (internal CA, SAN openbao + localhost/127.0.0.1 for the operator CLI inside
|
||||
# the container), TLS 1.2+; no plaintext listener, no UI, port not published on the host. The
|
||||
# Raft cluster port 8201 uses OpenBao's own automatic TLS and has no peers here.
|
||||
# * disable_mlock: the container runs without IPC_LOCK (no extra capabilities). The trade-off -
|
||||
# memory pages could be swapped - is accepted on this single-host lab stand: the container has
|
||||
# memswap_limit = memory limit (no swap). See docs/OPERATOR.md.
|
||||
ui = false
|
||||
disable_mlock = true
|
||||
api_addr = "https://openbao:8200"
|
||||
cluster_addr = "https://openbao:8201"
|
||||
log_level = "warn"
|
||||
|
||||
storage "raft" {
|
||||
path = "/openbao/file"
|
||||
node_id = "openbao-1"
|
||||
}
|
||||
|
||||
# Audit log of every request and response (secret values HMAC'ed, never in clear) to the container
|
||||
# stdout: `docker compose logs openbao` shows who read what and every denied request.
|
||||
audit "file" "stdout" {
|
||||
description = "lab 7 audit log"
|
||||
options {
|
||||
file_path = "stdout"
|
||||
}
|
||||
}
|
||||
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
cluster_address = "0.0.0.0:8201"
|
||||
tls_cert_file = "/run/secrets/openbao.crt"
|
||||
tls_key_file = "/run/secrets/openbao.key"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# Policy of the AppRole `api` (API replicas). Exactly one secret path, read only:
|
||||
# messenger/data/api = database_url (role messenger_api), cache_url (Valkey ACL user api),
|
||||
# s3_access_key_id / s3_secret_access_key (identity messenger-api: Write staging + Read final).
|
||||
# No metadata/list/write, no other service's path, no sys/*, no policy management. The token is
|
||||
# created with token_no_default_policy=true, so self-management is granted explicitly below.
|
||||
path "messenger/data/api" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/lookup-self" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/revoke-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Policy of the AppRole `relay`: messenger/data/relay = database_url (role messenger_relay) and
|
||||
# broker_url (RabbitMQ user relay: publish to the jobs exchange only). Read only, nothing else.
|
||||
path "messenger/data/relay" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/lookup-self" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/revoke-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
# Policy of the AppRole `worker`: messenger/data/worker = database_url (role messenger_worker),
|
||||
# broker_url (RabbitMQ user worker: consume the jobs queue only), s3 key pair messenger-worker
|
||||
# (staging + final, no List, no Admin). No admin credentials of the API, the database or S3.
|
||||
path "messenger/data/worker" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/lookup-self" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/revoke-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper: runs scripts\bao_check.sh (OpenBao allow/deny, no root credential in apps) with Git Bash.
|
||||
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0bao_check.sh"
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""OpenBao allow/deny check, run INSIDE a service container with that service's own credentials:
|
||||
|
||||
docker compose exec -T api python - < scripts/bao_check.py (wrapper: scripts/bao_check.sh)
|
||||
|
||||
Uses exactly what the service has: BAO_ADDR, BAO_CACERT (server verified), BAO_ROLE_ID_FILE,
|
||||
BAO_SECRET_ID_FILE, BAO_SECRET_PATH. Prints status codes and key NAMES only, never values or tokens.
|
||||
Expected for service S (api | relay | worker):
|
||||
allow AppRole login; read messenger/data/S; token lookup-self; revoke-self
|
||||
deny read messenger/data/<other services>; write/patch messenger/data/S; list metadata;
|
||||
write a policy; read the policy list; create a token; enable an auth method; read sys/mounts
|
||||
deny the revoked token afterwards; a login with a wrong secret_id
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ADDR = os.environ["BAO_ADDR"].rstrip("/")
|
||||
CTX = ssl.create_default_context(cafile=os.environ["BAO_CACERT"])
|
||||
PATH = os.environ["BAO_SECRET_PATH"]
|
||||
SERVICE = PATH.rsplit("/", 1)[-1]
|
||||
OTHERS = [s for s in ("api", "relay", "worker") if s != SERVICE]
|
||||
|
||||
|
||||
def call(method, path, token=None, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else (b"{}" if method in ("POST", "PUT") else None)
|
||||
req = urllib.request.Request(f"{ADDR}/v1/{path}", data=data, method=method,
|
||||
headers={"Content-Type": "application/json", **({"X-Vault-Token": token} if token else {})})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=5, context=CTX) as r:
|
||||
raw = r.read()
|
||||
return r.status, (json.loads(raw) if raw else {})
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, {}
|
||||
|
||||
|
||||
def read(name):
|
||||
with open(os.environ[name], encoding="utf-8") as f:
|
||||
return f.read().strip()
|
||||
|
||||
|
||||
failures = 0
|
||||
|
||||
|
||||
def expect(label, status, allowed):
|
||||
global failures
|
||||
ok = (200 <= status < 300) if allowed else status in (400, 403)
|
||||
failures += not ok
|
||||
print(f" {'PASS' if ok else 'FAIL'} {'allow' if allowed else 'deny '} {label:58s} -> HTTP {status}")
|
||||
|
||||
|
||||
print(f"service {SERVICE}: OpenBao {ADDR} (TLS verified against {os.environ['BAO_CACERT']})")
|
||||
status, body = call("POST", "auth/approle/login", body={"role_id": read("BAO_ROLE_ID_FILE"), "secret_id": read("BAO_SECRET_ID_FILE")})
|
||||
expect("AppRole login with the service's role_id/secret_id", status, True)
|
||||
auth = body.get("auth") or {}
|
||||
token = auth.get("client_token", "")
|
||||
print(f" token policies={auth.get('token_policies')} ttl={auth.get('lease_duration')}s renewable={auth.get('renewable')}")
|
||||
status, body = call("GET", PATH, token)
|
||||
expect(f"read own path {PATH}", status, True)
|
||||
print(f" keys: {sorted((body.get('data') or {}).get('data') or {})}")
|
||||
status, _ = call("GET", "auth/token/lookup-self", token)
|
||||
expect("token lookup-self", status, True)
|
||||
for other in OTHERS:
|
||||
expect(f"read other service's path messenger/data/{other}", call("GET", f"messenger/data/{other}", token)[0], False)
|
||||
expect(f"write own path {PATH}", call("POST", PATH, token, {"data": {"x": "y"}})[0], False)
|
||||
expect("list messenger/metadata", call("LIST", "messenger/metadata", token)[0], False)
|
||||
expect(f"write policy sys/policies/acl/{SERVICE}", call("PUT", f"sys/policies/acl/{SERVICE}", token, {"policy": 'path "*" {capabilities=["sudo"]}'})[0], False)
|
||||
expect("read policy list sys/policies/acl", call("LIST", "sys/policies/acl", token)[0], False)
|
||||
expect("create a child token auth/token/create", call("POST", "auth/token/create", token, {"policies": ["api"]})[0], False)
|
||||
expect("enable an auth method sys/auth/userpass", call("POST", "sys/auth/userpass", token, {"type": "userpass"})[0], False)
|
||||
expect("read sys/mounts", call("GET", "sys/mounts", token)[0], False)
|
||||
expect("revoke-self", call("POST", "auth/token/revoke-self", token)[0], True)
|
||||
expect("use the token after revoke-self (lookup-self)", call("GET", "auth/token/lookup-self", token)[0], False)
|
||||
expect("read own path with the revoked token", call("GET", PATH, token)[0], False)
|
||||
expect("AppRole login with a wrong secret_id", call("POST", "auth/approle/login", body={"role_id": read("BAO_ROLE_ID_FILE"), "secret_id": "00000000-0000-0000-0000-000000000000"})[0], False)
|
||||
print(f"{'PASS' if failures == 0 else 'FAIL'}: OpenBao policy of {SERVICE}, {failures} failure(s)")
|
||||
sys.exit(1 if failures else 0)
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/bin/sh
|
||||
# OpenBao proof (README defense step 4): policy allow/deny for every service + no root credential
|
||||
# in the application containers. Prints PASS/FAIL lines, never a token, share or secret value.
|
||||
# sh scripts/bao_check.sh (Windows: scripts\bao_check.cmd)
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
export MSYS_NO_PATHCONV=1 # Git Bash: keep /run/secrets as a container path
|
||||
OPERATOR_DIR="${OPERATOR_DIR:-$HOME/.mtusi-lab7-operator/${COMPOSE_PROJECT_NAME:-mtusi-lab7}}"
|
||||
rc=0
|
||||
for svc in api relay worker; do
|
||||
echo "== $svc"
|
||||
docker compose exec -T "$svc" python - < scripts/bao_check.py || rc=1
|
||||
done
|
||||
echo
|
||||
echo "== root credential / unseal material in the application containers (values compared, never printed)"
|
||||
for svc in api relay worker; do
|
||||
# 1. no token-like variable in the container configuration
|
||||
names="$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$(docker compose ps -q "$svc" | head -1)" \
|
||||
| cut -d= -f1 | grep -iE 'TOKEN|UNSEAL|ROOT' || true)"
|
||||
if [ -n "$names" ]; then echo " FAIL $svc: token-like env names: $names"; rc=1; else echo " PASS $svc: no *TOKEN*/*UNSEAL*/*ROOT* environment variable"; fi
|
||||
# 2. the operator's root token and unseal shares do not occur anywhere in the container's
|
||||
# secrets, code, temp files or process environment (fed via stdin, compared inside)
|
||||
# Positive control: the same search MUST find a value that is there (the service's own role_id),
|
||||
# otherwise "absent" below would prove nothing.
|
||||
found="$(docker compose exec -T "$svc" sh -c 'read -r v; grep -rlsF -- "$v" /run/secrets | head -1' < "secrets/bao/${svc}_role_id")"
|
||||
if [ -n "$found" ]; then echo " PASS control: own role_id found by the same search ($found)"; else echo " FAIL control search found nothing"; rc=1; fi
|
||||
for f in root-token unseal-share-1 unseal-share-2 unseal-share-3; do
|
||||
if [ ! -f "$OPERATOR_DIR/$f" ]; then echo " FAIL operator file $f missing in $OPERATOR_DIR"; rc=1; continue; fi
|
||||
found="$(docker compose exec -T "$svc" sh -c 'read -r v; for p in /run/secrets /app /tmp /proc/1/environ; do grep -rqsF -- "$v" "$p" && echo "$p"; done; true' < "$OPERATOR_DIR/$f")"
|
||||
if [ -n "$found" ]; then echo " FAIL $svc: $f found in $found"; rc=1; else echo " PASS $svc: $f absent (/run/secrets, /app, /tmp, PID 1 environment)"; fi
|
||||
done
|
||||
echo " $svc /run/secrets: $(docker compose exec -T "$svc" ls /run/secrets | tr '\n' ' ')"
|
||||
done
|
||||
[ "$rc" = 0 ] && echo "PASS: OpenBao allow/deny and no root credential in the application" || echo "FAIL"
|
||||
exit "$rc"
|
||||
@@ -0,0 +1,183 @@
|
||||
#!/usr/bin/env python3
|
||||
"""OpenBao operator actions of the lab 7 stand (docs/OPERATOR.md). Stdlib only; run on the host.
|
||||
|
||||
python scripts/bao_operator.py bootstrap # init (once) + unseal + configure + issue AppRole creds
|
||||
python scripts/bao_operator.py unseal # after every OpenBao (re)start: it starts SEALED
|
||||
python scripts/bao_operator.py status # initialized / sealed / mounts / roles (no secrets)
|
||||
python scripts/bao_operator.py new-secret-id api # issue a new SecretID for one service
|
||||
|
||||
Who holds what:
|
||||
* unseal shares (3, threshold 2) and the root token: the OPERATOR, in OPERATOR_DIR, outside the
|
||||
repository (default ~/.mtusi-lab7-operator/<compose project>/, files 0600). Never in Git, never
|
||||
in a container of the application, never printed. In a real team the 3 shares go to 3 people.
|
||||
* role_id + secret_id of api / relay / worker: ./secrets/bao/ (git-ignored), each pair mounted as
|
||||
a Docker secret ONLY into its own service - the "first secret" the service logs in with.
|
||||
* the root token is used only by this script, for configuration.
|
||||
|
||||
Every secret travels to the OpenBao CLI over the STDIN of `docker compose exec` (never as a command
|
||||
line argument or an environment variable of a process): the root token is the first stdin line,
|
||||
read by `read -r BAO_TOKEN`; KV values and policies follow as JSON/HCL on stdin (`-`).
|
||||
The CLI runs inside the openbao container against https://127.0.0.1:8200 with the internal CA
|
||||
(BAO_ADDR/BAO_CACERT in compose.yaml): the server certificate is verified.
|
||||
|
||||
Idempotent: init only if not initialized; mounts/auth/policies/roles/KV are (re)written to the
|
||||
state described here; an existing secret_id file is kept unless `new-secret-id` is asked.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / "secrets"
|
||||
POLICIES = ROOT / "infra" / "openbao" / "policies"
|
||||
PROJECT = os.environ.get("COMPOSE_PROJECT_NAME", "mtusi-lab7")
|
||||
OPERATOR_DIR = Path(os.environ.get("OPERATOR_DIR") or Path.home() / ".mtusi-lab7-operator" / PROJECT)
|
||||
SHARES, THRESHOLD = 3, 2
|
||||
# Token of a service: 1 h, at most 4 h with renewals; the services revoke it right after reading.
|
||||
# SecretID: valid 30 days, unlimited logins (every restart of a replica logs in again).
|
||||
ROLE_SETTINGS = ["token_ttl=1h", "token_max_ttl=4h", "token_type=service", "token_no_default_policy=true",
|
||||
"secret_id_ttl=720h", "secret_id_num_uses=0"]
|
||||
# What each service may read: KV v2 messenger/data/<service>. Values come from ./secrets.
|
||||
SERVICE_SECRETS = {
|
||||
"api": {"database_url": "database_url_api", "cache_url": "cache_url",
|
||||
"s3_access_key_id": "s3_api_access_key_id", "s3_secret_access_key": "s3_api_secret_access_key"},
|
||||
"relay": {"database_url": "database_url_relay", "broker_url": "broker_url_relay"},
|
||||
"worker": {"database_url": "database_url_worker", "broker_url": "broker_url_worker",
|
||||
"s3_access_key_id": "s3_worker_access_key_id", "s3_secret_access_key": "s3_worker_secret_access_key"},
|
||||
}
|
||||
|
||||
|
||||
def say(text: str) -> None:
|
||||
print(f"bao-operator: {text}", flush=True)
|
||||
|
||||
|
||||
def bao(*args: str, token: str | None = None, stdin: bytes = b"", check: bool = True) -> subprocess.CompletedProcess:
|
||||
"""Run `bao <args>` inside the openbao container; the token (if any) is the first stdin line."""
|
||||
script = 'read -r BAO_TOKEN; export BAO_TOKEN; exec bao "$@"' if token else 'exec bao "$@"'
|
||||
data = ((token + "\n").encode() if token else b"") + stdin
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "openbao", "sh", "-c", script, "sh", *args],
|
||||
input=data, capture_output=True, cwd=ROOT)
|
||||
if check and result.returncode != 0:
|
||||
# stderr of the CLI names the failing path/permission; it never contains our stdin data.
|
||||
raise SystemExit(f"bao-operator: `bao {' '.join(args)}` failed: {result.stderr.decode(errors='replace').strip()[:400]}")
|
||||
return result
|
||||
|
||||
|
||||
def status() -> dict:
|
||||
result = bao("status", "-format=json", check=False) # exit 2 = sealed, still prints JSON
|
||||
if result.returncode not in (0, 2):
|
||||
raise SystemExit("bao-operator: OpenBao is not reachable (is `docker compose up -d openbao` running?): "
|
||||
+ result.stderr.decode(errors="replace").strip()[:300])
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def private_write(path: Path, value: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(value + "\n", encoding="utf-8", newline="\n")
|
||||
os.chmod(path, 0o600)
|
||||
|
||||
|
||||
def operator_file(name: str) -> str:
|
||||
path = OPERATOR_DIR / name
|
||||
if not path.exists():
|
||||
raise SystemExit(f"bao-operator: {path} is missing: the operator material of this OpenBao is not here")
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
def init() -> None:
|
||||
if status()["initialized"]:
|
||||
say("already initialized")
|
||||
return
|
||||
if (OPERATOR_DIR / "root-token").exists():
|
||||
raise SystemExit(f"bao-operator: OpenBao is NOT initialized but {OPERATOR_DIR} has material of an older "
|
||||
"instance; move it away first (it does not belong to this storage)")
|
||||
out = json.loads(bao("operator", "init", f"-key-shares={SHARES}", f"-key-threshold={THRESHOLD}", "-format=json").stdout)
|
||||
for i, share in enumerate(out["unseal_keys_b64"], 1):
|
||||
private_write(OPERATOR_DIR / f"unseal-share-{i}", share)
|
||||
private_write(OPERATOR_DIR / "root-token", out["root_token"])
|
||||
os.chmod(OPERATOR_DIR, 0o700)
|
||||
say(f"initialized: {SHARES} unseal shares (threshold {THRESHOLD}) and the root token saved to {OPERATOR_DIR} "
|
||||
"(outside the repository; not printed)")
|
||||
|
||||
|
||||
def unseal() -> None:
|
||||
state = status()
|
||||
if not state["initialized"]:
|
||||
raise SystemExit("bao-operator: not initialized yet: run `bootstrap`")
|
||||
if not state["sealed"]:
|
||||
say("already unsealed")
|
||||
return
|
||||
for i in range(1, THRESHOLD + 1):
|
||||
bao("write", "-format=json", "sys/unseal", "key=-", stdin=operator_file(f"unseal-share-{i}").encode())
|
||||
state = status()
|
||||
if state["sealed"]:
|
||||
raise SystemExit("bao-operator: still sealed after the threshold of shares")
|
||||
say(f"unsealed with {THRESHOLD} of {SHARES} shares")
|
||||
|
||||
|
||||
def secret(name: str) -> str:
|
||||
return (SECRETS / name).read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
def configure() -> None:
|
||||
token = operator_file("root-token")
|
||||
mounts = json.loads(bao("secrets", "list", "-format=json", token=token).stdout)
|
||||
if "messenger/" not in mounts:
|
||||
bao("secrets", "enable", "-path=messenger", "-version=2", "kv", token=token)
|
||||
say("KV v2 mounted at messenger/")
|
||||
auths = json.loads(bao("auth", "list", "-format=json", token=token).stdout)
|
||||
if "approle/" not in auths:
|
||||
bao("auth", "enable", "approle", token=token)
|
||||
say("auth method approle enabled")
|
||||
# The audit device (file -> container stdout) is declared in infra/openbao/config.hcl:
|
||||
# OpenBao 2.7 refuses to enable audit devices over the API.
|
||||
for service, values in SERVICE_SECRETS.items():
|
||||
bao("policy", "write", service, "-", token=token, stdin=(POLICIES / f"{service}.hcl").read_bytes())
|
||||
bao("write", f"auth/approle/role/{service}", f"token_policies={service}", *ROLE_SETTINGS, token=token)
|
||||
data = {key: secret(source) for key, source in values.items()}
|
||||
bao("kv", "put", "-mount=messenger", service, "-", token=token, stdin=json.dumps(data).encode())
|
||||
role_id = json.loads(bao("read", "-format=json", f"auth/approle/role/{service}/role-id", token=token).stdout)["data"]["role_id"]
|
||||
private_write(SECRETS / "bao" / f"{service}_role_id", role_id)
|
||||
os.chmod(SECRETS / "bao" / f"{service}_role_id", 0o644) # readable by the container user (bind mount)
|
||||
if not (SECRETS / "bao" / f"{service}_secret_id").exists():
|
||||
issue_secret_id(service, token)
|
||||
say(f"{service}: policy {service} (read messenger/data/{service}), AppRole, KV keys {sorted(data)}")
|
||||
|
||||
|
||||
def issue_secret_id(service: str, token: str | None = None) -> None:
|
||||
token = token or operator_file("root-token")
|
||||
out = json.loads(bao("write", "-f", "-format=json", f"auth/approle/role/{service}/secret-id", token=token).stdout)
|
||||
path = SECRETS / "bao" / f"{service}_secret_id"
|
||||
private_write(path, out["data"]["secret_id"])
|
||||
os.chmod(path, 0o644) # the service reads it through the bind mount (folder ./secrets is 0700)
|
||||
say(f"{service}: new SecretID written to secrets/bao/{service}_secret_id (TTL 720h; not printed)")
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
command = argv[0] if argv else "status"
|
||||
if command == "bootstrap":
|
||||
init()
|
||||
unseal()
|
||||
configure()
|
||||
say("done; start the stand: docker compose up -d --build --wait")
|
||||
elif command == "unseal":
|
||||
unseal()
|
||||
elif command == "status":
|
||||
state = status()
|
||||
say(f"initialized={state['initialized']} sealed={state['sealed']} storage={state.get('storage_type')} "
|
||||
f"version={state.get('version')} operator_dir={OPERATOR_DIR}")
|
||||
elif command == "new-secret-id" and len(argv) == 2 and argv[1] in SERVICE_SECRETS:
|
||||
issue_secret_id(argv[1])
|
||||
say(f"restart the service to use it: docker compose up -d --force-recreate {argv[1]}")
|
||||
else:
|
||||
print(__doc__)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
+13
-8
@@ -1,21 +1,26 @@
|
||||
#!/bin/sh
|
||||
# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`.
|
||||
# Restarts EVERY process of the stand: LB, all API replicas, relay, worker(s), PostgreSQL, Valkey,
|
||||
# S3 (SeaweedFS) and the broker (RabbitMQ). Volumes, schema, data and queued messages are
|
||||
# preserved: no `down -v`, no FLUSH, no purge, no re-seed.
|
||||
# Output is suppressed by the test; run it by hand to see the steps.
|
||||
# S3 (SeaweedFS), the broker (RabbitMQ) and OpenBao. Volumes, schema, data, queued messages and the
|
||||
# OpenBao storage are preserved: no `down -v`, no FLUSH, no purge, no re-seed.
|
||||
# Lab 7: OpenBao comes back SEALED; the operator unseal step (scripts/bao_operator.py unseal, shares
|
||||
# from the operator directory outside the repository) runs before the services that need secrets.
|
||||
# Output is suppressed by the test; run it by hand to see the steps (no secret is printed).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PYTHON:-python}"
|
||||
|
||||
# 1. Entry point, API and the pipeline processes first: nothing is served or processed while the
|
||||
# stores restart underneath.
|
||||
docker compose stop lb api relay worker
|
||||
# 2. Stores: clean shutdown (PostgreSQL checkpoint, Valkey AOF fsync, SeaweedFS volume/filer
|
||||
# flush, RabbitMQ quorum log), then start again. Bytes live on s3data, messages on rabbitmqdata.
|
||||
docker compose restart postgres valkey s3 broker
|
||||
# 3. API replicas (wait for healthy stores via depends_on), the LB, then relay and worker. HAProxy
|
||||
# resolves the new replica addresses through Docker DNS by itself - no stale backend list.
|
||||
# flush, RabbitMQ quorum log, OpenBao raft), then start again.
|
||||
docker compose restart postgres valkey s3 broker openbao
|
||||
# 3. Operator: unseal (OpenBao is sealed after every start).
|
||||
"$PY" scripts/bao_operator.py unseal
|
||||
# 4. API replicas (log in to OpenBao again, read their secrets), the LB, then relay and worker.
|
||||
# HAProxy resolves the new replica addresses through Docker DNS by itself.
|
||||
docker compose start api
|
||||
docker compose start lb
|
||||
docker compose start relay worker
|
||||
echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3 and broker restarted with volumes preserved"
|
||||
echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3, broker and openbao restarted with volumes preserved; openbao unsealed"
|
||||
|
||||
@@ -56,6 +56,7 @@ class GracefulServer(uvicorn.Server):
|
||||
|
||||
|
||||
def main() -> int:
|
||||
logging_setup.configure_early()
|
||||
try:
|
||||
settings = Settings.from_env()
|
||||
except ConfigError as exc:
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Lab 7: secrets of a service from OpenBao (AppRole login -> read own KV path -> revoke token).
|
||||
|
||||
Used by config._secret(): when BAO_ADDR is set, DATABASE_URL / CACHE_URL / S3_* / BROKER_URL come from
|
||||
`BAO_SECRET_PATH` (e.g. messenger/data/api) instead of files. Startup sequence (once per process):
|
||||
|
||||
1. read role_id + secret_id from BAO_ROLE_ID_FILE / BAO_SECRET_ID_FILE (Docker secrets of THIS
|
||||
service only; the "first secret" delivered by the operator, scripts/bao_operator.py);
|
||||
2. POST auth/approle/login over HTTPS (server verified: BAO_CACERT = internal CA, hostname openbao)
|
||||
-> a service token with ONE policy (read its own path), TTL 1 h;
|
||||
3. GET the KV path -> the values stay in process memory only (never logged, never written);
|
||||
4. POST auth/token/revoke-self: the token is dead seconds after it was created.
|
||||
|
||||
Failure modes (README "что происходит при ..."):
|
||||
* OpenBao sealed/stopped at start: retried for BAO_STARTUP_TIMEOUT_SECONDS, then the process exits
|
||||
(configuration error) and Docker restarts it; replicas that are already running are not
|
||||
affected - they do not need OpenBao after startup.
|
||||
* Token expiry: irrelevant after startup (revoked anyway); every new process logs in again.
|
||||
* Wrong/expired secret_id or a policy denial: fail at once with the HTTP status, no retry.
|
||||
No root token, no unseal key and no long-lived token ever exist in an application container.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
log = logging.getLogger("messenger.bao")
|
||||
|
||||
_cache: dict[str, str] | None = None
|
||||
|
||||
|
||||
class BaoError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
return bool(os.environ.get("BAO_ADDR", "").strip())
|
||||
|
||||
|
||||
def _file(name: str) -> str:
|
||||
path = os.environ.get(name, "").strip()
|
||||
if not path:
|
||||
raise BaoError(f"{name} must be set when BAO_ADDR is set")
|
||||
try:
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
except OSError as exc:
|
||||
raise BaoError(f"{name}={path} cannot be read: {exc.strerror}") from None
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, addr: str, ca_file: str, timeout: float = 5.0):
|
||||
self.addr = addr.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self.context = ssl.create_default_context(cafile=ca_file or None) # verify chain + hostname
|
||||
self.context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
|
||||
def call(self, method: str, path: str, token: str | None = None, body: dict | None = None) -> dict:
|
||||
data = json.dumps(body).encode() if body is not None else (b"" if method == "POST" else None)
|
||||
request = urllib.request.Request(f"{self.addr}/v1/{path}", data=data, method=method)
|
||||
request.add_header("Content-Type", "application/json")
|
||||
if token:
|
||||
request.add_header("X-Vault-Token", token)
|
||||
with urllib.request.urlopen(request, timeout=self.timeout, context=self.context) as response:
|
||||
raw = response.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def _status(exc: Exception) -> int | None:
|
||||
return exc.code if isinstance(exc, urllib.error.HTTPError) else None
|
||||
|
||||
|
||||
def fetch() -> dict[str, str]:
|
||||
"""Login, read the service's KV path, revoke the token. Values are cached for the process."""
|
||||
global _cache
|
||||
if _cache is not None:
|
||||
return _cache
|
||||
client = Client(os.environ["BAO_ADDR"], os.environ.get("BAO_CACERT", "").strip())
|
||||
path = os.environ.get("BAO_SECRET_PATH", "").strip()
|
||||
if not path:
|
||||
raise BaoError("BAO_SECRET_PATH must be set when BAO_ADDR is set")
|
||||
role_id, secret_id = _file("BAO_ROLE_ID_FILE"), _file("BAO_SECRET_ID_FILE")
|
||||
deadline = time.monotonic() + float(os.environ.get("BAO_STARTUP_TIMEOUT_SECONDS", "60"))
|
||||
while True:
|
||||
try:
|
||||
auth = client.call("POST", "auth/approle/login", body={"role_id": role_id, "secret_id": secret_id})["auth"]
|
||||
token = auth["client_token"]
|
||||
try:
|
||||
data = client.call("GET", path, token=token)["data"]["data"]
|
||||
finally:
|
||||
try:
|
||||
client.call("POST", "auth/token/revoke-self", token=token)
|
||||
except (urllib.error.URLError, OSError):
|
||||
pass # TTL (1 h) bounds the token anyway
|
||||
break
|
||||
except (urllib.error.URLError, OSError, KeyError, ValueError) as exc:
|
||||
status = _status(exc)
|
||||
# 503 = sealed / standby, no status = unreachable: wait for the operator. 4xx = our
|
||||
# credentials or the policy are wrong: retrying would not help.
|
||||
if status is not None and status != 503:
|
||||
raise BaoError(f"OpenBao refused {path!r} for this service: HTTP {status}") from None
|
||||
if time.monotonic() > deadline:
|
||||
raise BaoError(f"OpenBao unavailable (sealed or unreachable): {type(exc).__name__}") from None
|
||||
log.warning("openbao_unavailable", extra={"fields": {"status": status, "error": type(exc).__name__}})
|
||||
time.sleep(2)
|
||||
if not isinstance(data, dict):
|
||||
raise BaoError(f"OpenBao path {path!r} has no KV data")
|
||||
log.info("secrets_loaded", extra={"fields": {
|
||||
"path": path, "keys": sorted(data), "policies": auth.get("token_policies"),
|
||||
"token_ttl_s": auth.get("lease_duration"), "token_revoked": True}})
|
||||
_cache = {str(k): str(v) for k, v in data.items()}
|
||||
return _cache
|
||||
+12
-1
@@ -77,7 +77,18 @@ def _choice(name: str, default: str, allowed: set[str]) -> str:
|
||||
|
||||
|
||||
def _secret(name: str, required: bool) -> str:
|
||||
"""Value of <NAME>_FILE (preferred, Docker secret) or <NAME> (local runs/tests)."""
|
||||
"""Value of a secret setting, in this order:
|
||||
1. OpenBao (lab 7, BAO_ADDR set): key name.lower() of the service's KV path (bao.py);
|
||||
2. <NAME>_FILE (Docker secret file: bootstrap jobs and operator tools);
|
||||
3. <NAME> (local runs/tests)."""
|
||||
from . import bao
|
||||
if bao.enabled():
|
||||
try:
|
||||
values = bao.fetch()
|
||||
except bao.BaoError as exc:
|
||||
raise ConfigError(str(exc)) from None
|
||||
if name.lower() in values:
|
||||
return values[name.lower()]
|
||||
path = os.environ.get(f"{name}_FILE", "").strip()
|
||||
if path:
|
||||
try:
|
||||
|
||||
@@ -7,6 +7,7 @@ from __future__ import annotations
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
from . import telemetry
|
||||
@@ -42,3 +43,10 @@ def configure(level: str) -> None:
|
||||
for name in ("uvicorn", "uvicorn.error"):
|
||||
logging.getLogger(name).handlers[:] = []
|
||||
logging.getLogger(name).propagate = True
|
||||
|
||||
|
||||
def configure_early() -> None:
|
||||
"""Before Settings exist (lab 7: secrets are fetched from OpenBao while the settings load, and
|
||||
those log lines must not be lost). Settings.from_env() validates LOG_LEVEL properly later."""
|
||||
raw = os.environ.get("LOG_LEVEL", "info").strip().lower()
|
||||
configure(raw if raw in {"debug", "info", "warning", "error"} else "info")
|
||||
|
||||
@@ -214,6 +214,7 @@ class Relay:
|
||||
|
||||
|
||||
def main() -> int:
|
||||
logging_setup.configure_early()
|
||||
try:
|
||||
settings = Settings.from_env(s3_credentials=False)
|
||||
if not settings.broker_url:
|
||||
|
||||
@@ -379,6 +379,7 @@ class Worker:
|
||||
|
||||
|
||||
def main() -> int:
|
||||
logging_setup.configure_early()
|
||||
try:
|
||||
settings = Settings.from_env()
|
||||
if not settings.broker_url:
|
||||
|
||||
Reference in New Issue
Block a user