lab7: PKI, mTLS infra, OpenBao non-dev, hardening, lifecycle scripts
This commit is contained in:
+111
-137
@@ -1,142 +1,45 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# Полный список переменных, которые читают приложение и стенд; значения-образцы
|
||||
# не являются секретами. Соответствие «переменная -> фактическая конфигурация»
|
||||
# описано в REPORT.md.
|
||||
#
|
||||
# Приложение (проверяется zod-схемой app/src/config/app-config.schema.ts):
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
DATABASE_URL=postgresql://messenger:change-me@postgres:5432/messenger
|
||||
REDIS_URL=redis://redis:6379
|
||||
DATABASE_POOL_MAX=10
|
||||
DATABASE_CONNECTION_TIMEOUT_MS=5000
|
||||
DATABASE_STATEMENT_TIMEOUT_MS=5000
|
||||
DATABASE_IDLE_TX_TIMEOUT_MS=30000
|
||||
CACHE_TTL_SECONDS=30
|
||||
CACHE_MODE=protected
|
||||
CACHE_LOCK_TTL_MS=1000
|
||||
CACHE_MISS_DELAY_MS=0
|
||||
# Бюджет проверки зависимостей в /health/ready: LB пробует ту же ручку
|
||||
# (timeout check 500 ms), поэтому проба обязана уложиться заметно раньше.
|
||||
HEALTH_TIMEOUT_MS=400
|
||||
# Токен доступа к /internal/metrics; сгенерируйте свой.
|
||||
METRICS_TOKEN=change-me
|
||||
# Дрейн перед выходом по SIGTERM: реплика перестаёт проходить пробы LB,
|
||||
# ждёт DRAIN_DELAY_MS (длиннее обнаружения отказа ~1 s) и только потом закрывается.
|
||||
DRAIN_DELAY_MS=3000
|
||||
# Переопределяет X-Instance-Id; по умолчанию это hostname контейнера
|
||||
# (= короткий ID контейнера, по нему работает scripts/stop-one.sh).
|
||||
# INSTANCE_ID=api-1
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
# Copy to .env via `scripts/init-env.sh`; NEVER commit .env or store secrets here!
|
||||
# В lab7 файл .env содержит ТОЛЬКО несекретную конфигурацию топологии и лимитов.
|
||||
# Все учётные данные приложения (DB, Redis, S3, METRICS_TOKEN) хранятся исключительно
|
||||
# в OpenBao (Raft KV v2) и запрашиваются сервисами в RAM по mTLS auth/cert.
|
||||
# Ключ корневого CA и Shamir-ключи OpenBao хранятся вне репозитория в $LAB7_OPERATOR_DIR.
|
||||
|
||||
# Стенд (compose.yaml и scripts/):
|
||||
# Топология и образ приложения
|
||||
APP_ENV=lab
|
||||
API_IMAGE=mtusi-messenger:lab7
|
||||
BUILD_ID=local
|
||||
API_REPLICAS=2
|
||||
WORKER_REPLICAS=1
|
||||
|
||||
# Опубликованные порты (наружу — только HTTPS 8443; админки — строго 127.0.0.1).
|
||||
# Plaintext :8080, postgres:5432, redis:6379 и broker:5672 не публикуются.
|
||||
PUBLIC_BASE_URL=https://localhost:8443
|
||||
APP_PUBLIC_PORT=8443
|
||||
LB_STATS_PORT=8404
|
||||
OPENBAO_PORT=8200
|
||||
S3_PUBLIC_PORT=9000
|
||||
PROMETHEUS_PORT=9090
|
||||
GRAFANA_PORT=3000
|
||||
|
||||
# Лимиты контейнеров
|
||||
API_CPUS_PER_REPLICA=1.5
|
||||
API_MEMORY_PER_REPLICA=1024m
|
||||
WORKER_CPUS=1.5
|
||||
WORKER_MEMORY=1280m
|
||||
PG_CPUS=1.5
|
||||
PG_MEMORY=512m
|
||||
REDIS_CPUS=0.25
|
||||
REDIS_MEMORY=128m
|
||||
LB_CPUS=0.25
|
||||
LB_MEMORY=128m
|
||||
# Тег образа API; BUILD_ID отличает сборки при rolling update.
|
||||
API_IMAGE=mtusi-messenger:lab7
|
||||
BUILD_ID=local
|
||||
APP_PUBLIC_PORT=8080
|
||||
LB_STATS_PORT=8404
|
||||
# Loopback-порты PostgreSQL/Redis нужны только операторским проверкам с хоста
|
||||
# (make test-e2e, psql). API-реплики портов не публикуют.
|
||||
POSTGRES_PUBLISHED_PORT=5432
|
||||
REDIS_PUBLISHED_PORT=6379
|
||||
|
||||
# PostgreSQL (пароль подставьте свой; тот же, что в DATABASE_URL):
|
||||
POSTGRES_DB=messenger
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=change-me
|
||||
|
||||
# Объектное хранилище MinIO. Credentials — файлы ./secrets/* (scripts/init-env.sh), не здесь.
|
||||
S3_ENDPOINT=http://s3:9000
|
||||
S3_PUBLIC_ENDPOINT=http://localhost:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_PUBLIC_BIND=127.0.0.1
|
||||
S3_PUBLIC_PORT=9000
|
||||
S3_CPUS=1.0
|
||||
S3_MEMORY=512m
|
||||
S3_CONNECT_TIMEOUT_MS=1000
|
||||
S3_REQUEST_TIMEOUT_MS=15000
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
# Каждая загрузка держит копию файла (≤ MAX_UPLOAD_BYTES) до полного декода;
|
||||
# худший декод (40 Мп RGBA16 interlaced PNG) ≈ 340 MiB. Граница памяти реплики:
|
||||
# базовый RSS (~250 MiB) + UPLOAD_MAX_IN_FLIGHT × 10 MiB + IMAGE_DECODE_MAX_CONCURRENT × 340 MiB
|
||||
# = 250 + 160 + 340 ≈ 750 MiB при API_MEMORY_PER_REPLICA=1024m.
|
||||
UPLOAD_MAX_IN_FLIGHT=16
|
||||
# Не больше стольких одновременных загрузок одного пользователя на реплику.
|
||||
UPLOAD_MAX_IN_FLIGHT_PER_USER=4
|
||||
IMAGE_DECODE_MAX_CONCURRENT=1
|
||||
DIRECT_UPLOAD_MAX_PENDING_PER_USER=10
|
||||
# UPLOAD_TIMEOUT_MS, DIRECT_UPLOAD_URL_TTL_SECONDS, ATTACHMENT_SWEEP_GRACE_SECONDS,
|
||||
# ATTACHMENT_SWEEP_INTERVAL_MS задаются в compose.yaml (environment) с умолчаниями
|
||||
# и переопределяются из shell только для экспериментов.
|
||||
|
||||
# lab5: очередь и асинхронная обработка изображений. URL брокера берётся из
|
||||
# файла секрета (scripts/init-env.sh), байты и credentials в сообщения не
|
||||
# попадают: только job_id/attachment_id/pipeline_version/attempt.
|
||||
BROKER_URL_FILE=/run/secrets/broker_url
|
||||
BROKER_DELIVERY_LIMIT=10
|
||||
BROKER_PUBLISH_TIMEOUT_MS=5000
|
||||
# Сколько заданий worker обрабатывает параллельно; prefetch равен этому числу.
|
||||
WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
JOB_LEASE_SECONDS=30
|
||||
JOB_RETRY_BASE_MS=1000
|
||||
JOB_RETRY_MAX_MS=30000
|
||||
PIPELINE_VERSION=1
|
||||
OUTBOX_POLL_INTERVAL_MS=500
|
||||
LEASE_REAPER_INTERVAL_MS=2000
|
||||
# 0 выключает фоновую уборку staging (ручной запуск остаётся).
|
||||
STAGING_CLEANUP_INTERVAL_MS=60000
|
||||
# Сколько staging-объект неуспешной загрузки живёт до удаления.
|
||||
STAGING_RETENTION_SECONDS=86400
|
||||
WORKER_HEALTH_PORT=8081
|
||||
QUEUED_RECONCILE_GRACE_SECONDS=15
|
||||
OUTBOX_RETENTION_SECONDS=86400
|
||||
JOB_EVENTS_RETENTION_SECONDS=2592000
|
||||
# 1 включает чтение fault:<point> из Redis; в обычном стенде — 0.
|
||||
FAULT_INJECTION_ENABLED=0
|
||||
WORKER_REPLICAS=1
|
||||
WORKER_CPUS=1.5
|
||||
# Бюджет worker: база ≈250 MiB + WORKER_CONCURRENCY × (10 MiB исходник +
|
||||
# ≈340 MiB худший декод 40 Мп) ≈ 950 MiB при concurrency 2; лимит 1280m.
|
||||
WORKER_MEMORY=1280m
|
||||
BROKER_CPUS=0.5
|
||||
BROKER_MEMORY=512m
|
||||
|
||||
# lab6: наблюдаемость (OpenTelemetry). OTEL_SERVICE_NAME здесь не задаётся:
|
||||
# compose.yaml выставляет messenger-api / messenger-worker литералами.
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
# Управляющие ключи (значения по умолчанию совпадают с compose.yaml):
|
||||
OTEL_SDK_DISABLED=false
|
||||
# Доля head sampling корневых трасс (ParentBased + TraceIdRatioBased), 0..1.
|
||||
OTEL_TRACES_SAMPLER_ARG=1
|
||||
OTEL_METRIC_EXPORT_INTERVAL=10000
|
||||
OTEL_EXPORTER_OTLP_TIMEOUT=5000
|
||||
OTEL_BSP_MAX_QUEUE_SIZE=2048
|
||||
OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512
|
||||
OTEL_BSP_SCHEDULE_DELAY=1000
|
||||
OTEL_BLRP_MAX_QUEUE_SIZE=2048
|
||||
OTEL_BLRP_MAX_EXPORT_BATCH_SIZE=512
|
||||
OTEL_BLRP_SCHEDULE_DELAY=1000
|
||||
LOG_LEVEL=INFO
|
||||
# Backend-ы наблюдаемости: loopback-порты UI и лимиты контейнеров.
|
||||
PROMETHEUS_PORT=9090
|
||||
GRAFANA_PORT=3000
|
||||
OPENBAO_CPUS=0.5
|
||||
OPENBAO_MEMORY=256m
|
||||
LB_CPUS=0.25
|
||||
LB_MEMORY=128m
|
||||
OTELGW_CPUS=0.25
|
||||
OTELGW_MEMORY=64m
|
||||
OTELCOL_CPUS=0.5
|
||||
OTELCOL_MEMORY=256m
|
||||
PROMETHEUS_CPUS=0.5
|
||||
@@ -148,15 +51,86 @@ TEMPO_MEMORY=512m
|
||||
GRAFANA_CPUS=0.5
|
||||
GRAFANA_MEMORY=384m
|
||||
|
||||
# lab7: TLS/mTLS, OpenBao и Argon2id (целевые переменные из skeleton lab7;
|
||||
# до реализации lab7 используются значения стенда lab6 выше).
|
||||
PUBLIC_BASE_URL=https://localhost:8443
|
||||
TLS_CA_FILE=/run/secrets/ca.crt
|
||||
TLS_CERT_FILE=/run/secrets/service.crt
|
||||
TLS_KEY_FILE=/run/secrets/service.key
|
||||
BAO_ADDR=https://openbao:8200
|
||||
BAO_CACERT=/run/secrets/bao-ca.crt
|
||||
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
|
||||
ARGON2_MEMORY_KIB=19456
|
||||
# PostgreSQL / Redis / S3 / RabbitMQ — несекретные имена БД, бакета и таймауты
|
||||
POSTGRES_DB=messenger
|
||||
DATABASE_POOL_MAX=10
|
||||
WORKER_DATABASE_POOL_MAX=6
|
||||
DATABASE_CONNECTION_TIMEOUT_MS=5000
|
||||
DATABASE_STATEMENT_TIMEOUT_MS=5000
|
||||
DATABASE_IDLE_TX_TIMEOUT_MS=30000
|
||||
CACHE_TTL_SECONDS=30
|
||||
CACHE_MODE=protected
|
||||
CACHE_LOCK_TTL_MS=1000
|
||||
CACHE_MISS_DELAY_MS=0
|
||||
SESSION_TTL_SECONDS=3600
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
HEALTH_TIMEOUT_MS=400
|
||||
DRAIN_DELAY_MS=3000
|
||||
|
||||
S3_PUBLIC_ENDPOINT=https://localhost:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_CONNECT_TIMEOUT_MS=1000
|
||||
S3_REQUEST_TIMEOUT_MS=15000
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
UPLOAD_MAX_IN_FLIGHT=16
|
||||
UPLOAD_MAX_IN_FLIGHT_PER_USER=4
|
||||
IMAGE_DECODE_MAX_CONCURRENT=1
|
||||
DIRECT_UPLOAD_MAX_PENDING_PER_USER=10
|
||||
UPLOAD_TIMEOUT_MS=25000
|
||||
DIRECT_UPLOAD_URL_TTL_SECONDS=300
|
||||
ATTACHMENT_SWEEP_GRACE_SECONDS=900
|
||||
ATTACHMENT_SWEEP_INTERVAL_MS=60000
|
||||
VIPS_DISC_THRESHOLD=1g
|
||||
|
||||
BROKER_DELIVERY_LIMIT=10
|
||||
BROKER_PUBLISH_TIMEOUT_MS=5000
|
||||
WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
JOB_LEASE_SECONDS=30
|
||||
JOB_RETRY_BASE_MS=1000
|
||||
JOB_RETRY_MAX_MS=30000
|
||||
PIPELINE_VERSION=1
|
||||
OUTBOX_POLL_INTERVAL_MS=500
|
||||
LEASE_REAPER_INTERVAL_MS=2000
|
||||
STAGING_CLEANUP_INTERVAL_MS=60000
|
||||
STAGING_RETENTION_SECONDS=86400
|
||||
WORKER_HEALTH_PORT=8081
|
||||
QUEUED_RECONCILE_GRACE_SECONDS=15
|
||||
OUTBOX_RETENTION_SECONDS=86400
|
||||
JOB_EVENTS_RETENTION_SECONDS=2592000
|
||||
FAULT_INJECTION_ENABLED=0
|
||||
|
||||
# lab7: параметры Argon2id, защиты от DoS на логин, rate-limit и ротации OpenBao/TLS
|
||||
ARGON2_MEMORY_KIB=32768
|
||||
ARGON2_ITERATIONS=2
|
||||
ARGON2_PARALLELISM=1
|
||||
AUTH_HASH_MAX_CONCURRENT=4
|
||||
AUTH_HASH_MAX_QUEUE=8
|
||||
AUTH_HASH_QUEUE_TIMEOUT_MS=2000
|
||||
LOGIN_RATE_LIMIT_USER_MAX=10
|
||||
LOGIN_RATE_LIMIT_IP_MAX=60
|
||||
REGISTER_RATE_LIMIT_IP_MAX=60
|
||||
LOGIN_RATE_LIMIT_WINDOW_SECONDS=60
|
||||
MAX_JSON_BODY_BYTES=65536
|
||||
TLS_RELOAD_INTERVAL_MS=5000
|
||||
BAO_REFRESH_INTERVAL_MS=15000
|
||||
BAO_TIMEOUT_MS=5000
|
||||
|
||||
# Наблюдаемость (OTLP поверх HTTPS + mTLS через otel-gateway)
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
OTEL_SDK_DISABLED=false
|
||||
OTEL_TRACES_SAMPLER_ARG=1
|
||||
OTEL_METRIC_EXPORT_INTERVAL=10000
|
||||
OTEL_EXPORTER_OTLP_TIMEOUT=5000
|
||||
OTEL_BSP_MAX_QUEUE_SIZE=2048
|
||||
OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512
|
||||
OTEL_BSP_SCHEDULE_DELAY=1000
|
||||
OTEL_BLRP_MAX_QUEUE_SIZE=2048
|
||||
OTEL_BLRP_MAX_EXPORT_BATCH_SIZE=512
|
||||
OTEL_BLRP_SCHEDULE_DELAY=1000
|
||||
LOG_LEVEL=INFO
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
PYTHON ?= python3
|
||||
BASE_URL ?= https://localhost:8443
|
||||
CA_FILE ?=
|
||||
CA_FILE ?= $(if $(wildcard $(CURDIR)/secrets/pki/ca.crt),$(CURDIR)/secrets/pki/ca.crt,)
|
||||
ACTION_SCRIPT ?=
|
||||
PROMETHEUS_URL ?= http://localhost:9090
|
||||
GRAFANA_URL ?= http://localhost:3000
|
||||
PROMETHEUS_URL ?= https://localhost:9090
|
||||
GRAFANA_URL ?= https://localhost:3000
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
CURL_TLS_ARGS = $(if $(CA_FILE),--cacert "$(CA_FILE)",)
|
||||
LAB6_ARGS = --base-url "$(BASE_URL)" --prometheus-url "$(PROMETHEUS_URL)" --grafana-url "$(GRAFANA_URL)" $(TLS_ARGS)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover test-security test-dependencies stand-up stand-down stand-status wait-ready init-env test-e2e s3-security consistency bench lab5-demo lab5-faults lab5-track2 jobs lab6-ready lab6-signals lab6-correlate lab6-redaction lab6-history lab6-incident-worker lab6-incident-db lab6-incident-telemetry lab6-track1
|
||||
.PHONY: help check validate test load test-persistence test-failover test-security test-dependencies \
|
||||
bootstrap unseal stand-up stand-down stand-status wait-ready init-env test-e2e s3-security consistency bench \
|
||||
lab5-demo lab5-faults lab5-track2 jobs \
|
||||
lab6-ready lab6-signals lab6-correlate lab6-redaction lab6-history lab6-incident-worker lab6-incident-db lab6-incident-telemetry lab6-track1 \
|
||||
lab7-tls-audit lab7-app-security lab7-openbao lab7-hardening lab7-track1
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes; test-security: external TLS check; init-env: .env + secrets; test-e2e: app e2e"
|
||||
@echo "check: offline structure; validate: OpenAPI; bootstrap: PKI + OpenBao + stand-up; unseal: operator OpenBao unseal; test: smoke; test-security: external TLS; lab7-*: Lab 7 security & Track 1 suites"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -42,6 +46,17 @@ COMPOSE = docker compose --env-file $(COMPOSE_ENV_FILE)
|
||||
test-dependencies:
|
||||
cd app && E2E_COMPOSE_DIR="$(CURDIR)" E2E_COMPOSE_ENV_FILE="$(COMPOSE_ENV_FILE)" npm run test:dependencies
|
||||
|
||||
bootstrap:
|
||||
./scripts/init-env.sh
|
||||
./scripts/pki-bootstrap.sh
|
||||
$(COMPOSE) up -d volumes-init openbao postgres redis s3 broker
|
||||
$(COMPOSE) up -d --no-recreate --wait postgres redis s3 broker
|
||||
./scripts/openbao-bootstrap.sh
|
||||
$(COMPOSE) up -d --build --wait
|
||||
|
||||
unseal:
|
||||
./scripts/openbao-unseal.sh
|
||||
|
||||
stand-up:
|
||||
$(COMPOSE) up -d --build --wait
|
||||
|
||||
@@ -113,3 +128,18 @@ lab6-incident-telemetry:
|
||||
|
||||
lab6-track1:
|
||||
$(PYTHON) scripts/lab6/track1.py $(LAB6_ARGS)
|
||||
|
||||
lab7-tls-audit:
|
||||
$(PYTHON) scripts/lab7/tls_audit.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
lab7-app-security:
|
||||
$(PYTHON) scripts/lab7/app_security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
lab7-openbao:
|
||||
$(PYTHON) scripts/lab7/openbao_lifecycle.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
lab7-hardening:
|
||||
$(PYTHON) scripts/lab7/hardening_audit.py
|
||||
|
||||
lab7-track1:
|
||||
$(PYTHON) scripts/lab7/track1_worker_compromise.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
+509
-202
@@ -1,20 +1,96 @@
|
||||
# Стенд lab7 (база lab6): клиент -> HAProxy -> API x N -> PostgreSQL + Redis + MinIO
|
||||
# + RabbitMQ; отдельный worker читает задания из quorum-очереди и публикует
|
||||
# оригинал и варианты в конечный S3-prefix. API отвечает 202 после COMMIT
|
||||
# (staging-объект + attachment + job + outbox), поэтому брокер не входит в
|
||||
# /health/ready и его недоступность не останавливает приём загрузок.
|
||||
# Одна команда запуска: make stand-up (docker compose --env-file .env up -d --build --wait)
|
||||
#
|
||||
# Проект запинен именем, чтобы имена контейнеров и labels были предсказуемы для
|
||||
# scripts/stop-one.sh; container_name нигде не задан, иначе масштабирование
|
||||
# одного Compose-service стало бы невозможным.
|
||||
# Стенд lab7 (Grade 5, Track 1 «Компрометация worker»):
|
||||
# - 4 изолированные сети: public_edge (только опубликованные порты), lb_api, app_data, obs_net (internal: true).
|
||||
# - Опубликованные порты: только HTTPS :8443 и loopback 127.0.0.1 admin (8404, 8200, 9000, 9090, 3000).
|
||||
# - Plaintext :8080, postgres:5432, redis:6379, broker:5672 наружу не публикуются и отключены.
|
||||
# - Секреты приложения (DB/Redis/S3/metrics) в .env и ./secrets/ отсутствуют:
|
||||
# api, worker и migrate получают их по mTLS auth/cert из non-dev Raft OpenBao.
|
||||
# - Все долгоживущие контейнеры: non-root user, read_only: true, cap_drop: [ALL],
|
||||
# no-new-privileges:true, bounded tmpfs, explicit CPU/RAM limits, pinned digests.
|
||||
# Единственное исключение 0:0 — одноразовый init-контейнер volumes-init (CHOWN, FOWNER).
|
||||
name: mtusi-lab7
|
||||
|
||||
networks:
|
||||
public_edge: {}
|
||||
lb_api:
|
||||
internal: true
|
||||
app_data:
|
||||
internal: true
|
||||
obs_net:
|
||||
internal: true
|
||||
|
||||
services:
|
||||
# One-shot volume ownership initializer: sets exact non-root UID:GID on named
|
||||
# volumes and exits (restart: 'no'). Only container running as UID 0.
|
||||
volumes-init:
|
||||
image: node:25.7.0-slim@sha256:e07427bc8f075386eafa62c1ddab758815f1fd11dd8eaacb61919e8b09ab00b3
|
||||
user: '0:0'
|
||||
entrypoint: ['node']
|
||||
command:
|
||||
[
|
||||
'-e',
|
||||
"const fs=require('node:fs');const specs=[['/mnt/postgres',70,70,0o700],['/mnt/redis',999,1000,0o750],['/mnt/s3',1000,1000,0o750],['/mnt/broker',100,101,0o750],['/mnt/openbao',100,1000,0o750],['/mnt/prometheus',65534,65534,0o750],['/mnt/loki',10001,10001,0o750],['/mnt/tempo',10001,10001,0o750],['/mnt/grafana',472,0,0o750]];for(const [p,u,g,m] of specs){fs.mkdirSync(p,{recursive:true});fs.chownSync(p,u,g);fs.chmodSync(p,m);}",
|
||||
]
|
||||
volumes:
|
||||
- postgres-data:/mnt/postgres
|
||||
- redis-data:/mnt/redis
|
||||
- s3-data:/mnt/s3
|
||||
- broker-data:/mnt/broker
|
||||
- openbao-data:/mnt/openbao
|
||||
- prometheus-data:/mnt/prometheus
|
||||
- loki-data:/mnt/loki
|
||||
- tempo-data:/mnt/tempo
|
||||
- grafana-data:/mnt/grafana
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
cap_add: ['CHOWN', 'FOWNER']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
restart: 'no'
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.25'
|
||||
memory: 128m
|
||||
|
||||
# Non-dev Raft OpenBao over TLS (:8200). Initialized/unsealed by host operator
|
||||
# scripts using Shamir shares stored outside Git in $LAB7_OPERATOR_DIR/openbao/.
|
||||
openbao:
|
||||
image: ghcr.io/openbao/openbao:2.4.4@sha256:595c83b42614a4d2b044608e4593c05b019c5db25bc9c185d8fff3ac96c03ddd
|
||||
user: '100:1000'
|
||||
entrypoint: ['/usr/bin/dumb-init', '--', 'bao']
|
||||
command: ['server', '-config=/openbao/config/openbao.hcl']
|
||||
ports:
|
||||
- '127.0.0.1:${OPENBAO_PORT:-8200}:8200'
|
||||
volumes:
|
||||
- ./infra/openbao/openbao.hcl:/openbao/config/openbao.hcl:ro
|
||||
- ./secrets/pki/openbao:/run/certs:ro
|
||||
- openbao-data:/openbao/file
|
||||
networks: [public_edge, app_data]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
|
||||
depends_on:
|
||||
volumes-init: { condition: service_completed_successfully }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '${OPENBAO_CPUS:-0.5}'
|
||||
memory: ${OPENBAO_MEMORY:-256m}
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
'CMD-SHELL',
|
||||
'BAO_ADDR=https://localhost:8200 BAO_CACERT=/run/certs/ca.crt bao status >/dev/null 2>&1',
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
|
||||
postgres:
|
||||
image: postgres:16.4-alpine
|
||||
# pg_stat_statements включён для трека 1 (агрегаты SQL по репликам);
|
||||
# max_connections поднят под N x DATABASE_POOL_MAX.
|
||||
image: postgres:16.4-alpine@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c
|
||||
user: '70:70'
|
||||
entrypoint: ['/bin/sh', '/etc/postgresql/entrypoint.sh']
|
||||
command:
|
||||
[
|
||||
'postgres',
|
||||
@@ -26,17 +102,43 @@ services:
|
||||
'shared_buffers=128MB',
|
||||
'-c',
|
||||
'effective_cache_size=384MB',
|
||||
'-c',
|
||||
'password_encryption=scram-sha-256',
|
||||
'-c',
|
||||
'hba_file=/etc/postgresql/pg_hba.conf',
|
||||
'-c',
|
||||
'ssl=on',
|
||||
'-c',
|
||||
'ssl_ca_file=/var/run/postgresql/certs/ca.crt',
|
||||
'-c',
|
||||
'ssl_cert_file=/var/run/postgresql/certs/server.crt',
|
||||
'-c',
|
||||
'ssl_key_file=/var/run/postgresql/certs/server.key',
|
||||
'-c',
|
||||
'ssl_crl_file=/var/run/postgresql/certs/ca.crl',
|
||||
'-c',
|
||||
'ssl_min_protocol_version=TLSv1.2',
|
||||
]
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
|
||||
# Только loopback: операторские проверки (host-side npm run test:e2e,
|
||||
# psql в evidence). API-реплики портов не публикуют вовсе.
|
||||
ports:
|
||||
- '127.0.0.1:${POSTGRES_PUBLISHED_PORT:-5432}:5432'
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_superuser_password
|
||||
secrets: [postgres_superuser_password]
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
- ./infra/postgres/01-init-roles.sql:/docker-entrypoint-initdb.d/01-init-roles.sql:ro
|
||||
- ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
|
||||
- ./infra/postgres/entrypoint.sh:/etc/postgresql/entrypoint.sh:ro
|
||||
- ./secrets/pki/postgres:/run/certs:ro
|
||||
networks: [app_data]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs:
|
||||
- '/tmp:size=32m,noexec,nosuid,nodev'
|
||||
- '/var/run/postgresql:size=16m,uid=70,gid=70,mode=0755,noexec,nosuid,nodev'
|
||||
depends_on:
|
||||
volumes-init: { condition: service_completed_successfully }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -46,20 +148,37 @@ services:
|
||||
test:
|
||||
[
|
||||
'CMD-SHELL',
|
||||
'pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}',
|
||||
'pg_isready -h 127.0.0.1 -p 5432 -U postgres -d $${POSTGRES_DB:-messenger}',
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: redis:7.4.2-alpine
|
||||
# appendonly: сессии и кэш переживают рестарт контейнера (проверка
|
||||
# сохранности с неизменным токеном). volatile-lru вытесняет только
|
||||
# ключи с TTL; в стенде у них ограниченный набор и объём.
|
||||
image: redis:7.4.2-alpine@sha256:02419de7eddf55aa5bcf49efb74e88fa8d931b4d77c07eff8a6b2144472b6952
|
||||
user: '999:1000'
|
||||
entrypoint: ['/bin/sh', '/etc/redis/entrypoint.sh']
|
||||
command:
|
||||
[
|
||||
'redis-server',
|
||||
'--port',
|
||||
'0',
|
||||
'--tls-port',
|
||||
'6379',
|
||||
'--tls-cert-file',
|
||||
'/run/certs/server.crt',
|
||||
'--tls-key-file',
|
||||
'/run/certs/server.key',
|
||||
'--tls-ca-cert-file',
|
||||
'/run/certs/ca.crt',
|
||||
'--tls-auth-clients',
|
||||
'yes',
|
||||
'--tls-session-caching',
|
||||
'no',
|
||||
'--tls-protocols',
|
||||
'TLSv1.2 TLSv1.3',
|
||||
'--aclfile',
|
||||
'/data/users.acl',
|
||||
'--appendonly',
|
||||
'yes',
|
||||
'--appendfsync',
|
||||
@@ -69,34 +188,54 @@ services:
|
||||
'--maxmemory-policy',
|
||||
'volatile-lru',
|
||||
]
|
||||
ports:
|
||||
- '127.0.0.1:${REDIS_PUBLISHED_PORT:-6379}:6379'
|
||||
secrets: [redis_admin_password, redis_health_password]
|
||||
volumes:
|
||||
- redis-data:/data
|
||||
- ./infra/redis/entrypoint.sh:/etc/redis/entrypoint.sh:ro
|
||||
- ./secrets/pki/redis:/run/certs:ro
|
||||
networks: [app_data]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=8m,noexec,nosuid,nodev']
|
||||
depends_on:
|
||||
volumes-init: { condition: service_completed_successfully }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '${REDIS_CPUS:-0.25}'
|
||||
memory: ${REDIS_MEMORY:-128m}
|
||||
healthcheck:
|
||||
test: ['CMD', 'redis-cli', 'ping']
|
||||
test:
|
||||
[
|
||||
'CMD-SHELL',
|
||||
'REDISCLI_AUTH="$(cat /run/secrets/redis_health_password)" redis-cli --tls --cacert /run/certs/ca.crt --cert /run/certs/health.crt --key /run/certs/health.key --user redis_health -h localhost -p 6379 ping | grep -q PONG',
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
|
||||
broker:
|
||||
image: rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e
|
||||
# Имя узла rabbit@broker должно оставаться стабильным: при смене
|
||||
# hostname данные в broker-data превращаются в сирот.
|
||||
hostname: broker
|
||||
secrets:
|
||||
- source: rabbitmq_conf
|
||||
target: /etc/rabbitmq/conf.d/20-credentials.conf
|
||||
user: '100:101'
|
||||
volumes:
|
||||
- broker-data:/var/lib/rabbitmq
|
||||
# rabbitmq_prometheus: агрегированные метрики на 15692 (наружу не публикуется).
|
||||
- ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
|
||||
# Портов нет: брокер доступен только сервисам compose-сети.
|
||||
- ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
|
||||
- ./infra/rabbitmq/definitions.json:/etc/rabbitmq/definitions.json:ro
|
||||
- ./infra/rabbitmq/init-worker.sh:/etc/rabbitmq/init-worker.sh:ro
|
||||
- ./secrets/pki/broker:/run/certs:ro
|
||||
networks: [app_data, obs_net]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs:
|
||||
- '/tmp:size=32m,noexec,nosuid,nodev'
|
||||
- '/var/log/rabbitmq:size=16m,noexec,nosuid,nodev'
|
||||
depends_on:
|
||||
volumes-init: { condition: service_completed_successfully }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -111,91 +250,90 @@ services:
|
||||
stop_grace_period: 30s
|
||||
restart: unless-stopped
|
||||
|
||||
# One-shot: creates the worker identity and tightens the API identity.
|
||||
# rabbitmqctl talks to rabbit@broker using the shared Erlang cookie, so the
|
||||
# data volume is mounted read-only.
|
||||
broker-init:
|
||||
image: rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e
|
||||
entrypoint: ['/bin/sh', '/bootstrap/init-worker.sh']
|
||||
volumes:
|
||||
- broker-data:/var/lib/rabbitmq:ro
|
||||
- ./infra/rabbitmq:/bootstrap:ro
|
||||
secrets: [broker_worker_password]
|
||||
depends_on:
|
||||
broker: { condition: service_healthy }
|
||||
restart: 'no'
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.25'
|
||||
memory: 128m
|
||||
|
||||
s3:
|
||||
image: minio/minio:RELEASE.2025-09-07T16-13-09Z@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e
|
||||
command: ['server', '/data', '--address', ':9000']
|
||||
user: '1000:1000'
|
||||
command: ['server', '/data', '--address', ':9000', '--certs-dir', '/etc/minio/certs']
|
||||
environment:
|
||||
MINIO_ROOT_USER_FILE: minio_root_user
|
||||
MINIO_ROOT_PASSWORD_FILE: minio_root_password
|
||||
MINIO_BROWSER: 'off'
|
||||
HOME: /tmp
|
||||
secrets: [minio_root_user, minio_root_password]
|
||||
# Консольный порт 9001 не публикуется, консоль отключена (MINIO_BROWSER=off).
|
||||
ports:
|
||||
- '${S3_PUBLIC_BIND:-127.0.0.1}:${S3_PUBLIC_PORT:-9000}:9000'
|
||||
- '127.0.0.1:${S3_PUBLIC_PORT:-9000}:9000'
|
||||
volumes:
|
||||
- s3-data:/data
|
||||
- ./secrets/pki/s3:/etc/minio/certs:ro
|
||||
networks: [public_edge, app_data]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
|
||||
depends_on:
|
||||
volumes-init: { condition: service_completed_successfully }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '${S3_CPUS:-1.0}'
|
||||
memory: ${S3_MEMORY:-512m}
|
||||
healthcheck:
|
||||
test: ['CMD', 'mc', 'ready', 'local']
|
||||
test:
|
||||
[
|
||||
'CMD-SHELL',
|
||||
'curl -fsS --cacert /etc/minio/certs/CAs/ca.crt https://localhost:9000/minio/health/live >/dev/null',
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
|
||||
# Идемпотентный bootstrap: bucket, политика, пользователь API.
|
||||
# Лимит 256m: mc admin policy attach на 128m получал OOM-kill (exit 137).
|
||||
s3-init:
|
||||
image: minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727
|
||||
entrypoint: ['/bin/sh', '/bootstrap/bootstrap.sh']
|
||||
environment:
|
||||
S3_BUCKET: '${S3_BUCKET:-messenger-attachments}'
|
||||
volumes:
|
||||
- ./infra/minio:/bootstrap:ro
|
||||
secrets:
|
||||
- minio_root_user
|
||||
- minio_root_password
|
||||
- s3_api_access_key_id
|
||||
- s3_api_secret_access_key
|
||||
- s3_worker_access_key_id
|
||||
- s3_worker_secret_access_key
|
||||
depends_on:
|
||||
s3: { condition: service_healthy }
|
||||
restart: 'no'
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.25'
|
||||
memory: 256m
|
||||
|
||||
# Миграции выполняются один раз отдельным сервисом, а не гонкой реплик:
|
||||
# api стартует только после его успешного завершения.
|
||||
# One-shot SQL migrations (001..010) under dedicated messenger_migrator role.
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
BUILD_ID: ${BUILD_ID:-local}
|
||||
image: ${API_IMAGE:-mtusi-messenger:lab7}
|
||||
user: '1000:1000'
|
||||
command: ['node', 'dist/database/migration.runner.js']
|
||||
env_file: [.env]
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
PG_HOST: postgres
|
||||
PG_PORT: '5432'
|
||||
PG_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
DATABASE_CONNECTION_TIMEOUT_MS: '${DATABASE_CONNECTION_TIMEOUT_MS:-5000}'
|
||||
DATABASE_STATEMENT_TIMEOUT_MS: '${DATABASE_STATEMENT_TIMEOUT_MS:-30000}'
|
||||
DATABASE_IDLE_TX_TIMEOUT_MS: '${DATABASE_IDLE_TX_TIMEOUT_MS:-30000}'
|
||||
TLS_ENABLED: 'true'
|
||||
TLS_CA_FILE: /run/certs/ca.crt
|
||||
TLS_CRL_FILE: /run/certs/ca.crl
|
||||
TLS_CLIENT_CERT_FILE: /run/certs/client.crt
|
||||
TLS_CLIENT_KEY_FILE: /run/certs/client.key
|
||||
BAO_ENABLED: 'true'
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/certs/ca.crt
|
||||
BAO_AUTH_METHOD: cert
|
||||
BAO_CERT_ROLE: messenger-migrator
|
||||
BAO_AUTH_ROLE: messenger-migrator
|
||||
BAO_SECRET_PATH: secret/data/messenger/migrator
|
||||
BAO_TIMEOUT_MS: '${BAO_TIMEOUT_MS:-5000}'
|
||||
volumes:
|
||||
- ./secrets/pki/migrate:/run/certs:ro
|
||||
networks: [app_data]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=8m,noexec,nosuid,nodev']
|
||||
depends_on:
|
||||
postgres: { condition: service_healthy }
|
||||
openbao: { condition: service_healthy }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.5'
|
||||
memory: 192m
|
||||
depends_on:
|
||||
postgres: { condition: service_healthy }
|
||||
redis: { condition: service_healthy }
|
||||
restart: 'no'
|
||||
|
||||
api:
|
||||
@@ -203,38 +341,98 @@ services:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
BUILD_ID: ${BUILD_ID:-unknown}
|
||||
BUILD_ID: ${BUILD_ID:-local}
|
||||
image: ${API_IMAGE:-mtusi-messenger:lab7}
|
||||
# Портов нет намеренно: единственная точка входа — HAProxy.
|
||||
env_file: [.env]
|
||||
user: '1000:1000'
|
||||
environment:
|
||||
DATABASE_POOL_MAX: ${DATABASE_POOL_MAX:-10}
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: '8443'
|
||||
API_HEALTH_PORT: '8081'
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
TLS_ENABLED: 'true'
|
||||
TLS_CA_FILE: /run/certs/ca.crt
|
||||
TLS_CRL_FILE: /run/certs/ca.crl
|
||||
TLS_SERVER_CERT_FILE: /run/certs/server.crt
|
||||
TLS_SERVER_KEY_FILE: /run/certs/server.key
|
||||
TLS_CLIENT_CERT_FILE: /run/certs/client.crt
|
||||
TLS_CLIENT_KEY_FILE: /run/certs/client.key
|
||||
TLS_ALLOWED_CLIENT_SANS: haproxy-lb
|
||||
TLS_RELOAD_INTERVAL_MS: '${TLS_RELOAD_INTERVAL_MS:-5000}'
|
||||
BAO_ENABLED: 'true'
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/certs/ca.crt
|
||||
BAO_AUTH_METHOD: cert
|
||||
BAO_CERT_ROLE: messenger-api
|
||||
BAO_AUTH_ROLE: messenger-api
|
||||
BAO_SECRET_PATH: secret/data/messenger/api
|
||||
BAO_REFRESH_INTERVAL_MS: '${BAO_REFRESH_INTERVAL_MS:-15000}'
|
||||
BAO_TIMEOUT_MS: '${BAO_TIMEOUT_MS:-5000}'
|
||||
PG_HOST: postgres
|
||||
PG_PORT: '5432'
|
||||
PG_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
DATABASE_POOL_MAX: '${DATABASE_POOL_MAX:-10}'
|
||||
DATABASE_CONNECTION_TIMEOUT_MS: '${DATABASE_CONNECTION_TIMEOUT_MS:-5000}'
|
||||
DATABASE_STATEMENT_TIMEOUT_MS: '${DATABASE_STATEMENT_TIMEOUT_MS:-5000}'
|
||||
DATABASE_IDLE_TX_TIMEOUT_MS: '${DATABASE_IDLE_TX_TIMEOUT_MS:-30000}'
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: '6379'
|
||||
REDIS_TLS_MTLS: 'true'
|
||||
CACHE_MODE: ${CACHE_MODE:-protected}
|
||||
CACHE_MISS_DELAY_MS: ${CACHE_MISS_DELAY_MS:-0}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
# Бюджет пробы готовности; LB проверяет ту же ручку с timeout check 500 ms.
|
||||
HEALTH_TIMEOUT_MS: ${HEALTH_TIMEOUT_MS:-400}
|
||||
# Дрейн длиннее обнаружения отказа LB (500 ms x fall 2 ≈ 1 s).
|
||||
DRAIN_DELAY_MS: ${DRAIN_DELAY_MS:-3000}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_api_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_api_secret_access_key
|
||||
UPLOAD_TIMEOUT_MS: ${UPLOAD_TIMEOUT_MS:-25000}
|
||||
DIRECT_UPLOAD_URL_TTL_SECONDS: ${DIRECT_UPLOAD_URL_TTL_SECONDS:-300}
|
||||
ATTACHMENT_SWEEP_GRACE_SECONDS: ${ATTACHMENT_SWEEP_GRACE_SECONDS:-900}
|
||||
ATTACHMENT_SWEEP_INTERVAL_MS: ${ATTACHMENT_SWEEP_INTERVAL_MS:-60000}
|
||||
# libvips держит декодируемое изображение в памяти, а не во временном
|
||||
# файле: /tmp — tmpfs 16 MiB, и изображение ~40 Мп туда не помещается.
|
||||
CACHE_TTL_SECONDS: '${CACHE_TTL_SECONDS:-30}'
|
||||
CACHE_LOCK_TTL_MS: '${CACHE_LOCK_TTL_MS:-1000}'
|
||||
CACHE_MISS_DELAY_MS: '${CACHE_MISS_DELAY_MS:-0}'
|
||||
SESSION_TTL_SECONDS: '${SESSION_TTL_SECONDS:-3600}'
|
||||
IDEMPOTENCY_TTL_SECONDS: '${IDEMPOTENCY_TTL_SECONDS:-86400}'
|
||||
ARGON2_MEMORY_KIB: '${ARGON2_MEMORY_KIB:-32768}'
|
||||
ARGON2_ITERATIONS: '${ARGON2_ITERATIONS:-2}'
|
||||
ARGON2_PARALLELISM: '${ARGON2_PARALLELISM:-1}'
|
||||
AUTH_HASH_MAX_CONCURRENT: '${AUTH_HASH_MAX_CONCURRENT:-4}'
|
||||
AUTH_HASH_MAX_QUEUE: '${AUTH_HASH_MAX_QUEUE:-8}'
|
||||
AUTH_HASH_QUEUE_TIMEOUT_MS: '${AUTH_HASH_QUEUE_TIMEOUT_MS:-2000}'
|
||||
LOGIN_RATE_LIMIT_USER_MAX: '${LOGIN_RATE_LIMIT_USER_MAX:-10}'
|
||||
LOGIN_RATE_LIMIT_IP_MAX: '${LOGIN_RATE_LIMIT_IP_MAX:-60}'
|
||||
REGISTER_RATE_LIMIT_IP_MAX: '${REGISTER_RATE_LIMIT_IP_MAX:-60}'
|
||||
LOGIN_RATE_LIMIT_WINDOW_SECONDS: '${LOGIN_RATE_LIMIT_WINDOW_SECONDS:-60}'
|
||||
MAX_JSON_BODY_BYTES: '${MAX_JSON_BODY_BYTES:-65536}'
|
||||
HEALTH_TIMEOUT_MS: '${HEALTH_TIMEOUT_MS:-400}'
|
||||
DRAIN_DELAY_MS: '${DRAIN_DELAY_MS:-3000}'
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-https://localhost:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_CONNECT_TIMEOUT_MS: '${S3_CONNECT_TIMEOUT_MS:-1000}'
|
||||
S3_REQUEST_TIMEOUT_MS: '${S3_REQUEST_TIMEOUT_MS:-15000}'
|
||||
MAX_UPLOAD_BYTES: '${MAX_UPLOAD_BYTES:-10485760}'
|
||||
MAX_IMAGE_PIXELS: '${MAX_IMAGE_PIXELS:-40000000}'
|
||||
UPLOAD_MAX_IN_FLIGHT: '${UPLOAD_MAX_IN_FLIGHT:-16}'
|
||||
UPLOAD_MAX_IN_FLIGHT_PER_USER: '${UPLOAD_MAX_IN_FLIGHT_PER_USER:-4}'
|
||||
IMAGE_DECODE_MAX_CONCURRENT: '${IMAGE_DECODE_MAX_CONCURRENT:-1}'
|
||||
DIRECT_UPLOAD_MAX_PENDING_PER_USER: '${DIRECT_UPLOAD_MAX_PENDING_PER_USER:-10}'
|
||||
UPLOAD_TIMEOUT_MS: '${UPLOAD_TIMEOUT_MS:-25000}'
|
||||
DIRECT_UPLOAD_URL_TTL_SECONDS: '${DIRECT_UPLOAD_URL_TTL_SECONDS:-300}'
|
||||
ATTACHMENT_SWEEP_GRACE_SECONDS: '${ATTACHMENT_SWEEP_GRACE_SECONDS:-900}'
|
||||
ATTACHMENT_SWEEP_INTERVAL_MS: '${ATTACHMENT_SWEEP_INTERVAL_MS:-60000}'
|
||||
VIPS_DISC_THRESHOLD: ${VIPS_DISC_THRESHOLD:-1g}
|
||||
FAULT_INJECTION_ENABLED: ${FAULT_INJECTION_ENABLED:-0}
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_RETRY_BASE_MS: ${JOB_RETRY_BASE_MS:-1000}
|
||||
JOB_RETRY_MAX_MS: ${JOB_RETRY_MAX_MS:-30000}
|
||||
BROKER_PUBLISH_TIMEOUT_MS: ${BROKER_PUBLISH_TIMEOUT_MS:-5000}
|
||||
# lab6: телеметрия. Collector НЕ в depends_on: приложение обязано
|
||||
# стартовать и работать без телеметрии.
|
||||
BROKER_HOST: broker
|
||||
BROKER_PORT: '5671'
|
||||
BROKER_VHOST: messenger
|
||||
BROKER_ROLE: producer
|
||||
BROKER_AUTH_MECHANISM: external
|
||||
BROKER_PASSIVE_TOPOLOGY: 'true'
|
||||
BROKER_DELIVERY_LIMIT: '${BROKER_DELIVERY_LIMIT:-10}'
|
||||
BROKER_PUBLISH_TIMEOUT_MS: '${BROKER_PUBLISH_TIMEOUT_MS:-5000}'
|
||||
OUTBOX_POLL_INTERVAL_MS: '${OUTBOX_POLL_INTERVAL_MS:-500}'
|
||||
FAULT_INJECTION_ENABLED: '${FAULT_INJECTION_ENABLED:-0}'
|
||||
JOB_MAX_ATTEMPTS: '${JOB_MAX_ATTEMPTS:-5}'
|
||||
JOB_RETRY_BASE_MS: '${JOB_RETRY_BASE_MS:-1000}'
|
||||
JOB_RETRY_MAX_MS: '${JOB_RETRY_MAX_MS:-30000}'
|
||||
PIPELINE_VERSION: '${PIPELINE_VERSION:-1}'
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-https://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/certs/ca.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/certs/client.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/certs/client.key
|
||||
OTEL_SDK_DISABLED: '${OTEL_SDK_DISABLED:-false}'
|
||||
OTEL_TRACES_SAMPLER_ARG: '${OTEL_TRACES_SAMPLER_ARG:-1}'
|
||||
OTEL_METRIC_EXPORT_INTERVAL: '${OTEL_METRIC_EXPORT_INTERVAL:-10000}'
|
||||
@@ -248,20 +446,15 @@ services:
|
||||
OTEL_BLRP_MAX_QUEUE_SIZE: '${OTEL_BLRP_MAX_QUEUE_SIZE:-2048}'
|
||||
OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: '${OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:-512}'
|
||||
OTEL_BLRP_SCHEDULE_DELAY: '${OTEL_BLRP_SCHEDULE_DELAY:-1000}'
|
||||
# Недоступный otel-collector: getaddrinfo по неизвестному имени в сети
|
||||
# Docker занимает поток libuv на секунды и без запаса голодают DNS-
|
||||
# запросы к postgres/s3 (проверено: 5-7 с на ENOTFOUND).
|
||||
UV_THREADPOOL_SIZE: '32'
|
||||
dns_opt: ['timeout:1', 'attempts:1']
|
||||
# Outbox закрывает недоступность брокера: API принимает загрузку и
|
||||
# отвечает 202 без публикации, relay доставит задание после восстановления.
|
||||
secrets:
|
||||
- s3_api_access_key_id
|
||||
- s3_api_secret_access_key
|
||||
- broker_url
|
||||
# Корневая ФС только для чтения: локального файла оригинала на API нет.
|
||||
volumes:
|
||||
- ./secrets/pki/api:/run/certs:ro
|
||||
networks: [lb_api, app_data]
|
||||
read_only: true
|
||||
tmpfs: ['/tmp:size=16m']
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
@@ -272,56 +465,94 @@ services:
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
migrate: { condition: service_completed_successfully }
|
||||
openbao: { condition: service_healthy }
|
||||
postgres: { condition: service_healthy }
|
||||
redis: { condition: service_healthy }
|
||||
s3-init: { condition: service_completed_successfully }
|
||||
s3: { condition: service_healthy }
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
'CMD',
|
||||
'node',
|
||||
'-e',
|
||||
"fetch('http://127.0.0.1:'+ (process.env.APP_PORT||8080) + '/health/ready').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))",
|
||||
"fetch('http://127.0.0.1:' + (process.env.API_HEALTH_PORT || 8081) + '/health/ready').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))",
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
# Worker — отдельный процесс без HTTP API. Он читает задания из quorum-
|
||||
# очереди, держит lease с heartbeat, пишет варианты и коммитит результат в
|
||||
# PostgreSQL. Остановка worker не блокирует приём загрузок API.
|
||||
# Least-privilege worker: NO Redis creds/module, NO S3_PUBLIC_ENDPOINT,
|
||||
# consumer-only RabbitMQ EXTERNAL identity, column-scoped PG role.
|
||||
worker:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
BUILD_ID: ${BUILD_ID:-unknown}
|
||||
BUILD_ID: ${BUILD_ID:-local}
|
||||
image: ${API_IMAGE:-mtusi-messenger:lab7}
|
||||
user: '1000:1000'
|
||||
command: ['node', 'dist/worker.main.js']
|
||||
env_file: [.env]
|
||||
environment:
|
||||
BROKER_URL_FILE: /run/secrets/broker_worker_url
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_worker_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_worker_secret_access_key
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
TLS_ENABLED: 'true'
|
||||
TLS_CA_FILE: /run/certs/ca.crt
|
||||
TLS_CRL_FILE: /run/certs/ca.crl
|
||||
TLS_CLIENT_CERT_FILE: /run/certs/client.crt
|
||||
TLS_CLIENT_KEY_FILE: /run/certs/client.key
|
||||
TLS_RELOAD_INTERVAL_MS: '${TLS_RELOAD_INTERVAL_MS:-5000}'
|
||||
BAO_ENABLED: 'true'
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/certs/ca.crt
|
||||
BAO_AUTH_METHOD: cert
|
||||
BAO_CERT_ROLE: messenger-worker
|
||||
BAO_AUTH_ROLE: messenger-worker
|
||||
BAO_SECRET_PATH: secret/data/messenger/worker
|
||||
BAO_REFRESH_INTERVAL_MS: '${BAO_REFRESH_INTERVAL_MS:-15000}'
|
||||
BAO_TIMEOUT_MS: '${BAO_TIMEOUT_MS:-5000}'
|
||||
PG_HOST: postgres
|
||||
PG_PORT: '5432'
|
||||
PG_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
DATABASE_POOL_MAX: '${WORKER_DATABASE_POOL_MAX:-6}'
|
||||
DATABASE_CONNECTION_TIMEOUT_MS: '${DATABASE_CONNECTION_TIMEOUT_MS:-5000}'
|
||||
DATABASE_STATEMENT_TIMEOUT_MS: '${DATABASE_STATEMENT_TIMEOUT_MS:-5000}'
|
||||
DATABASE_IDLE_TX_TIMEOUT_MS: '${DATABASE_IDLE_TX_TIMEOUT_MS:-30000}'
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_CONNECT_TIMEOUT_MS: '${S3_CONNECT_TIMEOUT_MS:-1000}'
|
||||
S3_REQUEST_TIMEOUT_MS: '${S3_REQUEST_TIMEOUT_MS:-15000}'
|
||||
MAX_UPLOAD_BYTES: '${MAX_UPLOAD_BYTES:-10485760}'
|
||||
MAX_IMAGE_PIXELS: '${MAX_IMAGE_PIXELS:-40000000}'
|
||||
VIPS_DISC_THRESHOLD: ${VIPS_DISC_THRESHOLD:-1g}
|
||||
FAULT_INJECTION_ENABLED: ${FAULT_INJECTION_ENABLED:-0}
|
||||
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-30}
|
||||
JOB_RETRY_BASE_MS: ${JOB_RETRY_BASE_MS:-1000}
|
||||
JOB_RETRY_MAX_MS: ${JOB_RETRY_MAX_MS:-30000}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
WORKER_HEALTH_PORT: ${WORKER_HEALTH_PORT:-8081}
|
||||
BROKER_PUBLISH_TIMEOUT_MS: ${BROKER_PUBLISH_TIMEOUT_MS:-5000}
|
||||
QUEUED_RECONCILE_GRACE_SECONDS: ${QUEUED_RECONCILE_GRACE_SECONDS:-15}
|
||||
OUTBOX_RETENTION_SECONDS: ${OUTBOX_RETENTION_SECONDS:-86400}
|
||||
JOB_EVENTS_RETENTION_SECONDS: ${JOB_EVENTS_RETENTION_SECONDS:-2592000}
|
||||
# lab6: телеметрия. Collector НЕ в depends_on: приложение обязано
|
||||
# стартовать и работать без телеметрии.
|
||||
BROKER_HOST: broker
|
||||
BROKER_PORT: '5671'
|
||||
BROKER_VHOST: messenger
|
||||
BROKER_ROLE: consumer
|
||||
BROKER_AUTH_MECHANISM: external
|
||||
BROKER_PASSIVE_TOPOLOGY: 'true'
|
||||
BROKER_DELIVERY_LIMIT: '${BROKER_DELIVERY_LIMIT:-10}'
|
||||
BROKER_PUBLISH_TIMEOUT_MS: '${BROKER_PUBLISH_TIMEOUT_MS:-5000}'
|
||||
FAULT_INJECTION_ENABLED: '${FAULT_INJECTION_ENABLED:-0}'
|
||||
WORKER_CONCURRENCY: '${WORKER_CONCURRENCY:-2}'
|
||||
JOB_MAX_ATTEMPTS: '${JOB_MAX_ATTEMPTS:-5}'
|
||||
JOB_TIMEOUT_SECONDS: '${JOB_TIMEOUT_SECONDS:-60}'
|
||||
JOB_LEASE_SECONDS: '${JOB_LEASE_SECONDS:-30}'
|
||||
JOB_RETRY_BASE_MS: '${JOB_RETRY_BASE_MS:-1000}'
|
||||
JOB_RETRY_MAX_MS: '${JOB_RETRY_MAX_MS:-30000}'
|
||||
PIPELINE_VERSION: '${PIPELINE_VERSION:-1}'
|
||||
LEASE_REAPER_INTERVAL_MS: '${LEASE_REAPER_INTERVAL_MS:-2000}'
|
||||
STAGING_CLEANUP_INTERVAL_MS: '${STAGING_CLEANUP_INTERVAL_MS:-60000}'
|
||||
STAGING_RETENTION_SECONDS: '${STAGING_RETENTION_SECONDS:-86400}'
|
||||
WORKER_HEALTH_PORT: '${WORKER_HEALTH_PORT:-8081}'
|
||||
QUEUED_RECONCILE_GRACE_SECONDS: '${QUEUED_RECONCILE_GRACE_SECONDS:-15}'
|
||||
OUTBOX_RETENTION_SECONDS: '${OUTBOX_RETENTION_SECONDS:-86400}'
|
||||
JOB_EVENTS_RETENTION_SECONDS: '${JOB_EVENTS_RETENTION_SECONDS:-2592000}'
|
||||
OTEL_SERVICE_NAME: messenger-worker
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-https://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/certs/ca.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/certs/client.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/certs/client.key
|
||||
OTEL_SDK_DISABLED: '${OTEL_SDK_DISABLED:-false}'
|
||||
OTEL_TRACES_SAMPLER_ARG: '${OTEL_TRACES_SAMPLER_ARG:-1}'
|
||||
OTEL_METRIC_EXPORT_INTERVAL: '${OTEL_METRIC_EXPORT_INTERVAL:-10000}'
|
||||
@@ -335,17 +566,15 @@ services:
|
||||
OTEL_BLRP_MAX_QUEUE_SIZE: '${OTEL_BLRP_MAX_QUEUE_SIZE:-2048}'
|
||||
OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: '${OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:-512}'
|
||||
OTEL_BLRP_SCHEDULE_DELAY: '${OTEL_BLRP_SCHEDULE_DELAY:-1000}'
|
||||
# Недоступный otel-collector: getaddrinfo по неизвестному имени в сети
|
||||
# Docker занимает поток libuv на секунды и без запаса голодают DNS-
|
||||
# запросы к postgres/s3 (проверено: 5-7 с на ENOTFOUND).
|
||||
UV_THREADPOOL_SIZE: '32'
|
||||
dns_opt: ['timeout:1', 'attempts:1']
|
||||
secrets:
|
||||
- s3_worker_access_key_id
|
||||
- s3_worker_secret_access_key
|
||||
- broker_worker_url
|
||||
volumes:
|
||||
- ./secrets/pki/worker:/run/certs:ro
|
||||
networks: [app_data]
|
||||
read_only: true
|
||||
tmpfs: ['/tmp:size=16m']
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
|
||||
deploy:
|
||||
replicas: ${WORKER_REPLICAS:-1}
|
||||
resources:
|
||||
@@ -356,18 +585,17 @@ services:
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
migrate: { condition: service_completed_successfully }
|
||||
openbao: { condition: service_healthy }
|
||||
postgres: { condition: service_healthy }
|
||||
redis: { condition: service_healthy }
|
||||
s3: { condition: service_healthy }
|
||||
broker: { condition: service_healthy }
|
||||
broker-init: { condition: service_completed_successfully }
|
||||
s3-init: { condition: service_completed_successfully }
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
'CMD',
|
||||
'node',
|
||||
'-e',
|
||||
"fetch('http://127.0.0.1:'+ (process.env.WORKER_HEALTH_PORT||8081) + '/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))",
|
||||
"fetch('http://127.0.0.1:' + (process.env.WORKER_HEALTH_PORT || 8081) + '/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))",
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
@@ -375,14 +603,34 @@ services:
|
||||
start_period: 20s
|
||||
|
||||
haproxy:
|
||||
# PROMEX (USE_PROMEX=1) проверен `haproxy -vv`; digest закреплён.
|
||||
image: haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122
|
||||
user: '99:99'
|
||||
command:
|
||||
[
|
||||
'haproxy',
|
||||
'-W',
|
||||
'-db',
|
||||
'-f',
|
||||
'/usr/local/etc/haproxy/haproxy.cfg',
|
||||
'-f',
|
||||
'/run/secrets/haproxy_stats_auth.cfg',
|
||||
]
|
||||
ports:
|
||||
- '${APP_PUBLIC_PORT:-8080}:8080'
|
||||
# Страница статистики — интерфейс LB, публикуется только на loopback.
|
||||
- '${APP_PUBLIC_PORT:-8443}:8443'
|
||||
- '127.0.0.1:${LB_STATS_PORT:-8404}:8404'
|
||||
secrets:
|
||||
- source: haproxy_stats_auth
|
||||
target: /run/secrets/haproxy_stats_auth.cfg
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./secrets/pki/haproxy:/run/certs:ro
|
||||
networks: [public_edge, lb_api, obs_net]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs:
|
||||
- '/tmp:size=8m,noexec,nosuid,nodev'
|
||||
- '/var/run:size=4m,noexec,nosuid,nodev'
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -390,36 +638,52 @@ services:
|
||||
memory: ${LB_MEMORY:-128m}
|
||||
depends_on:
|
||||
api: { condition: service_healthy }
|
||||
restart: unless-stopped
|
||||
|
||||
# --- lab6: наблюдаемость. Приложение от этих сервисов не зависит. ---
|
||||
# --- Observability (isolated obs_net; mTLS everywhere) ---
|
||||
|
||||
# One-shot: владельцы томов Loki/Tempo (UID 10001) без предположений о
|
||||
# наличии shell/chown в их образах. Использует уже собранный образ приложения.
|
||||
obs-volumes-init:
|
||||
image: ${API_IMAGE:-mtusi-messenger:lab7}
|
||||
pull_policy: never
|
||||
user: '0:0'
|
||||
entrypoint: ['node']
|
||||
command:
|
||||
[
|
||||
'-e',
|
||||
"const fs=require('node:fs');for(const p of ['/var/tempo','/loki']){fs.mkdirSync(p,{recursive:true});fs.chownSync(p,10001,10001)}",
|
||||
]
|
||||
# Closed loopback mTLS gateway owning DNS alias `otel-collector`.
|
||||
otel-gateway:
|
||||
image: haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122
|
||||
user: '99:99'
|
||||
command: ['haproxy', '-W', '-db', '-f', '/usr/local/etc/haproxy/gateway.cfg']
|
||||
volumes:
|
||||
- tempo-data:/var/tempo
|
||||
- loki-data:/loki
|
||||
restart: 'no'
|
||||
- ./infra/otel/gateway.cfg:/usr/local/etc/haproxy/gateway.cfg:ro
|
||||
- ./secrets/pki/otel-gateway:/run/certs:ro
|
||||
networks:
|
||||
app_data:
|
||||
aliases: [otel-collector]
|
||||
obs_net:
|
||||
aliases: [otel-collector]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs:
|
||||
- '/tmp:size=8m,noexec,nosuid,nodev'
|
||||
- '/var/run:size=4m,noexec,nosuid,nodev'
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.25'
|
||||
memory: 128m
|
||||
cpus: '${OTELGW_CPUS:-0.25}'
|
||||
memory: ${OTELGW_MEMORY:-64m}
|
||||
restart: unless-stopped
|
||||
|
||||
# Shares otel-gateway netns and binds strictly to 127.0.0.1 (zero external bypass).
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.128.0@sha256:1ab0baba0ee3695d823c46653d8a6e8894896e668ce8bd7ebe002e948d827bc7
|
||||
user: '10001:10001'
|
||||
network_mode: 'service:otel-gateway'
|
||||
command: ['--config=/etc/otelcol-contrib/config.yaml']
|
||||
secrets: [otel_prometheus_password]
|
||||
volumes:
|
||||
- ./infra/otel/collector.yaml:/etc/otelcol-contrib/config.yaml:ro
|
||||
- ./secrets/pki/otel-collector:/run/certs:ro
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
|
||||
depends_on:
|
||||
otel-gateway: { condition: service_started }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -429,19 +693,33 @@ services:
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.4.1@sha256:9abc6cf6aea7710d163dbb28d8eeb7dc5baef01e38fa4cd146a406dd9f07f70d
|
||||
user: '65534:65534'
|
||||
command:
|
||||
[
|
||||
'--config.file=/etc/prometheus/prometheus.yml',
|
||||
'--web.config.file=/run/secrets/prometheus_web.yml',
|
||||
'--storage.tsdb.path=/prometheus',
|
||||
'--storage.tsdb.retention.time=7d',
|
||||
'--web.enable-otlp-receiver',
|
||||
]
|
||||
ports:
|
||||
- '127.0.0.1:${PROMETHEUS_PORT:-9090}:9090'
|
||||
secrets:
|
||||
- source: prometheus_web_yml
|
||||
target: /run/secrets/prometheus_web.yml
|
||||
- prometheus_self_password
|
||||
volumes:
|
||||
- ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||
- ./infra/prometheus/rules:/etc/prometheus/rules:ro
|
||||
- ./secrets/pki/prometheus:/run/certs:ro
|
||||
- prometheus-data:/prometheus
|
||||
networks: [public_edge, obs_net]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
|
||||
depends_on:
|
||||
volumes-init: { condition: service_completed_successfully }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -451,12 +729,19 @@ services:
|
||||
|
||||
loki:
|
||||
image: grafana/loki:3.5.1@sha256:a74594532eec4cc313401beedc4dd2708c43674c032084b1aeb87c14a5be1745
|
||||
user: '10001:10001'
|
||||
command: ['-config.file=/etc/loki/loki.yaml']
|
||||
volumes:
|
||||
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
|
||||
- ./secrets/pki/loki:/run/certs:ro
|
||||
- loki-data:/loki
|
||||
networks: [obs_net]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
|
||||
depends_on:
|
||||
obs-volumes-init: { condition: service_completed_successfully }
|
||||
volumes-init: { condition: service_completed_successfully }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -466,12 +751,19 @@ services:
|
||||
|
||||
tempo:
|
||||
image: grafana/tempo:2.8.1@sha256:bc9245fe3da4e63dc4c6862d9c2dad9bcd8be13d0ba4f7705fa6acda4c904d0e
|
||||
user: '10001:10001'
|
||||
command: ['-config.file=/etc/tempo/tempo.yaml']
|
||||
volumes:
|
||||
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||
- ./secrets/pki/tempo:/run/certs:ro
|
||||
- tempo-data:/var/tempo
|
||||
networks: [obs_net]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
|
||||
depends_on:
|
||||
obs-volumes-init: { condition: service_completed_successfully }
|
||||
volumes-init: { condition: service_completed_successfully }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -481,7 +773,13 @@ services:
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:12.0.2@sha256:b5b59bfc7561634c2d7b136c4543d702ebcc94a3da477f21ff26f89ffd4214fa
|
||||
user: '472:0'
|
||||
environment:
|
||||
GF_SERVER_PROTOCOL: https
|
||||
GF_SERVER_CERT_FILE: /run/certs/server.crt
|
||||
GF_SERVER_CERT_KEY: /run/certs/server.key
|
||||
GF_PATHS_LOGS: /tmp/grafana-logs
|
||||
GF_LOG_MODE: console
|
||||
GF_SECURITY_ADMIN_USER: admin
|
||||
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password
|
||||
GF_AUTH_ANONYMOUS_ENABLED: 'false'
|
||||
@@ -489,17 +787,24 @@ services:
|
||||
GF_ANALYTICS_REPORTING_ENABLED: 'false'
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES: 'false'
|
||||
GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: 'false'
|
||||
secrets: [grafana_admin_password]
|
||||
secrets: [grafana_admin_password, grafana_prometheus_password]
|
||||
ports:
|
||||
- '127.0.0.1:${GRAFANA_PORT:-3000}:3000'
|
||||
volumes:
|
||||
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./infra/grafana/dashboards:/etc/grafana/dashboards:ro
|
||||
- ./secrets/pki/grafana:/run/certs:ro
|
||||
- grafana-data:/var/lib/grafana
|
||||
networks: [public_edge, obs_net]
|
||||
read_only: true
|
||||
cap_drop: ['ALL']
|
||||
security_opt: ['no-new-privileges:true']
|
||||
tmpfs: ['/tmp:size=16m,noexec,nosuid,nodev']
|
||||
depends_on:
|
||||
- prometheus
|
||||
- loki
|
||||
- tempo
|
||||
volumes-init: { condition: service_completed_successfully }
|
||||
prometheus: { condition: service_started }
|
||||
loki: { condition: service_started }
|
||||
tempo: { condition: service_started }
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -507,24 +812,26 @@ services:
|
||||
memory: ${GRAFANA_MEMORY:-384m}
|
||||
restart: unless-stopped
|
||||
|
||||
# Infra-only bootstrap credentials (NEVER mounted into api, worker, or migrate).
|
||||
secrets:
|
||||
minio_root_user: { file: ./secrets/minio_root_user }
|
||||
minio_root_password: { file: ./secrets/minio_root_password }
|
||||
s3_api_access_key_id: { file: ./secrets/s3_api_access_key_id }
|
||||
s3_api_secret_access_key: { file: ./secrets/s3_api_secret_access_key }
|
||||
s3_worker_access_key_id: { file: ./secrets/s3_worker_access_key_id }
|
||||
s3_worker_secret_access_key: { file: ./secrets/s3_worker_secret_access_key }
|
||||
broker_url: { file: ./secrets/broker_url }
|
||||
broker_worker_url: { file: ./secrets/broker_worker_url }
|
||||
broker_worker_password: { file: ./secrets/broker_worker_password }
|
||||
rabbitmq_conf: { file: ./secrets/rabbitmq.conf }
|
||||
grafana_admin_password: { file: ./secrets/grafana_admin_password }
|
||||
postgres_superuser_password: { file: ./secrets/infra/postgres_superuser_password }
|
||||
minio_root_user: { file: ./secrets/infra/minio_root_user }
|
||||
minio_root_password: { file: ./secrets/infra/minio_root_password }
|
||||
redis_admin_password: { file: ./secrets/infra/redis_admin_password }
|
||||
redis_health_password: { file: ./secrets/infra/redis_health_password }
|
||||
grafana_admin_password: { file: ./secrets/infra/grafana_admin_password }
|
||||
grafana_prometheus_password: { file: ./secrets/infra/grafana_prometheus_password }
|
||||
otel_prometheus_password: { file: ./secrets/infra/otel_prometheus_password }
|
||||
prometheus_web_yml: { file: ./secrets/infra/prometheus_web.yml }
|
||||
prometheus_self_password: { file: ./secrets/infra/prometheus_self_password }
|
||||
haproxy_stats_auth: { file: ./secrets/infra/haproxy_stats_auth.cfg }
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
redis-data:
|
||||
s3-data:
|
||||
broker-data:
|
||||
openbao-data:
|
||||
prometheus-data:
|
||||
loki-data:
|
||||
tempo-data:
|
||||
|
||||
@@ -6,15 +6,15 @@ SLI: 5xx / все бизнес-запросы API (маршруты `/health*`,
|
||||
## Источник сигнала
|
||||
Histogram `http_server_request_duration_seconds_count{job="messenger-api"}` (OTLP, обе реплики); правила — `infra/prometheus/rules/recording.yml`.
|
||||
|
||||
## Диагностика (Grafana: «Messenger: API и worker»)
|
||||
## Диагностика (Grafana `https://localhost:3000`: «Messenger: API и worker»)
|
||||
1. **Какие маршруты и коды.** Панель «RPS по маршруту и классу статуса»: 5xx на одном маршруте или на всех.
|
||||
2. **Балансировщик или приложение.** `sum(rate(haproxy_backend_http_responses_total{proxy="api",code="5xx"}[1m]))` против 5xx API. 503 от HAProxy без 5xx API — нет готовых реплик (`haproxy_backend_active_servers{proxy="api"}`, `/health/ready`).
|
||||
3. **БД.** `histogram_quantile(0.95, sum by (le, db_operation_name)(rate(db_client_operation_duration_seconds_bucket[1m])))`, пул: `db_client_connection_count` (used/idle), `db_client_connection_pending_requests`, wait p95. Рост длительности операций с `error_type` и 5xx — БД (блокировка, недоступность). Откройте трассу 5xx-запроса (Loki: `{service_name="messenger-api"} |= "5"` → поле TraceID): время ушло в CLIENT-span БД.
|
||||
2. **Балансировщик или приложение.** `sum(rate(haproxy_backend_http_responses_total{proxy="api",code="5xx"}[1m]))` против 5xx API. 503 от HAProxy без 5xx API — нет готовых реплик (`haproxy_backend_active_servers{proxy="api"}`, `/health/ready` по mTLS `haproxy -> api:8443`).
|
||||
3. **БД.** `histogram_quantile(0.95, sum by (le, db_operation_name)(rate(db_client_operation_duration_seconds_bucket[1m])))`, пул: `db_client_connection_count` (used/idle), `db_client_connection_pending_requests`, wait p95. Рост длительности операций с `error_type` и 5xx — БД (блокировка, недоступность, ошибка TLS/ротации). Откройте трассу 5xx-запроса (Loki: `{service_name="messenger-api"} |= "5"` → поле TraceID): время ушло в CLIENT-span БД.
|
||||
4. **Handler.** Если SERVER-span длиннее суммы DB-span, а операции БД быстрые — задержка в коде handler (разрыв между дочерними span-ами).
|
||||
5. **S3/Redis/брокер.** Логи `ObjectStorage`, `OutboxRelay` (WARN) и span-ы ошибок; `rabbitmq_queue_messages_unacked`.
|
||||
5. **S3/Redis/брокер/OpenBao.** Логи `ObjectStorage`, `OutboxRelay`, `OpenBao` (WARN) и span-ы ошибок; `rabbitmq_queue_messages_unacked`; статус OpenBao (`https://localhost:8200/v1/sys/seal-status`).
|
||||
|
||||
## Действие
|
||||
Устранить причину: снять блокировку/вернуть БД (`pg_stat_activity`, `pg_locks`), вернуть недоступную реплику (`scripts/start-replica.sh`), восстановить S3/Redis. Перезапуск реплик — только после выяснения причины.
|
||||
Устранить причину: снять блокировку/вернуть БД (`docker compose exec -T postgres psql -h /var/run/postgresql -U postgres -d messenger`), распечатать OpenBao при необходимости (`make unseal`), вернуть недоступную реплику (`scripts/start-replica.sh`), восстановить S3/Redis. Перезапуск реплик — только после выяснения причины.
|
||||
|
||||
## Критерий восстановления
|
||||
`messenger:api_errors:rate1m` близок к 0 и alert перешёл в resolved; `messenger:api_availability:ratio5m` возвращается ≥ 0.995 (окно 5m даёт запаздывание); очередь задач разобрана (`messenger_jobs_queue_depth` → 0).
|
||||
|
||||
@@ -14,7 +14,7 @@ Gauge публикуют обе API-реплики из одного snapshot Po
|
||||
5. **Backoff.** Состояние `delayed` > 0 при `retry` — ожидание повторной попытки, смотрите причину ретраев.
|
||||
|
||||
## Действие
|
||||
Вернуть остановленный worker (`docker compose --env-file .env up -d worker`), восстановить S3/БД/брокер; для зависших задач — `jobs.cli status <attachment_id>` / `replay` по документации lab5. Не очищайте очередь вручную.
|
||||
Вернуть остановленный worker (`docker compose --env-file .env up -d --no-build --no-deps --wait worker`), при инциденте компрометации выполнить `./scripts/revoke-worker.sh`, восстановить S3/БД/брокер или распечатать OpenBao (`make unseal`); для зависших задач — `jobs.cli status <attachment_id>` / `replay` по документации lab5. Не очищайте очередь вручную.
|
||||
|
||||
## Критерий восстановления
|
||||
`messenger_jobs_queue_oldest_age_seconds` падает ниже 30 с и далее к 0, `messenger_jobs_queue_depth{state=~"ready|delayed|processing"}` → 0, `messenger_outbox_pending` → 0, alert resolved; принятые вложения стали `ready`.
|
||||
|
||||
+31
-37
@@ -1,42 +1,36 @@
|
||||
# Инфраструктура студента
|
||||
# Инфраструктура стенда (Lab 7 — Grade 5, Track 1)
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
Основная топология описана в корневом `compose.yaml`. Стенд разделён на четыре сети (`public_edge`, `lb_api` internal, `app_data` internal, `obs_net` internal); наружу публикуется только HTTPS-вход `:8443`, а административные интерфейсы (`8404`, `8200`, `9000`, `9090`, `3000`) привязаны строго к `127.0.0.1`. Plaintext-порты `:8080`, `postgres:5432`, `redis:6379` и `broker:5672` отключены и не публикуются.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
## Роли и сервисы
|
||||
|
||||
## Роли (база lab6)
|
||||
| Роль | Service | Образ (pinned) | UID:GID | Сети | Готовность | Volume | Учётные данные / TLS |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| Volume init | `volumes-init` | `node:25.7.0-slim@sha256:e07427bc...` | `0:0` *(one-shot, `CHOWN,FOWNER`)* | — | exit 0 | все named volumes | Одноразовая инициализация владельцев томов |
|
||||
| KMS / Secrets | `openbao` | `ghcr.io/openbao/openbao:2.4.4@sha256:595c83b4...` | `100:1000` | `public_edge`, `app_data` | `bao status` по HTTPS `:8200` | `openbao-data` | Non-dev Raft, TLS `:8200`, `auth/cert`, unseal-ключи в `$LAB7_OPERATOR_DIR/openbao/` |
|
||||
| PostgreSQL | `postgres` | `postgres:16.4-alpine@sha256:5660c2cb...` | `70:70` | `app_data` | `pg_isready` по Unix-сокету | `postgres-data` | `hostssl` + `scram-sha-256`; роли `messenger_migrator`/`messenger_api`/`messenger_worker` |
|
||||
| Redis | `redis` | `redis:7.4.2-alpine@sha256:02419de7...` | `999:1000` | `app_data` | `redis-cli --tls` (`redis_health`) | `redis-data` | `--port 0 --tls-port 6379 --tls-auth-clients yes`, `user default off`, ACL `messenger_api` |
|
||||
| Broker | `broker` | `rabbitmq:4.1.8-alpine@sha256:153322e3...` | `100:101` | `app_data`, `obs_net` | `rabbitmq-diagnostics check_port_connectivity` | `broker-data` | AMQPS `:5671` mTLS + SASL `EXTERNAL` (CN), Prometheus HTTPS mTLS `:15691`, `definitions.json` без users |
|
||||
| Object storage | `s3` | `minio/minio:RELEASE.2025-09-07T16-13-09Z@sha256:14cea493...` | `1000:1000` | `public_edge`, `app_data` | `curl --cacert https://localhost:9000/minio/health/live` | `s3-data` | HTTPS `--certs-dir`, `MINIO_BROWSER=off`, IAM `messenger-api` / `messenger-worker` из OpenBao |
|
||||
| Migrations | `migrate` | сборка `mtusi-messenger:lab7` | `1000:1000` | `app_data` | exit 0 | — | mTLS `messenger-migrator-g1` -> OpenBao -> PostgreSQL TLS `verify-full` |
|
||||
| API (x2) | `api` | сборка `mtusi-messenger:lab7` | `1000:1000` | `lb_api`, `app_data` | loopback `127.0.0.1:8081/health/ready` | — | Вход mTLS `:8443` (SAN `haproxy-lb`), выход mTLS `messenger-api-g1`, секреты из OpenBao в RAM |
|
||||
| Worker (x1) | `worker` | сборка `mtusi-messenger:lab7` | `1000:1000` | `app_data` | loopback `127.0.0.1:8081/health` | — | Выход mTLS `messenger-worker-g1` (→ `g2`), consumer-only, без доступа к Redis/users/messages |
|
||||
| Load balancer | `haproxy` | `haproxy:3.2-alpine@sha256:254e6370...` | `99:99` | `public_edge`, `lb_api`, `obs_net` | depends on `api` healthy | — | HTTPS `:8443` (`no-tls-tickets`, deny `/internal/*`), mTLS к `api:8443`, `:8404` Basic Auth + mTLS `/metrics` |
|
||||
| OTel Gateway | `otel-gateway` | `haproxy:3.2-alpine@sha256:254e6370...` | `99:99` | `app_data`, `obs_net` (alias `otel-collector`) | TLS `:13133` | — | Закрытый loopback-sidecar: mTLS + CN/SAN allowlist + CRL на `:4318` и `:8888`, live `SIGUSR2` |
|
||||
| OTel Collector | `otel-collector` | `otel/opentelemetry-collector-contrib:0.128.0@sha256:1ab0baba...` | `10001:10001` | `service:otel-gateway` | `127.0.0.1:13134` | — | Слушает строго `127.0.0.1`, экспортирует в Tempo/Loki/Prometheus по mTLS |
|
||||
| Prometheus | `prometheus` | `prom/prometheus:v3.4.1@sha256:9abc6cf6...` | `65534:65534` | `public_edge`, `obs_net` | `https://localhost:9090/-/ready` | `prometheus-data` | HTTPS + mTLS + Basic Auth (`web.yml`), все 6 scrape jobs по HTTPS/mTLS |
|
||||
| Loki | `loki` | `grafana/loki:3.5.1@sha256:a7459453...` | `10001:10001` | `obs_net` | через Grafana mTLS proxy | `loki-data` | Нативный mTLS `:3100` (`RequireAndVerifyClientCert`) |
|
||||
| Tempo | `tempo` | `grafana/tempo:2.8.1@sha256:bc9245fe...` | `10001:10001` | `obs_net` | через Grafana mTLS proxy | `tempo-data` | Нативный mTLS gRPC `:4317` и HTTPS `:3200` |
|
||||
| Grafana | `grafana` | `grafana/grafana:12.0.2@sha256:b5b59bfc...` | `472:0` | `public_edge`, `obs_net` | `https://localhost:3000/api/health` | `grafana-data` | HTTPS `:3000`, `anonymous=false`, datasources по mTLS (`$__file{/run/certs/...}`) |
|
||||
|
||||
| Роль | Service | Образ | Готовность | Volume | Credentials |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| API | `api` | сборка `mtusi-messenger:lab7` | `/health/ready` (PostgreSQL, Redis, S3) | — | `secrets/s3_api_*`, `secrets/broker_url` |
|
||||
| Worker | `worker` | та же сборка, `dist/worker.main.js` | `127.0.0.1:8081/health` (consumer активен) | — | `secrets/s3_worker_*`, `secrets/broker_worker_url` |
|
||||
| Broker | `broker` | `rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e` | `rabbitmq-diagnostics check_port_connectivity` | `broker-data` | `rabbitmq.conf`; `broker-init` — `broker_worker_password` |
|
||||
| PostgreSQL | `postgres` | `postgres:16.4-alpine` | `pg_isready` | `postgres-data` | пароль в `.env` / `DATABASE_URL` |
|
||||
| Redis | `redis` | `redis:7.4.2-alpine` | `redis-cli ping` | `redis-data` | без пароля, только compose-сеть |
|
||||
| Object storage | `s3` | `minio/minio:RELEASE.2025-09-07T16-13-09Z@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e` | `mc ready local` | `s3-data` | root — `secrets/minio_root_*` |
|
||||
| S3 bootstrap | `s3-init` | `minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727` | завершается 0 | — | root + identities API/worker |
|
||||
| Broker bootstrap | `broker-init` | `rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e` | завершается 0 | `broker-data` (ro, cookie) | `broker_worker_password` |
|
||||
| Load balancer | `haproxy` | `haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122` | зависит от `api` healthy | — | — |
|
||||
| OTel Collector | `otel-collector` | `otel/opentelemetry-collector-contrib:0.128.0@sha256:1ab0baba0ee3695d823c46653d8a6e8894896e668ce8bd7ebe002e948d827bc7` | внутренний OTLP 4318 | — | — |
|
||||
| Prometheus | `prometheus` | `prom/prometheus:v3.4.1@sha256:9abc6cf6aea7710d163dbb28d8eeb7dc5baef01e38fa4cd146a406dd9f07f70d` | loopback `:9090` | `prometheus-data` | — |
|
||||
| Loki | `loki` | `grafana/loki:3.5.1@sha256:a74594532eec4cc313401beedc4dd2708c43674c032084b1aeb87c14a5be1745` | внутренний `:3100` | `loki-data` | — |
|
||||
| Tempo | `tempo` | `grafana/tempo:2.8.1@sha256:bc9245fe3da4e63dc4c6862d9c2dad9bcd8be13d0ba4f7705fa6acda4c904d0e` | внутренний `:3200` | `tempo-data` | — |
|
||||
| Grafana | `grafana` | `grafana/grafana:12.0.2@sha256:b5b59bfc7561634c2d7b136c4543d702ebcc94a3da477f21ff26f89ffd4214fa` | loopback `:3000` | `grafana-data` | `secrets/grafana_admin_password` |
|
||||
| Obs volumes init | `obs-volumes-init` | сборка `mtusi-messenger:lab7` | завершается 0 | `tempo-data`, `loki-data` | — |
|
||||
## Операторский bootstrap и жизненный цикл (без пересборки образов)
|
||||
|
||||
Политики MinIO разделены: API пишет/удаляет только `staging/*`, читает
|
||||
`attachments/*` и удаляет только legacy `attachments/*/original`; worker
|
||||
читает/удаляет `staging/*` и читает/пишет `attachments/*` (без удаления).
|
||||
Обе роли получают `s3:ListBucket`. Пароль брокера генерируется один раз в
|
||||
`scripts/init-env.sh` и попадает и в `secrets/broker_url` (amqplib), и в
|
||||
`secrets/rabbitmq.conf` (сам брокер), поэтому URL и конфигурация не расходятся.
|
||||
|
||||
Bootstrap идемпотентен: `scripts/init-env.sh` создаёт `.env` и секреты, `migrate`
|
||||
применяет SQL-миграции, `s3-init` создаёт bucket/политики/пользователей, а
|
||||
producer и consumer объявляют обменники и quorum-очереди при каждом подключении.
|
||||
Одноразовый `broker-init` (образ RabbitMQ, data volume только для cookie)
|
||||
создаёт `messenger-worker` и сужает права `messenger`: API публикует и объявляет
|
||||
топологию, но не читает основную очередь, worker потребляет её. Так схема
|
||||
сходится и на существующем volume, где `default_permissions` уже не применяются.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
1. `make bootstrap` (или пошагово):
|
||||
- `./scripts/init-env.sh` — создаёт несекретный `.env` и infra-only bootstrap-секреты в `./secrets/infra/`.
|
||||
- `./scripts/pki-bootstrap.sh` — создаёт локальный Root CA в `$LAB7_OPERATOR_DIR/pki/` (вне Git, не монтируется в контейнеры), `foreign-ca`/`rogue-client`, операторский сертификат `messenger-operator-g1` и изолированные директории `./secrets/pki/<service>/`.
|
||||
- Запуск хранилищ (`volumes-init openbao postgres redis s3 broker`) и `./scripts/openbao-bootstrap.sh` — `init` (5/3 в `$LAB7_OPERATOR_DIR/openbao/`), `unseal`, `kv-v2`, `auth/cert`, CRL, политики, генерация секретов, настройка PG/Redis/MinIO/RabbitMQ и отзыв initial root token.
|
||||
- `make stand-up` — миграции `001..010`, запуск `api` x2, `worker`, `haproxy` и observability.
|
||||
2. Ручной unseal после рестарта OpenBao: `./scripts/openbao-unseal.sh` (`make unseal`).
|
||||
3. Ротация рабочего секрета без пересборки: `./scripts/rotate-secret.sh api-db` (поддерживаются `api-db`, `api-redis`, `api-s3`, `worker-db`, `worker-s3`, `migrator-db`, `api`, `worker`).
|
||||
4. Ротация leaf-сертификата / отзыв по CRL без пересборки: `./scripts/rotate-cert.sh api --revoke` или `./scripts/rotate-cert.sh --revoke-cert <pem>`.
|
||||
5. Track 1 («Компрометация worker»): `./scripts/revoke-worker.sh` (отзыв `messenger-worker-g1` в OpenBao CRL + accessors, OTel allowlist, RabbitMQ, PG, MinIO, выпуск `messenger-worker-g2` и восстановление без `--build`).
|
||||
|
||||
@@ -5,20 +5,35 @@ datasources:
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
url: https://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
basicAuth: true
|
||||
basicAuthUser: grafana
|
||||
jsonData:
|
||||
manageAlerts: false
|
||||
timeInterval: 10s
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
serverName: prometheus
|
||||
secureJsonData:
|
||||
basicAuthPassword: '$__file{/run/secrets/grafana_prometheus_password}'
|
||||
tlsCACert: '$__file{/run/certs/ca.crt}'
|
||||
tlsClientCert: '$__file{/run/certs/client.crt}'
|
||||
tlsClientKey: '$__file{/run/certs/client.key}'
|
||||
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
url: https://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
serverName: loki
|
||||
derivedFields:
|
||||
# trace_id — structured metadata записи (не текст строки).
|
||||
- name: TraceID
|
||||
@@ -26,14 +41,22 @@ datasources:
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
secureJsonData:
|
||||
tlsCACert: '$__file{/run/certs/ca.crt}'
|
||||
tlsClientCert: '$__file{/run/certs/client.crt}'
|
||||
tlsClientKey: '$__file{/run/certs/client.key}'
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
url: https://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
serverName: tempo
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
tags:
|
||||
@@ -46,3 +69,7 @@ datasources:
|
||||
query: '{$${__tags}} | trace_id="$${__span.traceId}"'
|
||||
nodeGraph:
|
||||
enabled: true
|
||||
secureJsonData:
|
||||
tlsCACert: '$__file{/run/certs/ca.crt}'
|
||||
tlsClientCert: '$__file{/run/certs/client.crt}'
|
||||
tlsClientKey: '$__file{/run/certs/client.key}'
|
||||
|
||||
+30
-27
@@ -1,28 +1,17 @@
|
||||
# HAProxy — единственная точка входа lab4.
|
||||
#
|
||||
# Проверка готовности backend: GET /health/ready — та же ручка, что у
|
||||
# healthcheck контейнера. Реплика, потерявшая обязательную зависимость (свой
|
||||
# путь к общей БД или Redis), исключается из ротации, и трафик уходит на
|
||||
# здоровые; при отказе общей зависимости неготовыми становятся все реплики, и
|
||||
# клиент получает 503 от балансировщика — это честный признак того, что
|
||||
# готовых узлов нет.
|
||||
# Проба с зависимостями ограничена на стороне API: бюджет пробы 400 ms (общий
|
||||
# дедлайн /health/ready, проверка БД — по отдельному соединению, не из общего
|
||||
# пула) меньше timeout check 500 ms, который равен интервалу inter. Обнаружение
|
||||
# отказа (inter 500 ms × fall 2 ≈ 1 s) короче окна дреина API
|
||||
# (DRAIN_DELAY_MS=3000): узел уходит из ротации раньше, чем перестаёт
|
||||
# обслуживать.
|
||||
#
|
||||
# Реплики не перечислены статически: server-template + DNS Docker обновляет
|
||||
# список адресов при масштабировании (init-addr none — стартовать без адресов
|
||||
# и дождаться DNS, а не падать при пустом ответе).
|
||||
# HAProxy 3.2 (lab7): единственная внешняя HTTPS-точка входа (:8443),
|
||||
# обязательный mTLS к API-репликам (api:8443) и loopback HTTPS stats/metrics (:8404).
|
||||
# userlist ops_stats загружается вторым флагом -f /run/secrets/haproxy_stats_auth.cfg.
|
||||
|
||||
global
|
||||
maxconn 8192
|
||||
log stdout format raw local0
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||||
tune.ssl.cachesize 0
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
timeout connect 500ms
|
||||
timeout client 35s
|
||||
@@ -41,23 +30,37 @@ resolvers docker
|
||||
hold nx 500ms
|
||||
hold other 1s
|
||||
|
||||
frontend http
|
||||
bind *:8080
|
||||
frontend https_in
|
||||
bind *:8443 ssl crt /run/certs/server.pem
|
||||
# Внутренние маршруты не публикуются наружу (защита в глубину поверх токена).
|
||||
http-request deny deny_status 404 if { path_beg -i /internal }
|
||||
# Перезаписываем клиентские заголовки прокси для честного rate limit по IP.
|
||||
http-request set-header X-Forwarded-Proto https
|
||||
http-request set-header X-Forwarded-For %[src]
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
|
||||
http-check expect status 200
|
||||
timeout check 500ms
|
||||
default-server check inter 500ms fastinter 250ms downinter 1s fall 2 rise 2 maxconn 200
|
||||
server-template api 1-8 api:8080 resolvers docker init-addr none
|
||||
timeout check 750ms
|
||||
default-server ssl verify required ca-file /run/certs/ca.crt crl-file /run/certs/ca.crl crt /run/certs/client.pem sni str(api) verifyhost api check-ssl check-sni api check inter 500ms fastinter 250ms downinter 1s fall 2 rise 2 maxconn 200
|
||||
server-template api 1-8 api:8443 resolvers docker init-addr none
|
||||
|
||||
listen stats
|
||||
bind *:8404
|
||||
bind *:8404 ssl crt /run/certs/server.pem ca-file /run/certs/ca.crt crl-file /run/certs/ca.crl verify optional
|
||||
acl is_metrics path /metrics
|
||||
acl is_stats path_beg /stats
|
||||
acl prom_cert ssl_c_used ssl_c_verify 0
|
||||
acl prom_cn ssl_c_s_dn(cn) -m str prometheus
|
||||
acl prom_san ssl_c_san -m str DNS:prometheus
|
||||
http-request use-service prometheus-exporter if is_metrics prom_cert prom_cn prom_san
|
||||
http-request deny deny_status 403 if is_metrics
|
||||
acl stats_auth http_auth(ops_stats)
|
||||
http-request auth realm haproxy-stats if is_stats !stats_auth
|
||||
http-request deny deny_status 404 unless is_stats
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 1s
|
||||
stats show-legends
|
||||
# Prometheus-экспортёр HAProxy (PROMEX); scrape: haproxy:8404/metrics.
|
||||
http-request use-service prometheus-exporter if { path /metrics }
|
||||
|
||||
@@ -3,6 +3,11 @@ auth_enabled: false
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
grpc_listen_port: 9096
|
||||
http_tls_config:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
client_ca_file: /run/certs/ca.crt
|
||||
client_auth_type: RequireAndVerifyClientCert
|
||||
|
||||
common:
|
||||
path_prefix: /loki
|
||||
|
||||
+115
-37
@@ -1,58 +1,136 @@
|
||||
#!/bin/sh
|
||||
# Идемпотентная инициализация MinIO: приватный bucket, ограниченная политика и
|
||||
# отдельный пользователь API. Выполняется в контейнере minio/mc.
|
||||
# Идемпотентная инициализация MinIO по HTTPS с проверкой CA (БЕЗ --insecure):
|
||||
# приватный bucket, ужесточённые IAM-политики messenger-api и messenger-worker,
|
||||
# а также создание/привязка IAM-пользователей из stdin (от openbao-bootstrap.sh).
|
||||
# Секреты не печатаются и не пишутся в репозиторий.
|
||||
set -eu
|
||||
|
||||
IFS= read -r root_user < /run/secrets/minio_root_user || [ -n "$root_user" ]
|
||||
IFS= read -r root_password < /run/secrets/minio_root_password || [ -n "$root_password" ]
|
||||
IFS= read -r api_key < /run/secrets/s3_api_access_key_id || [ -n "$api_key" ]
|
||||
IFS= read -r api_secret < /run/secrets/s3_api_secret_access_key || [ -n "$api_secret" ]
|
||||
IFS= read -r worker_key < /run/secrets/s3_worker_access_key_id || [ -n "$worker_key" ]
|
||||
IFS= read -r worker_secret < /run/secrets/s3_worker_secret_access_key || [ -n "$worker_secret" ]
|
||||
bucket="${S3_BUCKET:?}"
|
||||
bucket="${S3_BUCKET:-messenger-attachments}"
|
||||
|
||||
# Опционально принимаем 4 строки из stdin: api_key, api_secret, worker_key, worker_secret.
|
||||
api_key=''
|
||||
api_secret=''
|
||||
worker_key=''
|
||||
worker_secret=''
|
||||
if [ ! -t 0 ]; then
|
||||
IFS= read -r api_key || true
|
||||
IFS= read -r api_secret || true
|
||||
IFS= read -r worker_key || true
|
||||
IFS= read -r worker_secret || true
|
||||
fi
|
||||
|
||||
export HOME=/tmp
|
||||
export MC_CONFIG_DIR=/tmp/.mc
|
||||
export MC_HOST_stand="http://${root_user}:${root_password}@s3:9000"
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
|
||||
export MC_HOST_stand="https://${root_user}:${root_password}@s3:9000"
|
||||
|
||||
mc mb --ignore-existing "stand/$bucket"
|
||||
mc anonymous set none "stand/$bucket"
|
||||
|
||||
# The API owns the staging prefix only: it writes the accepted upload there and
|
||||
# can remove it after the worker commits the result. The final prefix is read
|
||||
# for variant/original downloads and legacy lab4 originals, but never written.
|
||||
printf '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/staging/*"]},{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/attachments/*"]},{"Effect":"Allow","Action":["s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/attachments/*/original"]},{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::%s"],"Condition":{"StringLike":{"s3:prefix":["staging/*","attachments/*"]}}}]}' "$bucket" "$bucket" "$bucket" "$bucket" > /tmp/messenger-api-policy.json
|
||||
|
||||
# The worker reads staging, writes the final original and variants, and removes
|
||||
# staging after a safe commit. It never deletes the final prefix.
|
||||
printf '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/staging/*"]},{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject"],"Resource":["arn:aws:s3:::%s/attachments/*"]},{"Effect":"Allow","Action":["s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/attachments/*/v*/*"]},{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::%s"],"Condition":{"StringLike":{"s3:prefix":["staging/*","attachments/*"]}}}]}' "$bucket" "$bucket" "$bucket" "$bucket" > /tmp/messenger-worker-policy.json
|
||||
|
||||
ensure_user() {
|
||||
name=$1
|
||||
secret=$2
|
||||
if ! mc admin user info stand "$name" >/dev/null 2>&1; then
|
||||
mc admin user add stand "$name" "$secret"
|
||||
fi
|
||||
# API: staging/* RW+D, attachments/* R, attachments/*/original D (legacy sweeper),
|
||||
# ListBucket ограничен префиксами staging/* и attachments/* (нужен для 404 на HEAD).
|
||||
cat > /tmp/messenger-api-policy.json <<EOF
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::${bucket}/staging/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::${bucket}/attachments/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::${bucket}/attachments/*/original"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::${bucket}"],
|
||||
"Condition": {
|
||||
"StringLike": {
|
||||
"s3:prefix": ["staging/*", "attachments/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
# `mc admin policy create` does not overwrite and a policy attached to a user
|
||||
# cannot be removed. Detach, remove and recreate makes the script converge on
|
||||
# the current policy even when the stand volume predates lab5.
|
||||
install_policy() {
|
||||
# Worker (ужесточено для lab7 / Track 1):
|
||||
# - staging/*: только GetObject + DeleteObject (без PutObject — нельзя подделать входной файл)
|
||||
# - attachments/*/original: только GetObject + PutObject (без DeleteObject — нельзя удалить финализированный оригинал)
|
||||
# - attachments/*/v*/*: только PutObject + DeleteObject (варианты и уборка неудачной попытки)
|
||||
# - ListBucket строго на staging/* и attachments/* (root, backups/*, admin/* -> 403 AccessDenied)
|
||||
cat > /tmp/messenger-worker-policy.json <<EOF
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::${bucket}/staging/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject"],
|
||||
"Resource": ["arn:aws:s3:::${bucket}/attachments/*/original"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::${bucket}/attachments/*/v*/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::${bucket}"],
|
||||
"Condition": {
|
||||
"StringLike": {
|
||||
"s3:prefix": ["staging/*", "attachments/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
ensure_policy() {
|
||||
name=$1
|
||||
file=$2
|
||||
user=$3
|
||||
if mc admin policy info stand "$name" >/dev/null 2>&1; then
|
||||
mc admin policy detach stand "$name" --user "$user" >/dev/null 2>&1 || true
|
||||
if ! mc admin policy create stand "$name" "$file" >/dev/null 2>&1; then
|
||||
for u in "$api_key" "$worker_key"; do
|
||||
[ -n "$u" ] && mc admin policy detach stand "$name" --user "$u" >/dev/null 2>&1 || true
|
||||
done
|
||||
mc admin policy remove stand "$name" >/dev/null 2>&1 || true
|
||||
mc admin policy create stand "$name" "$file" >/dev/null
|
||||
fi
|
||||
mc admin policy create stand "$name" "$file"
|
||||
mc admin policy attach stand "$name" --user "$user"
|
||||
}
|
||||
|
||||
ensure_user "$api_key" "$api_secret"
|
||||
ensure_user "$worker_key" "$worker_secret"
|
||||
ensure_user_with_policy() {
|
||||
user=$1
|
||||
secret=$2
|
||||
policy=$3
|
||||
if [ -z "$user" ] || [ -z "$secret" ]; then
|
||||
return 0
|
||||
fi
|
||||
mc admin user add stand "$user" "$secret" >/dev/null
|
||||
mc admin policy attach stand "$policy" --user "$user" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
install_policy messenger-api /tmp/messenger-api-policy.json "$api_key"
|
||||
install_policy messenger-worker /tmp/messenger-worker-policy.json "$worker_key"
|
||||
ensure_policy messenger-api /tmp/messenger-api-policy.json
|
||||
ensure_policy messenger-worker /tmp/messenger-worker-policy.json
|
||||
|
||||
echo "bootstrap ok: bucket=$bucket policies=messenger-api,messenger-worker"
|
||||
ensure_user_with_policy "$api_key" "$api_secret" messenger-api
|
||||
ensure_user_with_policy "$worker_key" "$worker_secret" messenger-worker
|
||||
|
||||
echo "minio bootstrap ok: bucket=$bucket tls=verified policies=messenger-api,messenger-worker"
|
||||
|
||||
+20
-4
@@ -1,7 +1,23 @@
|
||||
# OpenBao — реализовать конфигурацию и политики
|
||||
# OpenBao (Lab 7 — Non-Dev Raft, TLS, `auth/cert`)
|
||||
|
||||
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
|
||||
## Конфигурация и файлы
|
||||
|
||||
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
|
||||
- `infra/openbao/openbao.hcl`: non-dev конфигурация (`ui = false`, `disable_mlock = true`), интегрированное хранилище `storage "raft"` в `/openbao/file` (`openbao-data`), TLS-слушатель `:8200` (`/run/certs/server.{crt,key}`, `tls_min_version = "tls12"`, `tls_disable_client_certs = false`).
|
||||
- `infra/openbao/policies/`:
|
||||
- `api.hcl` (`api-policy`) — только `read` на `secret/data/messenger/api` и `secret/metadata/messenger/api`, `lookup-self`/`renew-self`, явные `deny` на чужие роли, `sys/*` и `auth/cert/*`.
|
||||
- `worker.hcl` (`worker-policy`) — только `read` на `secret/data/messenger/worker` и `metadata`, явные `deny` на `api`, `migrator`, `operator-admin`, `sys/*`, `auth/cert/*`.
|
||||
- `migrator.hcl` (`migrator-policy`) — только `read` на `secret/data/messenger/migrator`.
|
||||
- `operator.hcl` (`operator-policy`) — повседневное управление секретами `messenger/*`, ролями/CRL `auth/cert/*`, выборочным отзывом `auth/token/{accessors,lookup-accessor,revoke-accessor}` и `sys/seal` без root-токена.
|
||||
|
||||
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
|
||||
## Разделение хранения и роли `auth/cert`
|
||||
|
||||
- Shamir unseal shares (5 долей, порог 3) и операторский mTLS-сертификат (`messenger-operator-g1`) хранятся строго вне Git в `${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}` (`0700`/`0600`) и никогда не монтируются в контейнеры.
|
||||
- Initial root token используется однократно в `scripts/openbao-bootstrap.sh` для включения `kv-v2` (`secret/`), `auth/cert`, загрузки политик, ролей и CRL, после чего немедленно отзывается (`auth/token/revoke-self`) и нигде не сохраняется.
|
||||
- Сервисные роли `auth/cert/certs/<role>` (`messenger-api`, `messenger-worker`, `messenger-migrator`) используют `token_no_default_policy = true`, ограниченный TTL (`5m`/`30m`, для migrator `2m`/`5m`), проверку `allowed_common_names`, `allowed_dns_sans` и CRL `auth/cert/crls/lab7-ca`.
|
||||
|
||||
## Операции оператора
|
||||
|
||||
- Первичный bootstrap (идемпотентный): `./scripts/openbao-bootstrap.sh`
|
||||
- Ручной unseal после рестарта/seal: `./scripts/openbao-unseal.sh` (или `make unseal`)
|
||||
- Ротация рабочих секретов без пересборки образов: `./scripts/rotate-secret.sh <api-db|api-redis|api-s3|worker-db|worker-s3|migrator-db|api|worker>`
|
||||
- Отзыв скомпрометированного worker (Track 1): `./scripts/revoke-worker.sh [--no-start]`
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
ui = false
|
||||
disable_mlock = true
|
||||
|
||||
api_addr = "https://openbao:8200"
|
||||
cluster_addr = "https://openbao:8201"
|
||||
|
||||
storage "raft" {
|
||||
path = "/openbao/file"
|
||||
node_id = "openbao-1"
|
||||
}
|
||||
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
cluster_address = "127.0.0.1:8201"
|
||||
tls_disable = false
|
||||
tls_cert_file = "/run/certs/server.crt"
|
||||
tls_key_file = "/run/certs/server.key"
|
||||
tls_min_version = "tls12"
|
||||
tls_disable_client_certs = false
|
||||
tls_require_and_verify_client_cert = false
|
||||
}
|
||||
|
||||
default_lease_ttl = "10m"
|
||||
max_lease_ttl = "1h"
|
||||
@@ -0,0 +1,37 @@
|
||||
# Least-privilege policy for messenger-api (loaded as "api-policy").
|
||||
path "secret/data/messenger/api" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "secret/metadata/messenger/api" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/lookup-self" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/renew-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
|
||||
# Explicit defense-in-depth denies across other roles and control planes.
|
||||
path "secret/data/messenger/worker" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "secret/data/messenger/migrator" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "secret/data/messenger/operator-admin" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "sys/*" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "auth/cert/*" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
# Least-privilege policy for one-shot messenger-migrator (loaded as "migrator-policy").
|
||||
path "secret/data/messenger/migrator" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "secret/metadata/messenger/migrator" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/lookup-self" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/renew-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
|
||||
path "secret/data/messenger/api" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "secret/data/messenger/worker" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "secret/data/messenger/operator-admin" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "sys/*" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "auth/cert/*" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
# Day-to-day operator policy (loaded as "operator-policy", distinct from root).
|
||||
# Includes targeted "sudo" ONLY on operator control-plane paths that OpenBao
|
||||
# marks as sudo-protected (token accessor management, workload policy updates,
|
||||
# and manual sealing). Raw storage and root generation remain denied.
|
||||
path "secret/data/messenger/*" {
|
||||
capabilities = ["create", "read", "update", "delete"]
|
||||
}
|
||||
|
||||
path "secret/metadata/messenger/*" {
|
||||
capabilities = ["list", "read", "delete"]
|
||||
}
|
||||
|
||||
path "auth/cert/certs/*" {
|
||||
capabilities = ["create", "read", "update", "delete", "list"]
|
||||
}
|
||||
|
||||
path "auth/cert/crls/*" {
|
||||
capabilities = ["create", "read", "update", "delete", "list"]
|
||||
}
|
||||
|
||||
path "auth/token/accessors" {
|
||||
capabilities = ["list", "sudo"]
|
||||
}
|
||||
|
||||
path "auth/token/lookup-accessor" {
|
||||
capabilities = ["update", "sudo"]
|
||||
}
|
||||
|
||||
path "auth/token/revoke-accessor" {
|
||||
capabilities = ["update", "sudo"]
|
||||
}
|
||||
|
||||
path "auth/token/lookup-self" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/renew-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
|
||||
path "sys/policies/acl/api-policy" {
|
||||
capabilities = ["create", "read", "update", "sudo"]
|
||||
}
|
||||
|
||||
path "sys/policies/acl/worker-policy" {
|
||||
capabilities = ["create", "read", "update", "sudo"]
|
||||
}
|
||||
|
||||
path "sys/policies/acl/migrator-policy" {
|
||||
capabilities = ["create", "read", "update", "sudo"]
|
||||
}
|
||||
|
||||
path "sys/seal" {
|
||||
capabilities = ["update", "sudo"]
|
||||
}
|
||||
|
||||
path "sys/health" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "sys/raw/*" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
# Least-privilege policy for messenger-worker (loaded as "worker-policy").
|
||||
path "secret/data/messenger/worker" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "secret/metadata/messenger/worker" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/lookup-self" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
|
||||
path "auth/token/renew-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
|
||||
# Explicit defense-in-depth denies across other roles and control planes.
|
||||
path "secret/data/messenger/api" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "secret/data/messenger/migrator" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "secret/data/messenger/operator-admin" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "sys/*" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
|
||||
path "auth/cert/*" {
|
||||
capabilities = ["deny"]
|
||||
}
|
||||
+17
-4
@@ -1,7 +1,20 @@
|
||||
# Конфигурация наблюдаемости — реализовать
|
||||
# Конфигурация наблюдаемости (Lab 7 — mTLS + закрытый `otel-gateway`)
|
||||
|
||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
||||
## Архитектура без plaintext-обходов
|
||||
|
||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
||||
- `otel-gateway` (`haproxy:3.2-alpine`, `user: 99:99`, `read_only: true`, `cap_drop: [ALL]`) владеет сетевым пространством и DNS-алиасом `otel-collector` в `app_data` и `obs_net`.
|
||||
- `:4318` (OTLP HTTP): обязательный mTLS + проверка CRL (`/run/certs/ca.crl`) + списки допустимых `CN` (`/run/certs/allowed-otlp-cn.lst`) и `SAN` (`/run/certs/allowed-otlp-san.lst`, только `DNS:messenger-api` и `DNS:messenger-worker`), `no-tls-tickets`, `tune.ssl.cachesize 0`.
|
||||
- `:8888` (self-metrics): обязательный mTLS + CRL строго для `CN=prometheus`, `SAN=DNS:prometheus`.
|
||||
- `:13133` (health): HTTPS с серверным сертификатом `otel-collector`.
|
||||
- Конфигурация: `infra/otel/gateway.cfg`; живой reload CRL и allowlist-файлов по `SIGUSR2` без пересборки образа.
|
||||
- `otel-collector` (`otel/opentelemetry-collector-contrib:0.128.0`, `network_mode: service:otel-gateway`) слушает исключительно loopback `127.0.0.1` (`:14318`, `:18888`, `:13134`), недоступный извне общего netns.
|
||||
- `processors.memory_limiter` (`limit_mib: 204`, `spike_limit_mib: 40`) и `batch` + `sending_queue` обеспечивают backpressure без роста RSS.
|
||||
- `processors.attributes/scrub` удаляет `Authorization`, `Cookie`, `X-Vault-Token`/`X-Bao-Token`, `password*`, `token*`, `secret_id`, `private_key`, `http.*.body` и `url.full` вторым рубежом поверх redaction приложения.
|
||||
- Экспорт во все 3 хранилища идёт по нативному mTLS (`client.crt`/`client.key`, `CN=otel-collector`): Tempo (`tempo:4317`), Loki (`https://loki:3100/otlp`), Prometheus (`https://prometheus:9090/api/v1/otlp` + Basic Auth из `/run/secrets/otel_prometheus_password`).
|
||||
|
||||
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
|
||||
## Хранилища и Grafana
|
||||
|
||||
- `infra/prometheus/prometheus.yml` + `infra/prometheus/web.yml` (шаблон): HTTPS + `RequireAndVerifyClientCert` + Basic Auth (`operator`, `grafana`, `otel-collector`, `prometheus-self`); все 6 scrape jobs (`prometheus`, `otel-collector`, `haproxy`, `rabbitmq`, `loki`, `tempo`) работают по HTTPS/mTLS.
|
||||
- `infra/loki/loki.yaml`: нативный mTLS на `:3100` (`RequireAndVerifyClientCert`).
|
||||
- `infra/tempo/tempo.yaml`: нативный mTLS на gRPC `:4317` и HTTPS `:3200`.
|
||||
- `infra/grafana/provisioning/datasources/datasources.yaml`: HTTPS/mTLS с `$__file{/run/certs/...}` и `tlsSkipVerify: false`; UI Grafana слушает HTTPS на `127.0.0.1:3000` с выключенным анонимным доступом.
|
||||
|
||||
+52
-13
@@ -1,15 +1,19 @@
|
||||
# OpenTelemetry Collector (contrib 0.128.0): единственная OTLP-точка входа.
|
||||
# traces -> Tempo, metrics -> Prometheus OTLP receiver, logs -> Loki OTLP.
|
||||
# Порт 4318 доступен только внутри compose-сети (наружу не публикуется).
|
||||
# OpenTelemetry Collector (contrib 0.128.0, lab7):
|
||||
# Слушает строго 127.0.0.1 внутри общего netns с otel-gateway (mTLS + CN/SAN + CRL).
|
||||
# Экспорт в Tempo/Loki/Prometheus идёт по нативному mTLS (+ Basic Auth в Prometheus).
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
endpoint: 127.0.0.1:13134
|
||||
basicauth/prometheus:
|
||||
client_auth:
|
||||
username: otel-collector
|
||||
password: ${file:/run/secrets/otel_prometheus_password}
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
endpoint: 127.0.0.1:14318
|
||||
|
||||
processors:
|
||||
# Бэкпрешер: при приближении к лимиту отказывает приёмнику (SDK ретраит/теряет).
|
||||
@@ -18,7 +22,7 @@ processors:
|
||||
check_interval: 1s
|
||||
limit_mib: 204
|
||||
spike_limit_mib: 40
|
||||
# Второй рубеж: секретные атрибуты. Тело лога защищает redaction приложения.
|
||||
# Второй рубеж: удаление секретных атрибутов поверх redaction приложения.
|
||||
attributes/scrub:
|
||||
actions:
|
||||
- { key: authorization, action: delete }
|
||||
@@ -27,9 +31,26 @@ processors:
|
||||
- { key: cookie, action: delete }
|
||||
- { key: Cookie, action: delete }
|
||||
- { key: http.request.header.cookie, action: delete }
|
||||
- { key: x-vault-token, action: delete }
|
||||
- { key: X-Vault-Token, action: delete }
|
||||
- { key: http.request.header.x-vault-token, action: delete }
|
||||
- { key: x-bao-token, action: delete }
|
||||
- { key: X-Bao-Token, action: delete }
|
||||
- { key: http.request.header.x-bao-token, action: delete }
|
||||
- { key: password, action: delete }
|
||||
- { key: password_hash, action: delete }
|
||||
- { key: token, action: delete }
|
||||
- { key: session_token, action: delete }
|
||||
- { key: client_token, action: delete }
|
||||
- { key: metrics_token, action: delete }
|
||||
- { key: secret_id, action: delete }
|
||||
- { key: role_id, action: delete }
|
||||
- { key: wrapping_token, action: delete }
|
||||
- { key: unseal_key, action: delete }
|
||||
- { key: private_key, action: delete }
|
||||
- { key: db_password, action: delete }
|
||||
- { key: redis_password, action: delete }
|
||||
- { key: s3_secret_access_key, action: delete }
|
||||
- { key: http.request.body, action: delete }
|
||||
- { key: http.response.body, action: delete }
|
||||
- { key: url.full, action: delete }
|
||||
@@ -43,7 +64,11 @@ exporters:
|
||||
otlp/tempo:
|
||||
endpoint: tempo:4317
|
||||
tls:
|
||||
insecure: true
|
||||
insecure: false
|
||||
ca_file: /run/certs/ca.crt
|
||||
cert_file: /run/certs/client.crt
|
||||
key_file: /run/certs/client.key
|
||||
server_name_override: tempo
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
@@ -55,7 +80,13 @@ exporters:
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
endpoint: https://loki:3100/otlp
|
||||
tls:
|
||||
insecure: false
|
||||
ca_file: /run/certs/ca.crt
|
||||
cert_file: /run/certs/client.crt
|
||||
key_file: /run/certs/client.key
|
||||
server_name_override: loki
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
@@ -67,8 +98,16 @@ exporters:
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
otlphttp/prometheus:
|
||||
# Prometheus сам обслуживает /api/v1/otlp/v1/metrics.
|
||||
endpoint: http://prometheus:9090/api/v1/otlp
|
||||
# Prometheus обслуживает /api/v1/otlp/v1/metrics по HTTPS + mTLS + Basic Auth.
|
||||
endpoint: https://prometheus:9090/api/v1/otlp
|
||||
auth:
|
||||
authenticator: basicauth/prometheus
|
||||
tls:
|
||||
insecure: false
|
||||
ca_file: /run/certs/ca.crt
|
||||
cert_file: /run/certs/client.crt
|
||||
key_file: /run/certs/client.key
|
||||
server_name_override: prometheus
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
@@ -81,7 +120,7 @@ exporters:
|
||||
max_elapsed_time: 30s
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
extensions: [health_check, basicauth/prometheus]
|
||||
telemetry:
|
||||
metrics:
|
||||
level: detailed
|
||||
@@ -89,8 +128,8 @@ service:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888
|
||||
host: 127.0.0.1
|
||||
port: 18888
|
||||
without_scope_info: true
|
||||
without_units: true
|
||||
without_type_suffix: true
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# HAProxy 3.2 loopback mTLS sidecar for otel-collector (lab7).
|
||||
# Owns Docker DNS alias `otel-collector` on app_data and obs_net; forwards only
|
||||
# to closed loopback ports (127.0.0.1:14318/18888/13134) inside shared netns.
|
||||
# Reloads CRL and CN/SAN allowlists live on SIGUSR2 without image rebuild.
|
||||
|
||||
global
|
||||
maxconn 4096
|
||||
log stdout format raw local0
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||||
tune.ssl.cachesize 0
|
||||
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 30s
|
||||
|
||||
frontend otlp_in
|
||||
bind *:4318 ssl crt /run/certs/server.pem ca-file /run/certs/ca.crt crl-file /run/certs/ca.crl verify required
|
||||
acl ok_cn ssl_c_s_dn(cn) -m str -f /run/certs/allowed-otlp-cn.lst
|
||||
acl ok_san ssl_c_san -m str -f /run/certs/allowed-otlp-san.lst
|
||||
http-request deny deny_status 403 unless ok_cn ok_san
|
||||
default_backend otlp_local
|
||||
|
||||
backend otlp_local
|
||||
server otel_otlp 127.0.0.1:14318
|
||||
|
||||
frontend prom_metrics
|
||||
bind *:8888 ssl crt /run/certs/server.pem ca-file /run/certs/ca.crt crl-file /run/certs/ca.crl verify required
|
||||
acl is_prom_cn ssl_c_s_dn(cn) -m str prometheus
|
||||
acl is_prom_san ssl_c_san -m str DNS:prometheus
|
||||
http-request deny deny_status 403 unless is_prom_cn is_prom_san
|
||||
default_backend prom_local
|
||||
|
||||
backend prom_local
|
||||
server otel_metrics 127.0.0.1:18888
|
||||
|
||||
frontend otel_health
|
||||
bind *:13133 ssl crt /run/certs/server.pem
|
||||
default_backend health_local
|
||||
|
||||
backend health_local
|
||||
server otel_health 127.0.0.1:13134
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Lab 7 least-privilege PostgreSQL roles & schema ownership.
|
||||
-- Executed by postgres superuser on initial initdb (and idempotently re-applied
|
||||
-- by scripts/openbao-bootstrap.sh). Runtime passwords and LOGIN are enabled only
|
||||
-- after OpenBao generates scoped credentials.
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_migrator') THEN
|
||||
CREATE ROLE messenger_migrator NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOLOGIN;
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_api') THEN
|
||||
CREATE ROLE messenger_api NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOLOGIN;
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_worker') THEN
|
||||
CREATE ROLE messenger_worker NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOLOGIN;
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
|
||||
|
||||
ALTER SCHEMA public OWNER TO messenger_migrator;
|
||||
|
||||
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
|
||||
REVOKE ALL ON SCHEMA public FROM PUBLIC;
|
||||
|
||||
GRANT CONNECT ON DATABASE messenger TO messenger_migrator, messenger_api, messenger_worker;
|
||||
GRANT USAGE, CREATE ON SCHEMA public TO messenger_migrator;
|
||||
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker;
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
# Copies read-only mounted TLS material into container-private tmpfs with 0600
|
||||
# key permissions required by PostgreSQL under non-root UID 70:70.
|
||||
set -eu
|
||||
|
||||
cert_dir=/var/run/postgresql/certs
|
||||
mkdir -p "$cert_dir"
|
||||
chmod 0700 "$cert_dir"
|
||||
|
||||
cp /run/certs/ca.crt "$cert_dir/ca.crt"
|
||||
cp /run/certs/ca.crl "$cert_dir/ca.crl"
|
||||
cp /run/certs/server.crt "$cert_dir/server.crt"
|
||||
cp /run/certs/server.key "$cert_dir/server.key"
|
||||
|
||||
chmod 0644 "$cert_dir/ca.crt" "$cert_dir/ca.crl" "$cert_dir/server.crt"
|
||||
chmod 0600 "$cert_dir/server.key"
|
||||
|
||||
exec docker-entrypoint.sh "$@"
|
||||
@@ -0,0 +1,9 @@
|
||||
# Lab 7 PostgreSQL client authentication configuration.
|
||||
# Local Unix socket allowed only for postgres superuser (healthcheck & operator maintenance).
|
||||
local all postgres peer
|
||||
# Mandatory TLS + SCRAM-SHA-256 for all network connections to application DB.
|
||||
hostssl messenger all 0.0.0.0/0 scram-sha-256
|
||||
hostssl messenger all ::/0 scram-sha-256
|
||||
# Reject all plaintext TCP connections explicitly.
|
||||
hostnossl all all 0.0.0.0/0 reject
|
||||
hostnossl all all ::/0 reject
|
||||
@@ -6,7 +6,7 @@ global:
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/*.yml
|
||||
|
||||
# Метрики API/worker приходят только по OTLP (--web.enable-otlp-receiver);
|
||||
# Метрики API/worker приходят только по OTLP (--web.enable-otlp-receiver) по mTLS + Basic Auth.
|
||||
# /internal/metrics — legacy JSON, не exposition-формат, и не скрейпится.
|
||||
otlp:
|
||||
translation_strategy: UnderscoreEscapingWithSuffixes
|
||||
@@ -20,15 +20,59 @@ storage:
|
||||
|
||||
scrape_configs:
|
||||
- job_name: prometheus
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/certs/ca.crt
|
||||
cert_file: /run/certs/client.crt
|
||||
key_file: /run/certs/client.key
|
||||
server_name: localhost
|
||||
basic_auth:
|
||||
username: prometheus-self
|
||||
password_file: /run/secrets/prometheus_self_password
|
||||
static_configs: [{ targets: ['localhost:9090'] }]
|
||||
|
||||
- job_name: otel-collector
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/certs/ca.crt
|
||||
cert_file: /run/certs/client.crt
|
||||
key_file: /run/certs/client.key
|
||||
server_name: otel-collector
|
||||
static_configs: [{ targets: ['otel-collector:8888'] }]
|
||||
|
||||
- job_name: haproxy
|
||||
scheme: https
|
||||
metrics_path: /metrics
|
||||
tls_config:
|
||||
ca_file: /run/certs/ca.crt
|
||||
cert_file: /run/certs/client.crt
|
||||
key_file: /run/certs/client.key
|
||||
server_name: haproxy
|
||||
static_configs: [{ targets: ['haproxy:8404'] }]
|
||||
|
||||
- job_name: rabbitmq
|
||||
static_configs: [{ targets: ['broker:15692'] }]
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/certs/ca.crt
|
||||
cert_file: /run/certs/client.crt
|
||||
key_file: /run/certs/client.key
|
||||
server_name: broker
|
||||
static_configs: [{ targets: ['broker:15691'] }]
|
||||
|
||||
- job_name: loki
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/certs/ca.crt
|
||||
cert_file: /run/certs/client.crt
|
||||
key_file: /run/certs/client.key
|
||||
server_name: loki
|
||||
static_configs: [{ targets: ['loki:3100'] }]
|
||||
|
||||
- job_name: tempo
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/certs/ca.crt
|
||||
cert_file: /run/certs/client.crt
|
||||
key_file: /run/certs/client.key
|
||||
server_name: tempo
|
||||
static_configs: [{ targets: ['tempo:3200'] }]
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Template for Prometheus HTTPS + mTLS + Basic Auth web config (lab7).
|
||||
# scripts/init-env.sh renders ./secrets/infra/prometheus_web.yml with generated
|
||||
# bcrypt hashes for operator, grafana, otel-collector, and prometheus-self.
|
||||
# No real credentials or password hashes are committed to Git.
|
||||
tls_server_config:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
client_ca_file: /run/certs/ca.crt
|
||||
client_auth_type: RequireAndVerifyClientCert
|
||||
min_version: TLS12
|
||||
|
||||
basic_auth_users:
|
||||
operator: __OPERATOR_BCRYPT__
|
||||
grafana: __GRAFANA_BCRYPT__
|
||||
otel-collector: __OTEL_BCRYPT__
|
||||
prometheus-self: __SELF_BCRYPT__
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"rabbit_version": "4.1.8",
|
||||
"vhosts": [
|
||||
{
|
||||
"name": "messenger"
|
||||
}
|
||||
],
|
||||
"exchanges": [
|
||||
{
|
||||
"name": "attachments.dlx",
|
||||
"vhost": "messenger",
|
||||
"type": "fanout",
|
||||
"durable": true,
|
||||
"auto_delete": false,
|
||||
"internal": false,
|
||||
"arguments": {}
|
||||
},
|
||||
{
|
||||
"name": "attachments.jobs",
|
||||
"vhost": "messenger",
|
||||
"type": "direct",
|
||||
"durable": true,
|
||||
"auto_delete": false,
|
||||
"internal": false,
|
||||
"arguments": {}
|
||||
}
|
||||
],
|
||||
"queues": [
|
||||
{
|
||||
"name": "attachments.process.dlq",
|
||||
"vhost": "messenger",
|
||||
"durable": true,
|
||||
"auto_delete": false,
|
||||
"arguments": {
|
||||
"x-queue-type": "quorum"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "attachments.process",
|
||||
"vhost": "messenger",
|
||||
"durable": true,
|
||||
"auto_delete": false,
|
||||
"arguments": {
|
||||
"x-queue-type": "quorum",
|
||||
"x-dead-letter-exchange": "attachments.dlx",
|
||||
"x-delivery-limit": 10
|
||||
}
|
||||
}
|
||||
],
|
||||
"bindings": [
|
||||
{
|
||||
"source": "attachments.dlx",
|
||||
"vhost": "messenger",
|
||||
"destination": "attachments.process.dlq",
|
||||
"destination_type": "queue",
|
||||
"routing_key": "",
|
||||
"arguments": {}
|
||||
},
|
||||
{
|
||||
"source": "attachments.jobs",
|
||||
"vhost": "messenger",
|
||||
"destination": "attachments.process",
|
||||
"destination_type": "queue",
|
||||
"routing_key": "attachment.process.v1",
|
||||
"arguments": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
[rabbitmq_prometheus].
|
||||
[rabbitmq_prometheus,rabbitmq_auth_mechanism_ssl].
|
||||
|
||||
@@ -1,21 +1,41 @@
|
||||
#!/bin/sh
|
||||
# Runs as a one-shot sidecar against rabbit@broker. The broker data volume is
|
||||
# mounted read-only only to share the Erlang cookie; no queue data is modified.
|
||||
# Lab 7 idempotent RabbitMQ EXTERNAL (X.509 CN) user & ACL convergence helper.
|
||||
# Invoked inside the broker container by scripts/openbao-bootstrap.sh.
|
||||
# Passwordless users match exact client certificate CNs:
|
||||
# - API (producer only): configure=^$ write=^attachments\.jobs$ read=^attachments\.jobs$
|
||||
# - Worker (consumer only): configure=^$ write=^$ read=^attachments\.process$
|
||||
set -eu
|
||||
|
||||
password=$(cat /run/secrets/broker_worker_password)
|
||||
configure='^(attachments\.jobs|attachments\.process|attachments\.dlx|attachments\.process\.dlq)$'
|
||||
write='^attachments\.(jobs|process|dlx|process\.dlq)$'
|
||||
all_read='^attachments\.(jobs|process|dlx|process\.dlq)$'
|
||||
api_read='^attachments\.(jobs|dlx)$'
|
||||
api_cn="${1:-messenger-api-g1}"
|
||||
worker_cn="${2:-messenger-worker-g1}"
|
||||
|
||||
if ! rabbitmqctl -n rabbit@broker -p messenger add_user messenger-worker "$password" 2>/dev/null; then
|
||||
rabbitmqctl -n rabbit@broker -q -p messenger change_password messenger-worker "$password"
|
||||
ensure_external_user() {
|
||||
user=$1
|
||||
if ! rabbitmqctl -q list_users | awk '{print $1}' | grep -Fxq "$user"; then
|
||||
# Password is cleared immediately; SASL EXTERNAL authenticates by verified TLS cert CN only.
|
||||
rabbitmqctl -q add_user "$user" "tmp-$(head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \n')"
|
||||
fi
|
||||
rabbitmqctl -q clear_password "$user"
|
||||
rabbitmqctl -q set_user_tags "$user"
|
||||
}
|
||||
|
||||
# Remove default guest user if present so no default credential exists.
|
||||
if rabbitmqctl -q list_users | awk '{print $1}' | grep -Fxq "guest"; then
|
||||
rabbitmqctl -q delete_user guest
|
||||
fi
|
||||
rabbitmqctl -n rabbit@broker -q -p messenger set_permissions messenger-worker \
|
||||
"$configure" "$write" "$all_read"
|
||||
# The API may publish and declare the topology, but must not consume the job
|
||||
# queue. The worker identity is used by the worker process.
|
||||
rabbitmqctl -n rabbit@broker -q -p messenger set_permissions messenger \
|
||||
"$configure" "$write" "$api_read"
|
||||
echo "broker init ok: publisher and consumer identities separated"
|
||||
|
||||
# Ensure vhost exists (also pre-declared in definitions.json).
|
||||
if ! rabbitmqctl -q list_vhosts | grep -Fxq "messenger"; then
|
||||
rabbitmqctl -q add_vhost messenger
|
||||
fi
|
||||
|
||||
ensure_external_user "$api_cn"
|
||||
ensure_external_user "$worker_cn"
|
||||
|
||||
rabbitmqctl -q set_permissions -p messenger "$api_cn" \
|
||||
'^$' '^attachments\.jobs$' '^attachments\.jobs$'
|
||||
|
||||
rabbitmqctl -q set_permissions -p messenger "$worker_cn" \
|
||||
'^$' '^$' '^attachments\.process$'
|
||||
|
||||
echo "broker external ACLs converged: api=${api_cn} worker=${worker_cn}"
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Lab 7 RabbitMQ 4.1.8 configuration:
|
||||
# - Plaintext AMQP (5672) and plaintext Prometheus (15692) disabled.
|
||||
# - Mandatory AMQPS mTLS (5671) + SASL EXTERNAL bound to client cert CN.
|
||||
# - TLS session resumption disabled so revoked identities fail on new connections.
|
||||
# - Durable topology pre-declared in definitions.json (ZERO users in file).
|
||||
|
||||
listeners.tcp = none
|
||||
listeners.ssl.default = 5671
|
||||
|
||||
ssl_options.cacertfile = /run/certs/ca.crt
|
||||
ssl_options.certfile = /run/certs/server.crt
|
||||
ssl_options.keyfile = /run/certs/server.key
|
||||
ssl_options.verify = verify_peer
|
||||
ssl_options.fail_if_no_peer_cert = true
|
||||
ssl_options.versions.1 = tlsv1.3
|
||||
ssl_options.versions.2 = tlsv1.2
|
||||
ssl_options.reuse_sessions = false
|
||||
|
||||
auth_mechanisms.1 = EXTERNAL
|
||||
ssl_cert_login_from = common_name
|
||||
|
||||
definitions.local.path = /etc/rabbitmq/definitions.json
|
||||
|
||||
prometheus.tcp.listener = none
|
||||
prometheus.ssl.port = 15691
|
||||
prometheus.ssl.cacertfile = /run/certs/ca.crt
|
||||
prometheus.ssl.certfile = /run/certs/server.crt
|
||||
prometheus.ssl.keyfile = /run/certs/server.key
|
||||
prometheus.ssl.verify = verify_peer
|
||||
prometheus.ssl.fail_if_no_peer_cert = true
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
# Seeds minimal /data/users.acl on a fresh Redis volume (user default off,
|
||||
# redis_admin, redis_health) without printing secrets, then starts redis-server.
|
||||
# Application ACL user (messenger_api) is converged by scripts/openbao-bootstrap.sh
|
||||
# via live `ACL SETUSER` + `ACL SAVE`.
|
||||
set -eu
|
||||
|
||||
acl_file=/data/users.acl
|
||||
if [ ! -s "$acl_file" ]; then
|
||||
IFS= read -r admin_pass < /run/secrets/redis_admin_password || [ -n "$admin_pass" ]
|
||||
IFS= read -r health_pass < /run/secrets/redis_health_password || [ -n "$health_pass" ]
|
||||
(
|
||||
umask 077
|
||||
tmp="${acl_file}.tmp.$$"
|
||||
{
|
||||
printf 'user default off\n'
|
||||
printf 'user redis_admin on >%s ~* &* +@all\n' "$admin_pass"
|
||||
printf 'user redis_health on >%s -@all +ping +hello +client|setinfo +quit\n' "$health_pass"
|
||||
} > "$tmp"
|
||||
mv "$tmp" "$acl_file"
|
||||
)
|
||||
fi
|
||||
|
||||
exec redis-server "$@"
|
||||
@@ -1,5 +1,10 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
http_tls_config:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
client_ca_file: /run/certs/ca.crt
|
||||
client_auth_type: RequireAndVerifyClientCert
|
||||
|
||||
distributor:
|
||||
receivers:
|
||||
@@ -7,6 +12,10 @@ distributor:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
tls:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
client_ca_file: /run/certs/ca.crt
|
||||
|
||||
compactor:
|
||||
compaction:
|
||||
|
||||
+13
-10
@@ -1,19 +1,22 @@
|
||||
#!/bin/sh
|
||||
# Black-box набор приложения (app/test/*.e2e-spec.ts) против поднятого стенда.
|
||||
# Требует loopback-портов PostgreSQL, Redis и MinIO из compose.yaml.
|
||||
# Black-box набор приложения (app/test/*.e2e-spec.ts) против локального стенда.
|
||||
# В lab7 PostgreSQL и Redis намеренно не публикуются на хост, поэтому для
|
||||
# host-side e2e передайте явные DATABASE_URL и REDIS_URL (или запускайте
|
||||
# unit/contract/lab7 проверки). Секреты в .env отсутствуют.
|
||||
set -eu
|
||||
|
||||
env_file="${COMPOSE_ENV_FILE:-.env}"
|
||||
compose_dir="$(pwd)"
|
||||
# shellcheck disable=SC1090
|
||||
set -a
|
||||
. "./$env_file"
|
||||
set +a
|
||||
if [ -f "./$env_file" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
set -a
|
||||
. "./$env_file"
|
||||
set +a
|
||||
fi
|
||||
|
||||
export API_BASE_URL="${API_BASE_URL:-http://127.0.0.1:${APP_PUBLIC_PORT:-8080}}"
|
||||
export DATABASE_URL="postgresql://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in $env_file}@127.0.0.1:${POSTGRES_PUBLISHED_PORT:-5432}/${POSTGRES_DB:-messenger}"
|
||||
export REDIS_URL="redis://127.0.0.1:${REDIS_PUBLISHED_PORT:-6379}"
|
||||
export E2E_S3_PUBLIC_ENDPOINT="${S3_PUBLIC_ENDPOINT:-http://localhost:9000}"
|
||||
export API_BASE_URL="${API_BASE_URL:-https://localhost:${APP_PUBLIC_PORT:-8443}}"
|
||||
export NODE_EXTRA_CA_CERTS="${NODE_EXTRA_CA_CERTS:-${compose_dir}/secrets/pki/ca.crt}"
|
||||
export E2E_S3_PUBLIC_ENDPOINT="${S3_PUBLIC_ENDPOINT:-https://localhost:${S3_PUBLIC_PORT:-9000}}"
|
||||
export E2E_S3_BUCKET="${S3_BUCKET:-messenger-attachments}"
|
||||
export E2E_COMPOSE_DIR="$compose_dir"
|
||||
export E2E_COMPOSE_ENV_FILE="$env_file"
|
||||
|
||||
+85
-56
@@ -1,77 +1,106 @@
|
||||
#!/bin/sh
|
||||
# Идемпотентно создаёт .env и secrets/* для локального стенда. Значения не печатает.
|
||||
set -eu
|
||||
#!/usr/bin/env bash
|
||||
# Idempotently creates non-secret .env and stateful infra-only bootstrap secrets
|
||||
# under ./secrets/infra/. Never prints secret values and NEVER creates
|
||||
# application credentials (DB/Redis/S3/Broker/Metrics app creds live ONLY in
|
||||
# OpenBao Raft KV v2 and backend auth stores).
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
(
|
||||
umask 077
|
||||
pg=$(openssl rand -hex 24)
|
||||
mt=$(openssl rand -hex 16)
|
||||
sed \
|
||||
-e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${pg}|" \
|
||||
-e "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:${pg}@postgres:5432/messenger|" \
|
||||
-e "s|^METRICS_TOKEN=.*|METRICS_TOKEN=${mt}|" \
|
||||
.env.example > .env
|
||||
)
|
||||
echo "created .env"
|
||||
cp .env.example .env
|
||||
chmod 0644 .env
|
||||
echo "created .env (non-secret topology config only)"
|
||||
else
|
||||
echo "kept .env"
|
||||
fi
|
||||
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
mkdir -p secrets secrets/infra
|
||||
chmod 0700 secrets secrets/infra
|
||||
|
||||
write_secret() {
|
||||
name=$1
|
||||
value=$2
|
||||
if [ -s "secrets/$name" ]; then
|
||||
echo "kept secrets/$name"
|
||||
return
|
||||
# Host isolation is enforced by 0700 on ./secrets and ./secrets/infra; individual
|
||||
# secret files are 0644 so heterogeneous non-root container UIDs (70, 99, 472,
|
||||
# 999, 1000, 10001, 65534) can read only the specific secret mounted to them.
|
||||
write_infra_secret() {
|
||||
local name="$1"
|
||||
local value="$2"
|
||||
local path="secrets/infra/${name}"
|
||||
if [ -s "$path" ]; then
|
||||
echo "kept ${path}"
|
||||
return 0
|
||||
fi
|
||||
(umask 133; printf '%s' "$value" > "secrets/$name")
|
||||
chmod 0644 "secrets/$name"
|
||||
echo "created secrets/$name"
|
||||
local tmp="${path}.tmp.$$"
|
||||
(umask 133; printf '%s' "$value" > "$tmp")
|
||||
chmod 0644 "$tmp"
|
||||
mv -f "$tmp" "$path"
|
||||
echo "created ${path}"
|
||||
}
|
||||
|
||||
write_secret minio_root_user "root-$(openssl rand -hex 6)"
|
||||
write_secret minio_root_password "$(openssl rand -hex 24)"
|
||||
write_secret s3_api_access_key_id "api-$(openssl rand -hex 8)"
|
||||
write_secret s3_api_secret_access_key "$(openssl rand -hex 24)"
|
||||
write_secret s3_worker_access_key_id "worker-$(openssl rand -hex 8)"
|
||||
write_secret s3_worker_secret_access_key "$(openssl rand -hex 24)"
|
||||
write_secret grafana_admin_password "$(openssl rand -hex 24)"
|
||||
bcrypt_hash() {
|
||||
local password="$1"
|
||||
python3 -c '
|
||||
import sys, bcrypt
|
||||
pw = sys.stdin.read().encode("utf-8")
|
||||
print(bcrypt.hashpw(pw, bcrypt.gensalt(rounds=10)).decode("ascii"), end="")
|
||||
' <<< "$password"
|
||||
}
|
||||
|
||||
if [ -s secrets/broker_worker_password ] && [ -s secrets/broker_worker_url ]; then
|
||||
echo "kept secrets/broker_worker_password secrets/broker_worker_url"
|
||||
write_infra_secret postgres_superuser_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret minio_root_user "root-$(openssl rand -hex 6)"
|
||||
write_infra_secret minio_root_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret redis_admin_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret redis_health_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret grafana_admin_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret grafana_prometheus_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret otel_prometheus_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret prometheus_self_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret prometheus_operator_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret haproxy_stats_password "$(openssl rand -hex 24)"
|
||||
|
||||
# Render Prometheus web.yml (HTTPS + mTLS + Basic Auth bcrypt hashes) from template.
|
||||
if [ -s secrets/infra/prometheus_web.yml ]; then
|
||||
echo "kept secrets/infra/prometheus_web.yml"
|
||||
else
|
||||
wp=$(openssl rand -hex 24)
|
||||
(umask 133; printf '%s' "$wp" > secrets/broker_worker_password)
|
||||
chmod 0644 secrets/broker_worker_password
|
||||
(umask 133; printf '%s' "amqp://messenger-worker:${wp}@broker:5672/messenger" > secrets/broker_worker_url)
|
||||
chmod 0644 secrets/broker_worker_url
|
||||
echo "created secrets/broker_worker_password secrets/broker_worker_url"
|
||||
op_hash="$(bcrypt_hash "$(cat secrets/infra/prometheus_operator_password)")"
|
||||
gr_hash="$(bcrypt_hash "$(cat secrets/infra/grafana_prometheus_password)")"
|
||||
ot_hash="$(bcrypt_hash "$(cat secrets/infra/otel_prometheus_password)")"
|
||||
sf_hash="$(bcrypt_hash "$(cat secrets/infra/prometheus_self_password)")"
|
||||
|
||||
tmp="secrets/infra/prometheus_web.yml.tmp.$$"
|
||||
(
|
||||
umask 133
|
||||
python3 - "$op_hash" "$gr_hash" "$ot_hash" "$sf_hash" <<'PY' > "$tmp"
|
||||
import sys
|
||||
from pathlib import Path
|
||||
op_h, gr_h, ot_h, sf_h = sys.argv[1:5]
|
||||
tpl = Path("infra/prometheus/web.yml").read_text(encoding="utf-8")
|
||||
out = (
|
||||
tpl.replace("__OPERATOR_BCRYPT__", op_h)
|
||||
.replace("__GRAFANA_BCRYPT__", gr_h)
|
||||
.replace("__OTEL_BCRYPT__", ot_h)
|
||||
.replace("__SELF_BCRYPT__", sf_h)
|
||||
)
|
||||
sys.stdout.write(out)
|
||||
PY
|
||||
)
|
||||
chmod 0644 "$tmp"
|
||||
mv -f "$tmp" secrets/infra/prometheus_web.yml
|
||||
echo "created secrets/infra/prometheus_web.yml"
|
||||
fi
|
||||
|
||||
# Broker password lives in one place and is rendered into both files, so the
|
||||
# URL used by the app and the RabbitMQ config cannot drift apart.
|
||||
if [ -s secrets/broker_url ] && [ -s secrets/rabbitmq.conf ]; then
|
||||
echo "kept secrets/broker_url secrets/rabbitmq.conf"
|
||||
# Render HAProxy stats Basic Auth userlist fragment (SHA-512 crypt hash).
|
||||
if [ -s secrets/infra/haproxy_stats_auth.cfg ]; then
|
||||
echo "kept secrets/infra/haproxy_stats_auth.cfg"
|
||||
else
|
||||
bp=$(openssl rand -hex 24)
|
||||
(umask 133; printf '%s' "amqp://messenger:${bp}@broker:5672/messenger" > secrets/broker_url)
|
||||
chmod 0644 secrets/broker_url
|
||||
stats_hash="$(openssl passwd -6 -stdin < secrets/infra/haproxy_stats_password)"
|
||||
tmp="secrets/infra/haproxy_stats_auth.cfg.tmp.$$"
|
||||
(
|
||||
umask 133
|
||||
{
|
||||
printf 'default_vhost = messenger\n'
|
||||
printf 'default_user = messenger\n'
|
||||
printf 'default_pass = %s\n' "$bp"
|
||||
printf 'default_permissions.configure = ^(attachments\\.jobs|attachments\\.process|attachments\\.dlx|attachments\\.process\\.dlq)$\n'
|
||||
printf 'default_permissions.read = ^attachments\\.(jobs|process|dlx|process\\.dlq)$\n'
|
||||
printf 'default_permissions.write = ^attachments\\.(jobs|process|dlx|process\\.dlq)$\n'
|
||||
} > secrets/rabbitmq.conf
|
||||
printf 'userlist ops_stats\n'
|
||||
printf ' user operator password %s\n' "$stats_hash"
|
||||
} > "$tmp"
|
||||
)
|
||||
chmod 0644 secrets/rabbitmq.conf
|
||||
echo "created secrets/broker_url secrets/rabbitmq.conf"
|
||||
chmod 0644 "$tmp"
|
||||
mv -f "$tmp" secrets/infra/haproxy_stats_auth.cfg
|
||||
echo "created secrets/infra/haproxy_stats_auth.cfg"
|
||||
fi
|
||||
|
||||
@@ -1,54 +1,97 @@
|
||||
#!/bin/sh
|
||||
# Проверка приватности S3 вне API: анонимный доступ, права отдельных credentials
|
||||
# API, закрытая консоль. Секреты не печатаются.
|
||||
#!/usr/bin/env bash
|
||||
# Проверка приватности S3 вне API (lab7 HTTPS + CA + OpenBao-managed API IAM):
|
||||
# анонимный доступ -> 403, права отдельного API-пользователя из OpenBao,
|
||||
# закрытая консоль :9001. Секреты не печатаются.
|
||||
set -u
|
||||
cd "$(dirname "$0")/../.."
|
||||
env_file="${COMPOSE_ENV_FILE:-.env}"
|
||||
# shellcheck disable=SC1090
|
||||
set -a; . "./$env_file"; set +a
|
||||
endpoint="${S3_PUBLIC_ENDPOINT:-http://localhost:9000}"
|
||||
if [ -f "./$env_file" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
set -a; . "./$env_file"; set +a
|
||||
fi
|
||||
|
||||
endpoint="${S3_PUBLIC_ENDPOINT:-https://localhost:${S3_PUBLIC_PORT:-9000}}"
|
||||
bucket="${S3_BUCKET:-messenger-attachments}"
|
||||
compose="docker compose --env-file $env_file"
|
||||
ca_file="${CA_FILE:-$(pwd)/secrets/pki/ca.crt}"
|
||||
operator_dir="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
bao_addr="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
compose=(docker compose --env-file "$env_file")
|
||||
mc_image="minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727"
|
||||
fail=0
|
||||
|
||||
report() { # status name
|
||||
if [ "$1" = ok ]; then echo "PASS $2"; else echo "FAIL $2"; fail=1; fi
|
||||
}
|
||||
|
||||
key=$($compose exec -T postgres psql -U "${POSTGRES_USER:-messenger}" -d "${POSTGRES_DB:-messenger}" -At \
|
||||
key=$("${compose[@]}" exec -T postgres psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -At \
|
||||
-c "SELECT object_key FROM attachments WHERE status = 'ready' ORDER BY created_at DESC LIMIT 1")
|
||||
if [ -z "$key" ]; then
|
||||
echo "FAIL no ready attachment to check; upload one first (make test)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' "$endpoint/$bucket/$key")
|
||||
[ "$code" = 403 ] && report ok "anonymous GET of a ready object -> 403" || report fail "anonymous GET of a ready object -> $code (want 403)"
|
||||
code=$(curl -s --cacert "$ca_file" -o /dev/null -w '%{http_code}' "$endpoint/$bucket/$key")
|
||||
[ "$code" = 403 ] && report ok "anonymous HTTPS GET of a ready object -> 403" || report fail "anonymous HTTPS GET of a ready object -> $code (want 403)"
|
||||
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' "$endpoint/$bucket/")
|
||||
[ "$code" = 403 ] && report ok "anonymous list of the bucket -> 403" || report fail "anonymous list of the bucket -> $code (want 403)"
|
||||
code=$(curl -s --cacert "$ca_file" -o /dev/null -w '%{http_code}' "$endpoint/$bucket/")
|
||||
[ "$code" = 403 ] && report ok "anonymous HTTPS list of the bucket -> 403" || report fail "anonymous HTTPS list of the bucket -> $code (want 403)"
|
||||
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' -X PUT --data-binary x "$endpoint/$bucket/attachments/anonymous-write")
|
||||
[ "$code" = 403 ] && report ok "anonymous PUT -> 403" || report fail "anonymous PUT -> $code (want 403)"
|
||||
code=$(curl -s --cacert "$ca_file" -o /dev/null -w '%{http_code}' -X PUT --data-binary x "$endpoint/$bucket/attachments/anonymous-write")
|
||||
[ "$code" = 403 ] && report ok "anonymous HTTPS PUT -> 403" || report fail "anonymous HTTPS PUT -> $code (want 403)"
|
||||
|
||||
# Fetch API S3 credentials cleanly via OpenBao operator mTLS auth (zero static app secrets on disk).
|
||||
tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/lab7-s3sec.XXXXXX")"
|
||||
trap 'rm -rf "$tmp_dir"' EXIT
|
||||
op_token="$(curl -fsS --cacert "$ca_file" \
|
||||
--cert "${operator_dir}/operator/operator.crt" \
|
||||
--key "${operator_dir}/operator/operator.key" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${bao_addr}/v1/auth/cert/login" | jq -r '.auth.client_token // empty')"
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$op_token" > "${tmp_dir}/auth.cfg"
|
||||
chmod 0600 "${tmp_dir}/auth.cfg"
|
||||
api_kv="$(curl -fsS --cacert "$ca_file" -K "${tmp_dir}/auth.cfg" \
|
||||
"${bao_addr}/v1/secret/data/messenger/api" | jq -c '.data.data')"
|
||||
curl -fsS --cacert "$ca_file" -K "${tmp_dir}/auth.cfg" -X POST \
|
||||
"${bao_addr}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
|
||||
api_key="$(printf '%s' "$api_kv" | jq -r '.s3_access_key_id')"
|
||||
api_sec="$(printf '%s' "$api_kv" | jq -r '.s3_secret_access_key')"
|
||||
|
||||
s3_cid="$("${compose[@]}" ps -q s3 | head -n 1)"
|
||||
app_data_net="$(docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$s3_cid" \
|
||||
| tr ' ' '\n' | grep '_app_data$' | head -n 1)"
|
||||
|
||||
# The API credentials only, inside a one-off container (secrets come from files).
|
||||
api_mc() {
|
||||
$compose run --rm --no-deps -T --entrypoint /bin/sh s3-init -c '
|
||||
IFS= read -r k < /run/secrets/s3_api_access_key_id
|
||||
IFS= read -r s < /run/secrets/s3_api_secret_access_key
|
||||
export MC_CONFIG_DIR=/tmp/.mc MC_HOST_api="http://$k:$s@s3:9000"
|
||||
exec mc "$@"' sh "$@" >/dev/null 2>&1
|
||||
printf '%s\n%s\n' "$api_key" "$api_sec" \
|
||||
| docker run --rm -i \
|
||||
--network "$app_data_net" \
|
||||
--user 1000:1000 \
|
||||
--read-only --cap-drop ALL --security-opt no-new-privileges:true \
|
||||
--tmpfs /tmp:size=16m,noexec,nosuid,nodev \
|
||||
-v "${ca_file}:/run/certs/ca.crt:ro" \
|
||||
--entrypoint /bin/sh "$mc_image" -c '
|
||||
set -eu
|
||||
IFS= read -r k; IFS= read -r s
|
||||
export HOME=/tmp MC_CONFIG_DIR=/tmp/.mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
export MC_HOST_api="https://${k}:${s}@s3:9000"
|
||||
exec mc "$@"
|
||||
' sh "$@" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
api_mc mb api/forbidden-bucket && report fail "API credentials can create buckets" || report ok "API credentials cannot create buckets"
|
||||
api_mc admin info api && report fail "API credentials can use admin API" || report ok "API credentials cannot use admin API"
|
||||
api_mc stat "api/$bucket/$key" && report ok "API credentials can read attachments/*" || report fail "API credentials cannot read attachments/*"
|
||||
api_mc stat "api/$bucket/outside-prefix" ; rc=$?
|
||||
api_mc cp /etc/hostname "api/$bucket/outside-prefix" && report fail "API credentials can write outside attachments/" || report ok "API credentials cannot write outside attachments/"
|
||||
: "$rc"
|
||||
api_mc stat "api/$bucket/$key" && report ok "API credentials can read attachments/* over HTTPS" || report fail "API credentials cannot read attachments/*"
|
||||
api_mc cp /etc/hostname "api/$bucket/outside-prefix" && report fail "API credentials can write outside staging/" || report ok "API credentials cannot write outside staging/"
|
||||
|
||||
port=$($compose port s3 9001 2>/dev/null || true)
|
||||
port=$("${compose[@]}" port s3 9001 2>/dev/null || true)
|
||||
[ -z "$port" ] && report ok "console port 9001 is not published" || report fail "console port 9001 is published ($port)"
|
||||
if curl -s -o /dev/null --max-time 3 http://localhost:9001; then report fail "console reachable on localhost:9001"; else report ok "console not reachable on localhost:9001"; fi
|
||||
if curl -s -o /dev/null --max-time 3 https://localhost:9001 --cacert "$ca_file"; then
|
||||
report fail "console reachable on localhost:9001"
|
||||
else
|
||||
report ok "console not reachable on localhost:9001"
|
||||
fi
|
||||
|
||||
exit "$fail"
|
||||
|
||||
+15
-3
@@ -58,12 +58,24 @@ def cli(*args, stdin=None):
|
||||
raise Failure('jobs.cli did not return JSON for ' + ' '.join(args))
|
||||
|
||||
|
||||
def redis_admin(*args):
|
||||
"""Run redis-cli as redis_admin over mTLS inside the redis container."""
|
||||
return compose(
|
||||
'exec', '-T', 'redis', 'sh', '-c',
|
||||
'REDISCLI_AUTH="$(cat /run/secrets/redis_admin_password)" '
|
||||
'exec redis-cli --tls --cacert /run/certs/ca.crt '
|
||||
'--cert /run/certs/health.crt --key /run/certs/health.key '
|
||||
'--user redis_admin -h localhost -p 6379 "$@"',
|
||||
'--', *args,
|
||||
)
|
||||
|
||||
|
||||
def set_fault(key, value):
|
||||
compose('exec', '-T', 'redis', 'redis-cli', 'SET', key, value)
|
||||
redis_admin('SET', key, value)
|
||||
|
||||
|
||||
def clear_fault(key):
|
||||
compose('exec', '-T', 'redis', 'redis-cli', 'DEL', key)
|
||||
redis_admin('DEL', key)
|
||||
|
||||
|
||||
def clear_faults():
|
||||
@@ -71,7 +83,7 @@ def clear_faults():
|
||||
"local keys=redis.call('keys',ARGV[1]) "
|
||||
"for i=1,#keys do redis.call('del',keys[i]) end return #keys"
|
||||
)
|
||||
compose('exec', '-T', 'redis', 'redis-cli', 'EVAL', script, '0', 'fault:*')
|
||||
redis_admin('EVAL', script, '0', 'fault:*')
|
||||
|
||||
|
||||
def rabbit_queues():
|
||||
|
||||
@@ -283,7 +283,7 @@ def sequential_uploads(ctx, actor, chat, count, delay):
|
||||
elapsed = (time.monotonic() - started) * 1000
|
||||
consumed = True
|
||||
if delay:
|
||||
out = stand.compose('exec', '-T', 'redis', 'redis-cli', 'GET', key).stdout.strip()
|
||||
out = stand.redis_admin('GET', key).stdout.strip()
|
||||
consumed = out == ''
|
||||
rows.append({'request_id': r['headers']['X-Request-Id'], 'status': r['status'],
|
||||
'elapsed_ms': elapsed, 'consumed': consumed,
|
||||
|
||||
+155
-56
@@ -1,11 +1,13 @@
|
||||
"""Shared lab6 helpers: Prometheus/Loki/Tempo/Grafana client, controlled app
|
||||
environment, SQL table lock, batch drain. Python 3.9+, standard library only."""
|
||||
"""Shared lab6 helpers (updated for lab7 HTTPS/mTLS + Basic Auth + network
|
||||
isolation): Prometheus/Loki/Tempo/Grafana client, controlled app environment,
|
||||
SQL table lock, batch drain. Python 3.9+, standard library only."""
|
||||
import base64
|
||||
import binascii
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -59,25 +61,93 @@ SDK_DEFAULTS = {
|
||||
'LOG_LEVEL': 'INFO',
|
||||
}
|
||||
|
||||
_DEFAULT_CA_FILE = None
|
||||
_PROM_PREFIX = None
|
||||
|
||||
|
||||
def utc_now():
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
|
||||
|
||||
def _operator_dir():
|
||||
env_dir = os.environ.get('LAB7_OPERATOR_DIR')
|
||||
if env_dir:
|
||||
return Path(env_dir)
|
||||
xdg = os.environ.get('XDG_STATE_HOME')
|
||||
base = Path(xdg) if xdg else (Path.home() / '.local/state')
|
||||
return base / 'mtusi-lab7-operator'
|
||||
|
||||
|
||||
def _default_ca_path(ca_file=None):
|
||||
for candidate in (ca_file, _DEFAULT_CA_FILE, os.environ.get('CA_FILE'),
|
||||
str(ROOT / 'secrets/pki/ca.crt')):
|
||||
if candidate and Path(candidate).is_file():
|
||||
return str(candidate)
|
||||
return None
|
||||
|
||||
|
||||
def _is_prometheus_url(url):
|
||||
if _PROM_PREFIX and url.startswith(_PROM_PREFIX):
|
||||
return True
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
return parsed.port == 9090 or parsed.path.startswith('/api/v1/query') or \
|
||||
parsed.path.startswith('/api/v1/series') or \
|
||||
parsed.path.startswith('/api/v1/metadata') or \
|
||||
parsed.path.startswith('/api/v1/label/') or \
|
||||
parsed.path.startswith('/api/v1/rules') or \
|
||||
parsed.path == '/-/ready'
|
||||
|
||||
|
||||
def _prom_basic_auth_header():
|
||||
pw_path = ROOT / 'secrets/infra/prometheus_operator_password'
|
||||
if not pw_path.is_file():
|
||||
return None
|
||||
token = base64.b64encode(b'operator:' + pw_path.read_bytes().strip()).decode()
|
||||
return {'Authorization': 'Basic ' + token}
|
||||
|
||||
|
||||
def _ssl_context_for(url, ca_file=None, use_client_cert=False):
|
||||
if not url.startswith('https://'):
|
||||
return None
|
||||
ca_path = _default_ca_path(ca_file)
|
||||
ctx = ssl.create_default_context(cafile=ca_path)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if use_client_cert:
|
||||
op_dir = _operator_dir() / 'operator'
|
||||
cert = op_dir / 'operator.crt'
|
||||
key = op_dir / 'operator.key'
|
||||
if cert.is_file() and key.is_file():
|
||||
ctx.load_cert_chain(certfile=str(cert), keyfile=str(key))
|
||||
return ctx
|
||||
|
||||
|
||||
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
|
||||
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
_NoRedirect())
|
||||
def _opener_for(url, ca_file=None, use_client_cert=False):
|
||||
handlers = [urllib.request.ProxyHandler({}), _NoRedirect()]
|
||||
ctx = _ssl_context_for(url, ca_file=ca_file, use_client_cert=use_client_cert)
|
||||
if ctx is not None:
|
||||
handlers.append(urllib.request.HTTPSHandler(context=ctx))
|
||||
return urllib.request.build_opener(*handlers)
|
||||
|
||||
|
||||
def http_get(url, headers=None, timeout=HTTP_TIMEOUT):
|
||||
def http_get(url, headers=None, timeout=HTTP_TIMEOUT, ca_file=None,
|
||||
use_client_cert=None):
|
||||
"""GET returning (status, bytes); never prints the URL query/headers."""
|
||||
request = urllib.request.Request(url, headers=headers or {})
|
||||
is_prom = _is_prometheus_url(url)
|
||||
need_mtls = is_prom if use_client_cert is None else bool(use_client_cert)
|
||||
req_headers = dict(headers or {})
|
||||
if is_prom and 'Authorization' not in req_headers:
|
||||
prom_auth = _prom_basic_auth_header()
|
||||
if prom_auth:
|
||||
req_headers.update(prom_auth)
|
||||
request = urllib.request.Request(url, headers=req_headers)
|
||||
opener = _opener_for(url, ca_file=ca_file, use_client_cert=need_mtls)
|
||||
try:
|
||||
with _OPENER.open(request, timeout=timeout) as response:
|
||||
with opener.open(request, timeout=timeout) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
with error:
|
||||
@@ -87,8 +157,10 @@ def http_get(url, headers=None, timeout=HTTP_TIMEOUT):
|
||||
type(exc).__name__ + ')') from None
|
||||
|
||||
|
||||
def http_json(url, headers=None, timeout=HTTP_TIMEOUT, allow=(200,)):
|
||||
status, data = http_get(url, headers, timeout)
|
||||
def http_json(url, headers=None, timeout=HTTP_TIMEOUT, allow=(200,),
|
||||
ca_file=None, use_client_cert=None):
|
||||
status, data = http_get(url, headers, timeout, ca_file=ca_file,
|
||||
use_client_cert=use_client_cert)
|
||||
if status not in allow:
|
||||
raise Failure('GET ' + url.split('?')[0] + ': status ' + str(status))
|
||||
try:
|
||||
@@ -196,25 +268,34 @@ def normalize_trace(document):
|
||||
class ObsClient:
|
||||
def __init__(self, prometheus_url, grafana_url, password_file=None,
|
||||
base_url=None, ca_file=None):
|
||||
global _DEFAULT_CA_FILE, _PROM_PREFIX
|
||||
self.prometheus = prometheus_url.rstrip('/')
|
||||
self.grafana = grafana_url.rstrip('/')
|
||||
self.base_url = base_url
|
||||
self.ca_file = ca_file
|
||||
path = Path(password_file) if password_file else (
|
||||
ROOT / 'secrets/grafana_admin_password')
|
||||
if ca_file:
|
||||
_DEFAULT_CA_FILE = ca_file
|
||||
_PROM_PREFIX = self.prometheus
|
||||
candidates = [Path(password_file)] if password_file else [
|
||||
ROOT / 'secrets/infra/grafana_admin_password',
|
||||
ROOT / 'secrets/grafana_admin_password',
|
||||
]
|
||||
self._auth = None
|
||||
if path.exists():
|
||||
token = base64.b64encode(
|
||||
b'admin:' + path.read_bytes().strip()).decode()
|
||||
self._auth = {'Authorization': 'Basic ' + token}
|
||||
for path in candidates:
|
||||
if path.exists():
|
||||
token = base64.b64encode(
|
||||
b'admin:' + path.read_bytes().strip()).decode()
|
||||
self._auth = {'Authorization': 'Basic ' + token}
|
||||
break
|
||||
|
||||
# -- Prometheus
|
||||
# -- Prometheus (HTTPS + mTLS operator cert + Basic Auth)
|
||||
def prom_query(self, expr, at=None):
|
||||
params = {'query': expr}
|
||||
if at is not None:
|
||||
params['time'] = str(at)
|
||||
_, body = http_json(self.prometheus + '/api/v1/query?' +
|
||||
urllib.parse.urlencode(params))
|
||||
urllib.parse.urlencode(params),
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
if not isinstance(body, dict) or body.get('status') != 'success':
|
||||
raise Failure('Prometheus query failed')
|
||||
return body['data']['result']
|
||||
@@ -229,20 +310,23 @@ class ObsClient:
|
||||
params = {'query': expr, 'start': str(start), 'end': str(end),
|
||||
'step': str(step)}
|
||||
_, body = http_json(self.prometheus + '/api/v1/query_range?' +
|
||||
urllib.parse.urlencode(params))
|
||||
urllib.parse.urlencode(params),
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
if not isinstance(body, dict) or body.get('status') != 'success':
|
||||
raise Failure('Prometheus range query failed')
|
||||
return body['data']['result']
|
||||
|
||||
def prom_names(self):
|
||||
_, body = http_json(self.prometheus + '/api/v1/label/__name__/values')
|
||||
_, body = http_json(self.prometheus + '/api/v1/label/__name__/values',
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
return sorted(body['data'])
|
||||
|
||||
# -- Grafana proxied backends
|
||||
# -- Grafana proxied backends (HTTPS + Basic Auth; Grafana->DS uses mTLS)
|
||||
def _grafana_get(self, path, allow=(200,)):
|
||||
if self._auth is None:
|
||||
raise Failure('Grafana password file is missing')
|
||||
return http_get(self.grafana + path, self._auth)
|
||||
return http_get(self.grafana + path, self._auth,
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
|
||||
def grafana_json(self, path, allow=(200,)):
|
||||
status, data = self._grafana_get(path)
|
||||
@@ -305,7 +389,8 @@ class ObsClient:
|
||||
raise Failure('Grafana password file is missing')
|
||||
status, data = http_get(
|
||||
self.grafana + path,
|
||||
{**self._auth, 'Accept': 'application/json'})
|
||||
{**self._auth, 'Accept': 'application/json'},
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
if status == 200:
|
||||
try:
|
||||
return normalize_trace(json.loads(data))
|
||||
@@ -317,14 +402,22 @@ class ObsClient:
|
||||
return None
|
||||
time.sleep(1)
|
||||
|
||||
# -- closed backends from inside the compose network
|
||||
# -- closed backends from inside the compose network (HTTPS + CA verified)
|
||||
def internal_get(self, service, port, path):
|
||||
script = (
|
||||
"const fs=require('node:fs'),https=require('node:https');"
|
||||
"const [h,p,u]=process.argv.slice(1);"
|
||||
"fetch('http://'+h+':'+p+u,{signal:AbortSignal.timeout(5000)})"
|
||||
".then(async r=>{const b=await r.text();"
|
||||
"console.log(JSON.stringify({status:r.status,body:b.slice(0,1048576)}))})"
|
||||
".catch(e=>{console.log(JSON.stringify({status:0,body:String(e.name)}))})")
|
||||
"const req=https.request({host:h,port:Number(p),path:u,method:'GET',"
|
||||
"ca:fs.readFileSync('/run/certs/ca.crt'),servername:h,"
|
||||
"rejectUnauthorized:true,timeout:5000},res=>{"
|
||||
"let b='';res.setEncoding('utf8');"
|
||||
"res.on('data',c=>{if(b.length<1048576)b+=c});"
|
||||
"res.on('end',()=>console.log(JSON.stringify({status:res.statusCode,body:b})));"
|
||||
"});"
|
||||
"req.on('timeout',()=>req.destroy(new Error('Timeout')));"
|
||||
"req.on('error',e=>console.log(JSON.stringify({status:0,body:String(e.code||e.message)})));"
|
||||
"req.end();"
|
||||
)
|
||||
result = stand.compose('exec', '-T', 'api', 'node', '-e', script,
|
||||
service, str(port), path, check_result=False)
|
||||
try:
|
||||
@@ -342,26 +435,40 @@ class ObsClient:
|
||||
problems = []
|
||||
if self.base_url:
|
||||
try:
|
||||
status, _ = http_get(self.base_url.rstrip('/') + '/health/ready')
|
||||
status, _ = http_get(self.base_url.rstrip('/') + '/health/ready',
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
self._check(problems, 'api-ready', status == 200)
|
||||
except Failure:
|
||||
problems.append('api-ready')
|
||||
probes = (('otel-collector', 13133, '/', 'collector-health'),
|
||||
('loki', 3100, '/ready', 'loki-ready'),
|
||||
('tempo', 3200, '/ready', 'tempo-ready'))
|
||||
for service, port, path, name in probes:
|
||||
try:
|
||||
status, _ = self.internal_get(service, port, path)
|
||||
self._check(problems, name, status == 200)
|
||||
except Failure:
|
||||
problems.append(name)
|
||||
# Collector health over HTTPS from api (same app_data network).
|
||||
try:
|
||||
status, _ = http_get(self.prometheus + '/-/ready')
|
||||
status, _ = self.internal_get('otel-collector', 13133, '/')
|
||||
self._check(problems, 'collector-health', status == 200)
|
||||
except Failure:
|
||||
problems.append('collector-health')
|
||||
# Loki and Tempo live on isolated obs_net; verify via Grafana's mTLS proxy.
|
||||
try:
|
||||
body = self.grafana_json('/api/datasources/uid/loki/health',
|
||||
allow=(200, 400, 404, 500))
|
||||
self._check(problems, 'loki-ready',
|
||||
isinstance(body, dict) and
|
||||
body.get('status', '').upper() == 'OK')
|
||||
except Failure:
|
||||
problems.append('loki-ready')
|
||||
try:
|
||||
status, _ = self._grafana_get('/api/datasources/proxy/uid/tempo/api/echo')
|
||||
self._check(problems, 'tempo-ready', status == 200)
|
||||
except Failure:
|
||||
problems.append('tempo-ready')
|
||||
try:
|
||||
status, _ = http_get(self.prometheus + '/-/ready',
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
self._check(problems, 'prometheus-ready', status == 200)
|
||||
except Failure:
|
||||
problems.append('prometheus-ready')
|
||||
try:
|
||||
status, _ = http_get(self.grafana + '/api/health')
|
||||
status, _ = http_get(self.grafana + '/api/health',
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
self._check(problems, 'grafana-health', status == 200)
|
||||
except Failure:
|
||||
problems.append('grafana-health')
|
||||
@@ -388,8 +495,6 @@ class ObsClient:
|
||||
try:
|
||||
for uid in DATASOURCE_UIDS:
|
||||
if uid == 'tempo':
|
||||
# The Tempo plugin has no health resource; its API echo
|
||||
# through the datasource proxy proves the connection.
|
||||
status, _ = self._grafana_get(
|
||||
'/api/datasources/proxy/uid/tempo/api/echo')
|
||||
self._check(problems, 'datasource:tempo', status == 200)
|
||||
@@ -400,7 +505,8 @@ class ObsClient:
|
||||
self._check(problems, 'datasource:' + uid,
|
||||
isinstance(body, dict) and
|
||||
body.get('status', '').upper() == 'OK')
|
||||
_, rules = http_json(self.prometheus + '/api/v1/rules')
|
||||
_, rules = http_json(self.prometheus + '/api/v1/rules',
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
names = {r['name'] for g in rules['data']['groups']
|
||||
for r in g['rules']}
|
||||
for alert in RULE_ALERTS:
|
||||
@@ -518,8 +624,6 @@ class ObsClient:
|
||||
yield set_overrides
|
||||
finally:
|
||||
if dirty[0]:
|
||||
# Restore the original effective values as controller env so the
|
||||
# recreated containers match what was running before.
|
||||
for key in MUTABLE_KEYS:
|
||||
original = baseline.get(('api', key))
|
||||
if original is not None and key in touched:
|
||||
@@ -542,10 +646,9 @@ class ObsClient:
|
||||
self.wait_ready(app_telemetry=True, provisioning=True,
|
||||
timeout=120)
|
||||
|
||||
# -- foreign faults
|
||||
# -- foreign faults (Redis over mTLS + redis_admin ACL)
|
||||
def foreign_faults(self):
|
||||
result = stand.compose('exec', '-T', 'redis', 'redis-cli', '--scan',
|
||||
'--pattern', 'fault:*')
|
||||
result = stand.redis_admin('--scan', '--pattern', 'fault:*')
|
||||
return sorted(line for line in result.stdout.split() if line)
|
||||
|
||||
def require_no_foreign_faults(self):
|
||||
@@ -558,8 +661,8 @@ class ObsClient:
|
||||
# --------------------------------------------------------------- PostgreSQL
|
||||
|
||||
def psql(sql, timeout=30):
|
||||
script = 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 ' \
|
||||
'-At -F , -c "$SQL"'
|
||||
script = 'psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" ' \
|
||||
'-v ON_ERROR_STOP=1 -At -F , -c "$SQL"'
|
||||
result = subprocess.run(
|
||||
['docker', 'compose', '--env-file', stand.ENV_FILE, 'exec', '-T',
|
||||
'-e', 'SQL=' + sql, 'postgres', 'sh', '-c', script],
|
||||
@@ -579,7 +682,8 @@ def hold_table_lock(table):
|
||||
process = subprocess.Popen(
|
||||
['docker', 'compose', '--env-file', stand.ENV_FILE, 'exec', '-T',
|
||||
'postgres', 'sh', '-c',
|
||||
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 -At'],
|
||||
'psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" '
|
||||
'-v ON_ERROR_STOP=1 -At'],
|
||||
cwd=ROOT, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, bufsize=1)
|
||||
pid = None
|
||||
@@ -630,12 +734,7 @@ def hold_table_lock(table):
|
||||
|
||||
|
||||
def wait_drained(attachment_ids, obs=None, timeout=120, flush_telemetry=True):
|
||||
"""Batch-check jobs/outbox/attachments in PostgreSQL (no HTTP polling).
|
||||
|
||||
Returns {'drained': bool, 'states': {id: status}, 'queued': n,
|
||||
'outbox': n, 'seconds': t, 'timestamps': ...}. A vanished known ID is a
|
||||
Failure; non-ready at the deadline is reported, not raised.
|
||||
"""
|
||||
"""Batch-check jobs/outbox/attachments in PostgreSQL (no HTTP polling)."""
|
||||
ids = list(attachment_ids)
|
||||
for item in ids:
|
||||
uuid.UUID(item)
|
||||
|
||||
Executable
+391
@@ -0,0 +1,391 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Idempotent OpenBao & Backend Store Bootstrap (non-dev Raft).
|
||||
# - Initializes OpenBao if uninitialized (5 Shamir shares, threshold 3 saved 0600
|
||||
# in $LAB7_OPERATOR_DIR/openbao/ outside Git, NEVER mounted into containers).
|
||||
# - Unseals via scripts/openbao-unseal.sh.
|
||||
# - Enables kv-v2 at secret/ and auth/cert, uploads ca.crl, writes least-privilege
|
||||
# HCL policies and cert roles, verifies operator mTLS login, and REVOKES the
|
||||
# initial root token (never persisted to disk, .env, or containers).
|
||||
# - Idempotently seeds scoped KV v2 secrets and converges live accounts in
|
||||
# PostgreSQL, Redis (mTLS + ACL SAVE), MinIO (HTTPS + CA), and RabbitMQ
|
||||
# (EXTERNAL passwordless CN users + strict producer/consumer ACLs).
|
||||
# - Never prints secrets, tokens, or unseal shares.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
BAO_OP_DIR="${OPERATOR_DIR}/openbao"
|
||||
OP_CERT="${OPERATOR_DIR}/operator/operator.crt"
|
||||
OP_KEY="${OPERATOR_DIR}/operator/operator.key"
|
||||
CA_CERT="${CA_FILE:-$(pwd)/secrets/pki/ca.crt}"
|
||||
CRL_FILE="$(pwd)/secrets/pki/ca.crl"
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
COMPOSE_ENV="${COMPOSE_ENV_FILE:-.env}"
|
||||
COMPOSE=(docker compose --env-file "$COMPOSE_ENV")
|
||||
MC_IMAGE="minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727"
|
||||
|
||||
umask 077
|
||||
mkdir -p "$BAO_OP_DIR"
|
||||
chmod 0700 "$BAO_OP_DIR"
|
||||
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-bao-boot.XXXXXX")"
|
||||
ROOT_CFG="${TMP_DIR}/root-auth.cfg"
|
||||
OP_CFG="${TMP_DIR}/op-auth.cfg"
|
||||
|
||||
cleanup() {
|
||||
if [ -s "$OP_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
if [ -s "$ROOT_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$ROOT_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$TMP_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
for req in "$CA_CERT" "$CRL_FILE" "$OP_CERT" "$OP_KEY"; do
|
||||
if [ ! -s "$req" ]; then
|
||||
echo "error: required PKI artifact missing: ${req}; run scripts/pki-bootstrap.sh first" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
write_token_cfg() {
|
||||
local cfg_path="$1"
|
||||
local token="$2"
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$token" > "$cfg_path"
|
||||
chmod 0600 "$cfg_path"
|
||||
}
|
||||
|
||||
bao_api() {
|
||||
local cfg="$1"
|
||||
local method="$2"
|
||||
local path="$3"
|
||||
shift 3
|
||||
curl -fsS --cacert "$CA_CERT" -K "$cfg" -X "$method" "$@" "${BAO_ADDR}/v1/${path}"
|
||||
}
|
||||
|
||||
bao_login_operator() {
|
||||
local login_json token
|
||||
login_json="$(curl -fsS --cacert "$CA_CERT" \
|
||||
--cert "$OP_CERT" --key "$OP_KEY" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${BAO_ADDR}/v1/auth/cert/login")"
|
||||
token="$(printf '%s' "$login_json" | jq -r '.auth.client_token // empty')"
|
||||
if [ -z "$token" ]; then
|
||||
echo "error: operator mTLS login to OpenBao failed" >&2
|
||||
exit 1
|
||||
fi
|
||||
write_token_cfg "$OP_CFG" "$token"
|
||||
}
|
||||
|
||||
write_policy() {
|
||||
local cfg="$1"
|
||||
local name="$2"
|
||||
local hcl_file="$3"
|
||||
jq -Rs '{policy: .}' < "$hcl_file" \
|
||||
| bao_api "$cfg" PUT "sys/policies/acl/${name}" \
|
||||
-H 'Content-Type: application/json' --data-binary @- >/dev/null
|
||||
}
|
||||
|
||||
write_cert_role() {
|
||||
local cfg="$1"
|
||||
local role="$2"
|
||||
local cn_pattern="$3"
|
||||
local dns_san="$4"
|
||||
local policy="$5"
|
||||
local no_default="$6"
|
||||
local ttl="$7"
|
||||
local max_ttl="$8"
|
||||
jq -n \
|
||||
--rawfile cert "$CA_CERT" \
|
||||
--arg role "$role" \
|
||||
--arg cn "$cn_pattern" \
|
||||
--arg san "$dns_san" \
|
||||
--arg policy "$policy" \
|
||||
--argjson no_def "$no_default" \
|
||||
--arg ttl "$ttl" \
|
||||
--arg max_ttl "$max_ttl" \
|
||||
'{
|
||||
display_name: $role,
|
||||
certificate: $cert,
|
||||
allowed_common_names: [$cn],
|
||||
allowed_dns_sans: [$san],
|
||||
token_policies: [$policy],
|
||||
token_no_default_policy: $no_def,
|
||||
token_ttl: $ttl,
|
||||
token_max_ttl: $max_ttl
|
||||
}' \
|
||||
| bao_api "$cfg" POST "auth/cert/certs/${role}" \
|
||||
-H 'Content-Type: application/json' --data-binary @- >/dev/null
|
||||
}
|
||||
|
||||
upload_crl() {
|
||||
local cfg="$1"
|
||||
jq -Rs '{crl: .}' < "$CRL_FILE" \
|
||||
| bao_api "$cfg" POST "auth/cert/crls/lab7-ca" \
|
||||
-H 'Content-Type: application/json' --data-binary @- >/dev/null
|
||||
}
|
||||
|
||||
# 1. Wait for OpenBao HTTPS listener
|
||||
seal_json=""
|
||||
for _ in $(seq 1 40); do
|
||||
if seal_json="$(curl -fsS --cacert "$CA_CERT" "${BAO_ADDR}/v1/sys/seal-status" 2>/dev/null)"; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [ -z "$seal_json" ]; then
|
||||
echo "error: OpenBao HTTPS listener unreachable at ${BAO_ADDR}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
initialized="$(printf '%s' "$seal_json" | jq -r '.initialized')"
|
||||
sealed="$(printf '%s' "$seal_json" | jq -r '.sealed')"
|
||||
|
||||
# 2. First-time initialization (or idempotent operator re-login)
|
||||
if [ "$initialized" != "true" ]; then
|
||||
init_json="$(curl -fsS --cacert "$CA_CERT" -X POST \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data '{"secret_shares":5,"secret_threshold":3}' \
|
||||
"${BAO_ADDR}/v1/sys/init")"
|
||||
|
||||
for i in 0 1 2 3 4; do
|
||||
idx=$((i + 1))
|
||||
printf '%s' "$init_json" | jq -r ".keys_base64[${i}]" > "${BAO_OP_DIR}/unseal-share-${idx}"
|
||||
chmod 0600 "${BAO_OP_DIR}/unseal-share-${idx}"
|
||||
done
|
||||
|
||||
root_token="$(printf '%s' "$init_json" | jq -r '.root_token')"
|
||||
write_token_cfg "$ROOT_CFG" "$root_token"
|
||||
unset init_json root_token
|
||||
echo "initialized OpenBao (5 shares / threshold 3 saved in ${BAO_OP_DIR})"
|
||||
|
||||
./scripts/openbao-unseal.sh --from-operator-dir "$BAO_OP_DIR"
|
||||
|
||||
# Wait briefly after unseal for Raft leader readiness
|
||||
for _ in $(seq 1 20); do
|
||||
if bao_api "$ROOT_CFG" GET "sys/mounts" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# Enable kv-v2 at secret/
|
||||
mounts_json="$(bao_api "$ROOT_CFG" GET "sys/mounts")"
|
||||
if ! printf '%s' "$mounts_json" | jq -e 'has("secret/")' >/dev/null; then
|
||||
bao_api "$ROOT_CFG" POST "sys/mounts/secret" \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data '{"type":"kv","options":{"version":"2"}}' >/dev/null
|
||||
fi
|
||||
|
||||
# Enable auth/cert
|
||||
auth_json="$(bao_api "$ROOT_CFG" GET "sys/auth")"
|
||||
if ! printf '%s' "$auth_json" | jq -e 'has("cert/")' >/dev/null; then
|
||||
bao_api "$ROOT_CFG" POST "sys/auth/cert" \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data '{"type":"cert"}' >/dev/null
|
||||
fi
|
||||
|
||||
# Install all 4 ACL policies
|
||||
write_policy "$ROOT_CFG" "api-policy" infra/openbao/policies/api.hcl
|
||||
write_policy "$ROOT_CFG" "worker-policy" infra/openbao/policies/worker.hcl
|
||||
write_policy "$ROOT_CFG" "migrator-policy" infra/openbao/policies/migrator.hcl
|
||||
write_policy "$ROOT_CFG" "operator-policy" infra/openbao/policies/operator.hcl
|
||||
|
||||
# Upload initial CRL and register all 4 cert roles
|
||||
upload_crl "$ROOT_CFG"
|
||||
write_cert_role "$ROOT_CFG" "messenger-api" "messenger-api-*" "messenger-api" "api-policy" true "5m" "30m"
|
||||
write_cert_role "$ROOT_CFG" "messenger-worker" "messenger-worker-*" "messenger-worker" "worker-policy" true "5m" "30m"
|
||||
write_cert_role "$ROOT_CFG" "messenger-migrator" "messenger-migrator-*" "messenger-migrator" "migrator-policy" true "2m" "5m"
|
||||
write_cert_role "$ROOT_CFG" "messenger-operator" "messenger-operator-*" "messenger-operator" "operator-policy" false "15m" "1h"
|
||||
|
||||
# Verify operator mTLS auth succeeds BEFORE revoking root token
|
||||
bao_login_operator
|
||||
|
||||
# Permanently revoke the initial root token (zero root token custody on disk!)
|
||||
bao_api "$ROOT_CFG" POST "auth/token/revoke-self" >/dev/null
|
||||
rm -f "$ROOT_CFG"
|
||||
echo "configured OpenBao kv-v2, auth/cert, policies, CRL and revoked initial root token"
|
||||
else
|
||||
if [ "$sealed" = "true" ]; then
|
||||
./scripts/openbao-unseal.sh --from-operator-dir "$BAO_OP_DIR"
|
||||
fi
|
||||
bao_login_operator
|
||||
# Idempotently converge workload policies, cert roles, and CRL using operator cert
|
||||
write_policy "$OP_CFG" "api-policy" infra/openbao/policies/api.hcl
|
||||
write_policy "$OP_CFG" "worker-policy" infra/openbao/policies/worker.hcl
|
||||
write_policy "$OP_CFG" "migrator-policy" infra/openbao/policies/migrator.hcl
|
||||
upload_crl "$OP_CFG"
|
||||
write_cert_role "$OP_CFG" "messenger-api" "messenger-api-*" "messenger-api" "api-policy" true "5m" "30m"
|
||||
write_cert_role "$OP_CFG" "messenger-worker" "messenger-worker-*" "messenger-worker" "worker-policy" true "5m" "30m"
|
||||
write_cert_role "$OP_CFG" "messenger-migrator" "messenger-migrator-*" "messenger-migrator" "migrator-policy" true "2m" "5m"
|
||||
echo "authenticated to initialized OpenBao via messenger-operator mTLS cert"
|
||||
fi
|
||||
|
||||
# 3. Read or generate scoped KV v2 secrets (never written to .env or ./secrets/)
|
||||
read_kv_optional() {
|
||||
local path="$1"
|
||||
local body code
|
||||
code="$(curl -sS --cacert "$CA_CERT" -K "$OP_CFG" -o "${TMP_DIR}/kv.out" -w '%{http_code}' \
|
||||
"${BAO_ADDR}/v1/secret/data/${path}")"
|
||||
if [ "$code" = "200" ]; then
|
||||
jq -c '.data.data' "${TMP_DIR}/kv.out"
|
||||
else
|
||||
printf ''
|
||||
fi
|
||||
}
|
||||
|
||||
write_kv() {
|
||||
local path="$1"
|
||||
local payload="$2"
|
||||
printf '%s' "$payload" \
|
||||
| jq '{data: .}' \
|
||||
| bao_api "$OP_CFG" POST "secret/data/${path}" \
|
||||
-H 'Content-Type: application/json' --data-binary @- >/dev/null
|
||||
}
|
||||
|
||||
api_cn="$(openssl x509 -in secrets/pki/api/client.crt -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
worker_cn="$(openssl x509 -in secrets/pki/worker/client.crt -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
api_cn="${api_cn:-messenger-api-g1}"
|
||||
worker_cn="${worker_cn:-messenger-worker-g1}"
|
||||
|
||||
api_kv="$(read_kv_optional "messenger/api")"
|
||||
if [ -z "$api_kv" ]; then
|
||||
api_kv="$(jq -n \
|
||||
--arg db_pass "$(openssl rand -hex 24)" \
|
||||
--arg redis_pass "$(openssl rand -hex 24)" \
|
||||
--arg s3_key "api-$(openssl rand -hex 8)" \
|
||||
--arg s3_sec "$(openssl rand -hex 24)" \
|
||||
--arg metrics "$(openssl rand -hex 24)" \
|
||||
'{
|
||||
db_user: "messenger_api",
|
||||
db_password: $db_pass,
|
||||
redis_user: "messenger_api",
|
||||
redis_password: $redis_pass,
|
||||
s3_access_key_id: $s3_key,
|
||||
s3_secret_access_key: $s3_sec,
|
||||
metrics_token: $metrics
|
||||
}')"
|
||||
write_kv "messenger/api" "$api_kv"
|
||||
echo "seeded OpenBao secret/messenger/api"
|
||||
else
|
||||
echo "kept existing OpenBao secret/messenger/api"
|
||||
fi
|
||||
|
||||
worker_kv="$(read_kv_optional "messenger/worker")"
|
||||
if [ -z "$worker_kv" ]; then
|
||||
worker_kv="$(jq -n \
|
||||
--arg db_pass "$(openssl rand -hex 24)" \
|
||||
--arg s3_key "worker-$(openssl rand -hex 8)" \
|
||||
--arg s3_sec "$(openssl rand -hex 24)" \
|
||||
--arg broker_user "$worker_cn" \
|
||||
'{
|
||||
db_user: "messenger_worker",
|
||||
db_password: $db_pass,
|
||||
s3_access_key_id: $s3_key,
|
||||
s3_secret_access_key: $s3_sec,
|
||||
broker_user: $broker_user
|
||||
}')"
|
||||
write_kv "messenger/worker" "$worker_kv"
|
||||
echo "seeded OpenBao secret/messenger/worker"
|
||||
else
|
||||
echo "kept existing OpenBao secret/messenger/worker"
|
||||
fi
|
||||
|
||||
migrator_kv="$(read_kv_optional "messenger/migrator")"
|
||||
if [ -z "$migrator_kv" ]; then
|
||||
migrator_kv="$(jq -n \
|
||||
--arg db_pass "$(openssl rand -hex 24)" \
|
||||
'{
|
||||
db_user: "messenger_migrator",
|
||||
db_password: $db_pass
|
||||
}')"
|
||||
write_kv "messenger/migrator" "$migrator_kv"
|
||||
echo "seeded OpenBao secret/messenger/migrator"
|
||||
else
|
||||
echo "kept existing OpenBao secret/messenger/migrator"
|
||||
fi
|
||||
|
||||
# Seed operator-admin reference copy (operator-policy ONLY)
|
||||
op_admin_kv="$(jq -n \
|
||||
--rawfile pg_pass secrets/infra/postgres_superuser_password \
|
||||
--rawfile minio_user secrets/infra/minio_root_user \
|
||||
--rawfile minio_pass secrets/infra/minio_root_password \
|
||||
--rawfile redis_admin secrets/infra/redis_admin_password \
|
||||
--rawfile grafana_pass secrets/infra/grafana_admin_password \
|
||||
'{
|
||||
pg_admin_password: ($pg_pass | gsub("\r|\n"; "")),
|
||||
minio_root_user: ($minio_user | gsub("\r|\n"; "")),
|
||||
minio_root_password: ($minio_pass | gsub("\r|\n"; "")),
|
||||
redis_admin_password: ($redis_admin | gsub("\r|\n"; "")),
|
||||
grafana_admin_password: ($grafana_pass | gsub("\r|\n"; ""))
|
||||
}')"
|
||||
write_kv "messenger/operator-admin" "$op_admin_kv"
|
||||
|
||||
# 4. Converge live backend auth stores (PostgreSQL, Redis, MinIO, RabbitMQ)
|
||||
|
||||
# 4a. PostgreSQL least-privilege roles & scram-sha-256 passwords
|
||||
pg_migrator_pass="$(printf '%s' "$migrator_kv" | jq -r '.db_password')"
|
||||
pg_api_pass="$(printf '%s' "$api_kv" | jq -r '.db_password')"
|
||||
pg_worker_pass="$(printf '%s' "$worker_kv" | jq -r '.db_password')"
|
||||
|
||||
{
|
||||
cat infra/postgres/01-init-roles.sql
|
||||
printf "\nSET password_encryption = 'scram-sha-256';\n"
|
||||
printf "ALTER ROLE messenger_migrator WITH LOGIN PASSWORD '%s';\n" "$pg_migrator_pass"
|
||||
printf "ALTER ROLE messenger_api WITH LOGIN PASSWORD '%s';\n" "$pg_api_pass"
|
||||
printf "ALTER ROLE messenger_worker WITH LOGIN PASSWORD '%s';\n" "$pg_worker_pass"
|
||||
} | "${COMPOSE[@]}" exec -T postgres psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -v ON_ERROR_STOP=1 >/dev/null
|
||||
echo "converged PostgreSQL roles (messenger_migrator, messenger_api, messenger_worker)"
|
||||
|
||||
# 4b. Redis mTLS ACL user (messenger_api ONLY; zero worker Redis access)
|
||||
redis_api_pass="$(printf '%s' "$api_kv" | jq -r '.redis_password')"
|
||||
printf 'ACL SETUSER messenger_api reset on >%s ~session:sha256:* ~messages:* ~lock:messages:* ~rl:* ~fault:* -@all +ping +hello +client|setinfo +quit +get +set +del +incr +expire +pexpire +ttl +pttl +@scripting +multi +exec +discard\nACL SAVE\n' \
|
||||
"$redis_api_pass" \
|
||||
| "${COMPOSE[@]}" exec -T redis sh -c \
|
||||
'REDISCLI_AUTH="$(cat /run/secrets/redis_admin_password)" redis-cli --tls --cacert /run/certs/ca.crt --cert /run/certs/health.crt --key /run/certs/health.key --user redis_admin -h localhost -p 6379 >/dev/null'
|
||||
echo "converged Redis ACL (messenger_api saved to /data/users.acl)"
|
||||
|
||||
# 4c. MinIO bucket, tightened policies & scoped IAM users over HTTPS + CA
|
||||
s3_api_key="$(printf '%s' "$api_kv" | jq -r '.s3_access_key_id')"
|
||||
s3_api_sec="$(printf '%s' "$api_kv" | jq -r '.s3_secret_access_key')"
|
||||
s3_worker_key="$(printf '%s' "$worker_kv" | jq -r '.s3_access_key_id')"
|
||||
s3_worker_sec="$(printf '%s' "$worker_kv" | jq -r '.s3_secret_access_key')"
|
||||
|
||||
s3_cid="$("${COMPOSE[@]}" ps -q s3 | head -n 1)"
|
||||
app_data_net="$(docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$s3_cid" \
|
||||
| tr ' ' '\n' | grep '_app_data$' | head -n 1)"
|
||||
if [ -z "$app_data_net" ]; then
|
||||
echo "error: could not detect app_data network for s3 container" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '%s\n%s\n%s\n%s\n' "$s3_api_key" "$s3_api_sec" "$s3_worker_key" "$s3_worker_sec" \
|
||||
| docker run --rm -i \
|
||||
--network "$app_data_net" \
|
||||
--user 1000:1000 \
|
||||
--read-only \
|
||||
--cap-drop ALL \
|
||||
--security-opt no-new-privileges:true \
|
||||
--tmpfs /tmp:size=16m,noexec,nosuid,nodev \
|
||||
-e "S3_BUCKET=${S3_BUCKET:-messenger-attachments}" \
|
||||
-v "$(pwd)/infra/minio:/bootstrap:ro" \
|
||||
-v "$(pwd)/secrets/pki/ca.crt:/run/certs/ca.crt:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_user:/run/secrets/minio_root_user:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_password:/run/secrets/minio_root_password:ro" \
|
||||
--entrypoint /bin/sh \
|
||||
"$MC_IMAGE" /bootstrap/bootstrap.sh
|
||||
|
||||
# 4d. RabbitMQ EXTERNAL passwordless CN users & strict producer/consumer ACLs
|
||||
"${COMPOSE[@]}" exec -T broker /bin/sh /etc/rabbitmq/init-worker.sh "$api_cn" "$worker_cn"
|
||||
|
||||
echo "openbao-bootstrap complete (root token revoked, zero secrets printed)"
|
||||
Executable
+96
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env bash
|
||||
# Operator-only OpenBao unseal command.
|
||||
# Reads 3 Shamir shares from $LAB7_OPERATOR_DIR/openbao/ (outside Git, never
|
||||
# mounted into containers) and unseals OpenBao over HTTPS with CA verification.
|
||||
# Never prints unseal keys. Idempotent if OpenBao is already unsealed.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
SHARES_DIR=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--from-operator-dir)
|
||||
shift
|
||||
SHARES_DIR="${1:?missing path for --from-operator-dir}"
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [--from-operator-dir <dir>]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
if [ -z "$SHARES_DIR" ]; then
|
||||
SHARES_DIR="${OPERATOR_DIR}/openbao"
|
||||
fi
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
CA_CERT="${CA_FILE:-$(pwd)/secrets/pki/ca.crt}"
|
||||
|
||||
if [ ! -s "$CA_CERT" ]; then
|
||||
echo "error: CA certificate not found at ${CA_CERT}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Wait briefly for listener readiness after container restart
|
||||
seal_json=""
|
||||
for _ in $(seq 1 30); do
|
||||
if seal_json="$(curl -fsS --cacert "$CA_CERT" "${BAO_ADDR}/v1/sys/seal-status" 2>/dev/null)"; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
if [ -z "$seal_json" ]; then
|
||||
echo "error: OpenBao not reachable at ${BAO_ADDR}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
initialized="$(printf '%s' "$seal_json" | jq -r '.initialized')"
|
||||
sealed="$(printf '%s' "$seal_json" | jq -r '.sealed')"
|
||||
|
||||
if [ "$initialized" != "true" ]; then
|
||||
echo "error: OpenBao is not initialized yet; run scripts/openbao-bootstrap.sh first" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$sealed" = "false" ]; then
|
||||
echo "openbao already unsealed (${BAO_ADDR})"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
for idx in 1 2 3; do
|
||||
share_file="${SHARES_DIR}/unseal-share-${idx}"
|
||||
if [ ! -s "$share_file" ]; then
|
||||
echo "error: missing unseal share file ${share_file}" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Pipe share strictly via stdin so key material never appears in process argv.
|
||||
resp="$(jq -Rs '{key: (gsub("\r|\n"; ""))}' < "$share_file" \
|
||||
| curl -fsS --cacert "$CA_CERT" -X PUT \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data-binary @- \
|
||||
"${BAO_ADDR}/v1/sys/unseal")"
|
||||
sealed="$(printf '%s' "$resp" | jq -r '.sealed')"
|
||||
if [ "$sealed" = "false" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$sealed" != "false" ]; then
|
||||
echo "error: OpenBao remained sealed after submitting 3 shares" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "openbao unsealed ok (${BAO_ADDR})"
|
||||
Executable
+373
@@ -0,0 +1,373 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Idempotent Local PKI Bootstrap.
|
||||
# - Operator CA private key, OpenSSL CA DB, foreign-ca, rogue-client, and
|
||||
# messenger-operator-g1 live strictly outside Git in $LAB7_OPERATOR_DIR (0700)
|
||||
# and are NEVER mounted into any container.
|
||||
# - Runtime per-service leaf certs, ca.crt, and ca.crl are installed atomically
|
||||
# into gitignored ./secrets/pki/<service>/ with strict EKU separation
|
||||
# (serverAuth ONLY vs clientAuth ONLY) and single-DNS-SAN client identities.
|
||||
# - Never prints private keys. Re-running is idempotent unless --force is set.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
FORCE=0
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--force) FORCE=1 ;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [--force]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
PKI_OP_DIR="${OPERATOR_DIR}/pki"
|
||||
BAO_OP_DIR="${OPERATOR_DIR}/openbao"
|
||||
OP_CERT_DIR="${OPERATOR_DIR}/operator"
|
||||
RUNTIME_PKI_DIR="$(pwd)/secrets/pki"
|
||||
|
||||
umask 077
|
||||
mkdir -p "$OPERATOR_DIR" "$PKI_OP_DIR/newcerts" "$PKI_OP_DIR/issued" "$BAO_OP_DIR" "$OP_CERT_DIR"
|
||||
chmod 0700 "$OPERATOR_DIR" "$PKI_OP_DIR" "$PKI_OP_DIR/newcerts" "$PKI_OP_DIR/issued" "$BAO_OP_DIR" "$OP_CERT_DIR"
|
||||
|
||||
mkdir -p secrets "$RUNTIME_PKI_DIR"
|
||||
chmod 0700 secrets "$RUNTIME_PKI_DIR"
|
||||
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-pki.XXXXXX")"
|
||||
trap 'rm -rf "$TMP_DIR"' EXIT
|
||||
|
||||
CA_CNF="${PKI_OP_DIR}/ca.cnf"
|
||||
write_ca_cnf() {
|
||||
cat > "${CA_CNF}" <<EOF
|
||||
[ ca ]
|
||||
default_ca = CA_default
|
||||
|
||||
[ CA_default ]
|
||||
dir = ${PKI_OP_DIR}
|
||||
certs = \$dir
|
||||
crl_dir = \$dir
|
||||
new_certs_dir = \$dir/newcerts
|
||||
database = \$dir/index.txt
|
||||
serial = \$dir/serial
|
||||
crlnumber = \$dir/crlnumber
|
||||
certificate = \$dir/ca.crt
|
||||
private_key = \$dir/ca.key
|
||||
default_md = sha256
|
||||
default_days = 30
|
||||
default_crl_days = 30
|
||||
preserve = no
|
||||
unique_subject = no
|
||||
policy = policy_loose
|
||||
copy_extensions = copy
|
||||
crl_extensions = crl_ext
|
||||
|
||||
[ policy_loose ]
|
||||
organizationName = optional
|
||||
commonName = supplied
|
||||
|
||||
[ req ]
|
||||
default_md = sha256
|
||||
distinguished_name = req_dn
|
||||
prompt = no
|
||||
|
||||
[ req_dn ]
|
||||
O = mtusi-lab7
|
||||
CN = mtusi-lab7-local-ca
|
||||
|
||||
[ v3_ca ]
|
||||
subjectKeyIdentifier = hash
|
||||
authorityKeyIdentifier = keyid:always,issuer
|
||||
basicConstraints = critical, CA:true, pathlen:0
|
||||
keyUsage = critical, keyCertSign, cRLSign
|
||||
|
||||
[ v3_server ]
|
||||
basicConstraints = critical, CA:false
|
||||
subjectKeyIdentifier = hash
|
||||
authorityKeyIdentifier = keyid:always,issuer
|
||||
keyUsage = critical, digitalSignature
|
||||
extendedKeyUsage = serverAuth
|
||||
|
||||
[ v3_client ]
|
||||
basicConstraints = critical, CA:false
|
||||
subjectKeyIdentifier = hash
|
||||
authorityKeyIdentifier = keyid:always,issuer
|
||||
keyUsage = critical, digitalSignature
|
||||
extendedKeyUsage = clientAuth
|
||||
|
||||
[ crl_ext ]
|
||||
authorityKeyIdentifier = keyid:always
|
||||
EOF
|
||||
chmod 0600 "${CA_CNF}"
|
||||
}
|
||||
|
||||
atomic_install() {
|
||||
local src="$1"
|
||||
local dst="$2"
|
||||
local mode="$3"
|
||||
local dir
|
||||
dir="$(dirname "$dst")"
|
||||
mkdir -p "$dir"
|
||||
local tmp="${dst}.tmp.$$"
|
||||
cp "$src" "$tmp"
|
||||
chmod "$mode" "$tmp"
|
||||
mv -f "$tmp" "$dst"
|
||||
}
|
||||
|
||||
if [ "$FORCE" -eq 1 ]; then
|
||||
rm -f "${PKI_OP_DIR}/ca.key" "${PKI_OP_DIR}/ca.crt" "${PKI_OP_DIR}/ca.crl" \
|
||||
"${PKI_OP_DIR}/index.txt" "${PKI_OP_DIR}/index.txt.old" "${PKI_OP_DIR}/index.txt.attr" "${PKI_OP_DIR}/index.txt.attr.old" \
|
||||
"${PKI_OP_DIR}/serial" "${PKI_OP_DIR}/serial.old" "${PKI_OP_DIR}/crlnumber" "${PKI_OP_DIR}/crlnumber.old" \
|
||||
"${PKI_OP_DIR}/foreign-ca.key" "${PKI_OP_DIR}/foreign-ca.crt" \
|
||||
"${PKI_OP_DIR}/foreign-client.key" "${PKI_OP_DIR}/foreign-client.crt" \
|
||||
"${PKI_OP_DIR}/rogue-client.key" "${PKI_OP_DIR}/rogue-client.crt" \
|
||||
"${OP_CERT_DIR}/operator.key" "${OP_CERT_DIR}/operator.crt"
|
||||
rm -rf "${PKI_OP_DIR}/newcerts" "${PKI_OP_DIR}/issued"
|
||||
mkdir -p "${PKI_OP_DIR}/newcerts" "${PKI_OP_DIR}/issued"
|
||||
chmod 0700 "${PKI_OP_DIR}/newcerts" "${PKI_OP_DIR}/issued"
|
||||
fi
|
||||
|
||||
write_ca_cnf
|
||||
|
||||
# 1. Local Root CA (ECDSA P-256, pathlen:0, 365d)
|
||||
if [ ! -s "${PKI_OP_DIR}/ca.key" ] || [ ! -s "${PKI_OP_DIR}/ca.crt" ]; then
|
||||
: > "${PKI_OP_DIR}/index.txt"
|
||||
printf 'unique_subject = no\n' > "${PKI_OP_DIR}/index.txt.attr"
|
||||
printf '1000\n' > "${PKI_OP_DIR}/serial"
|
||||
printf '1000\n' > "${PKI_OP_DIR}/crlnumber"
|
||||
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "${PKI_OP_DIR}/ca.key"
|
||||
chmod 0600 "${PKI_OP_DIR}/ca.key"
|
||||
openssl req -new -x509 -sha256 -days 365 \
|
||||
-key "${PKI_OP_DIR}/ca.key" \
|
||||
-config "${CA_CNF}" -extensions v3_ca \
|
||||
-subj "/O=mtusi-lab7/CN=mtusi-lab7-local-ca" \
|
||||
-out "${PKI_OP_DIR}/ca.crt"
|
||||
chmod 0644 "${PKI_OP_DIR}/ca.crt"
|
||||
echo "created Root CA in ${PKI_OP_DIR}"
|
||||
else
|
||||
[ -f "${PKI_OP_DIR}/index.txt" ] || : > "${PKI_OP_DIR}/index.txt"
|
||||
[ -f "${PKI_OP_DIR}/index.txt.attr" ] || printf 'unique_subject = no\n' > "${PKI_OP_DIR}/index.txt.attr"
|
||||
[ -f "${PKI_OP_DIR}/serial" ] || printf '1000\n' > "${PKI_OP_DIR}/serial"
|
||||
[ -f "${PKI_OP_DIR}/crlnumber" ] || printf '1000\n' > "${PKI_OP_DIR}/crlnumber"
|
||||
echo "kept Root CA in ${PKI_OP_DIR}"
|
||||
fi
|
||||
|
||||
# Generate or refresh CRL v2
|
||||
if [ ! -s "${PKI_OP_DIR}/ca.crl" ] || [ "$FORCE" -eq 1 ]; then
|
||||
openssl ca -batch -config "${CA_CNF}" -gencrl -out "${PKI_OP_DIR}/ca.crl" >/dev/null 2>&1
|
||||
chmod 0644 "${PKI_OP_DIR}/ca.crl"
|
||||
fi
|
||||
|
||||
# 2. Foreign CA + Foreign Client (strictly in operator dir for negative tests)
|
||||
if [ ! -s "${PKI_OP_DIR}/foreign-ca.key" ] || [ ! -s "${PKI_OP_DIR}/foreign-ca.crt" ]; then
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "${PKI_OP_DIR}/foreign-ca.key"
|
||||
chmod 0600 "${PKI_OP_DIR}/foreign-ca.key"
|
||||
openssl req -new -x509 -sha256 -days 365 \
|
||||
-key "${PKI_OP_DIR}/foreign-ca.key" \
|
||||
-subj "/O=mtusi-lab7-foreign/CN=mtusi-lab7-foreign-ca" \
|
||||
-addext "basicConstraints=critical,CA:true,pathlen:0" \
|
||||
-addext "keyUsage=critical,keyCertSign,cRLSign" \
|
||||
-out "${PKI_OP_DIR}/foreign-ca.crt"
|
||||
chmod 0644 "${PKI_OP_DIR}/foreign-ca.crt"
|
||||
fi
|
||||
|
||||
if [ ! -s "${PKI_OP_DIR}/foreign-client.key" ] || [ ! -s "${PKI_OP_DIR}/foreign-client.crt" ]; then
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "${PKI_OP_DIR}/foreign-client.key"
|
||||
chmod 0600 "${PKI_OP_DIR}/foreign-client.key"
|
||||
openssl req -new -sha256 \
|
||||
-key "${PKI_OP_DIR}/foreign-client.key" \
|
||||
-subj "/O=mtusi-lab7-foreign/CN=foreign-client" \
|
||||
-out "${TMP_DIR}/foreign-client.csr"
|
||||
cat > "${TMP_DIR}/foreign-client.ext" <<EOF
|
||||
basicConstraints = critical, CA:false
|
||||
keyUsage = critical, digitalSignature
|
||||
extendedKeyUsage = clientAuth
|
||||
subjectAltName = DNS:foreign-client
|
||||
EOF
|
||||
openssl x509 -req -sha256 -days 30 \
|
||||
-in "${TMP_DIR}/foreign-client.csr" \
|
||||
-CA "${PKI_OP_DIR}/foreign-ca.crt" -CAkey "${PKI_OP_DIR}/foreign-ca.key" -CAcreateserial \
|
||||
-extfile "${TMP_DIR}/foreign-client.ext" \
|
||||
-out "${PKI_OP_DIR}/foreign-client.crt" >/dev/null 2>&1
|
||||
chmod 0644 "${PKI_OP_DIR}/foreign-client.crt"
|
||||
rm -f "${PKI_OP_DIR}/foreign-ca.srl"
|
||||
fi
|
||||
|
||||
# Helper: issue leaf cert signed by our Local Root CA via `openssl ca` (tracks serial in index.txt)
|
||||
issue_leaf() {
|
||||
local cert_id="$1"
|
||||
local kind="$2" # server | client
|
||||
local cn="$3"
|
||||
local san="$4"
|
||||
local out_crt="$5"
|
||||
local out_key="$6"
|
||||
local key_mode="${7:-0644}"
|
||||
|
||||
if [ "$FORCE" -eq 0 ] && [ -s "$out_crt" ] && [ -s "$out_key" ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local ext_section="v3_server"
|
||||
[ "$kind" = "client" ] && ext_section="v3_client"
|
||||
|
||||
local req_cnf="${TMP_DIR}/${cert_id}.req.cnf"
|
||||
local key_tmp="${TMP_DIR}/${cert_id}.key"
|
||||
local csr_tmp="${TMP_DIR}/${cert_id}.csr"
|
||||
local crt_tmp="${TMP_DIR}/${cert_id}.crt"
|
||||
|
||||
cat > "$req_cnf" <<EOF
|
||||
[ req ]
|
||||
default_md = sha256
|
||||
distinguished_name = dn
|
||||
req_extensions = req_ext
|
||||
prompt = no
|
||||
|
||||
[ dn ]
|
||||
O = mtusi-lab7
|
||||
CN = ${cn}
|
||||
|
||||
[ req_ext ]
|
||||
subjectAltName = ${san}
|
||||
EOF
|
||||
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "$key_tmp"
|
||||
openssl req -new -sha256 -key "$key_tmp" -config "$req_cnf" -out "$csr_tmp"
|
||||
openssl ca -batch -notext -config "${CA_CNF}" -extensions "$ext_section" \
|
||||
-in "$csr_tmp" -out "$crt_tmp" >/dev/null 2>&1
|
||||
|
||||
atomic_install "$crt_tmp" "$out_crt" 0644
|
||||
atomic_install "$key_tmp" "$out_key" "$key_mode"
|
||||
# Keep public cert reference in operator DB for deterministic revocation later.
|
||||
atomic_install "$crt_tmp" "${PKI_OP_DIR}/issued/${cert_id}.crt" 0644
|
||||
echo "issued ${cert_id} (kind=${kind} cn=${cn})"
|
||||
}
|
||||
|
||||
make_bundle() {
|
||||
local crt="$1"
|
||||
local key="$2"
|
||||
local bundle="$3"
|
||||
local tmp="${TMP_DIR}/bundle.pem"
|
||||
cat "$crt" "$key" > "$tmp"
|
||||
atomic_install "$tmp" "$bundle" 0644
|
||||
}
|
||||
|
||||
# 3. Operator-only certs signed by our Root CA (NEVER mounted into containers)
|
||||
issue_leaf rogue-client client rogue-client "DNS:rogue-client" \
|
||||
"${PKI_OP_DIR}/rogue-client.crt" "${PKI_OP_DIR}/rogue-client.key" 0600
|
||||
|
||||
issue_leaf messenger-operator client messenger-operator-g1 "DNS:messenger-operator" \
|
||||
"${OP_CERT_DIR}/operator.crt" "${OP_CERT_DIR}/operator.key" 0600
|
||||
|
||||
# 4. Prepare isolated per-service runtime cert dirs (0755 inside 0700 host parent)
|
||||
SERVICES=(
|
||||
haproxy api worker migrate postgres redis s3 broker
|
||||
otel-gateway otel-collector prometheus loki tempo grafana openbao
|
||||
)
|
||||
for svc in "${SERVICES[@]}"; do
|
||||
mkdir -p "${RUNTIME_PKI_DIR}/${svc}"
|
||||
chmod 0755 "${RUNTIME_PKI_DIR}/${svc}"
|
||||
done
|
||||
mkdir -p "${RUNTIME_PKI_DIR}/s3/CAs"
|
||||
chmod 0755 "${RUNTIME_PKI_DIR}/s3/CAs"
|
||||
|
||||
# 5. Server certificates (EKU=serverAuth ONLY, per unified-contract.md §1.2)
|
||||
issue_leaf haproxy-ingress server localhost "DNS:localhost,DNS:haproxy" \
|
||||
"${RUNTIME_PKI_DIR}/haproxy/server.crt" "${RUNTIME_PKI_DIR}/haproxy/server.key" 0644
|
||||
make_bundle "${RUNTIME_PKI_DIR}/haproxy/server.crt" "${RUNTIME_PKI_DIR}/haproxy/server.key" \
|
||||
"${RUNTIME_PKI_DIR}/haproxy/server.pem"
|
||||
|
||||
issue_leaf api-server server api "DNS:api" \
|
||||
"${RUNTIME_PKI_DIR}/api/server.crt" "${RUNTIME_PKI_DIR}/api/server.key" 0644
|
||||
|
||||
issue_leaf postgres-server server postgres "DNS:postgres,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/postgres/server.crt" "${RUNTIME_PKI_DIR}/postgres/server.key" 0644
|
||||
|
||||
issue_leaf redis-server server redis "DNS:redis,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/redis/server.crt" "${RUNTIME_PKI_DIR}/redis/server.key" 0644
|
||||
|
||||
issue_leaf s3-server server s3 "DNS:s3,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/s3/public.crt" "${RUNTIME_PKI_DIR}/s3/private.key" 0644
|
||||
|
||||
issue_leaf broker-server server broker "DNS:broker" \
|
||||
"${RUNTIME_PKI_DIR}/broker/server.crt" "${RUNTIME_PKI_DIR}/broker/server.key" 0644
|
||||
|
||||
issue_leaf otel-server server otel-collector "DNS:otel-collector,DNS:otel-gateway" \
|
||||
"${RUNTIME_PKI_DIR}/otel-gateway/server.crt" "${RUNTIME_PKI_DIR}/otel-gateway/server.key" 0644
|
||||
make_bundle "${RUNTIME_PKI_DIR}/otel-gateway/server.crt" "${RUNTIME_PKI_DIR}/otel-gateway/server.key" \
|
||||
"${RUNTIME_PKI_DIR}/otel-gateway/server.pem"
|
||||
|
||||
issue_leaf prometheus-server server prometheus "DNS:prometheus,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/prometheus/server.crt" "${RUNTIME_PKI_DIR}/prometheus/server.key" 0644
|
||||
|
||||
issue_leaf loki-server server loki "DNS:loki" \
|
||||
"${RUNTIME_PKI_DIR}/loki/server.crt" "${RUNTIME_PKI_DIR}/loki/server.key" 0644
|
||||
|
||||
issue_leaf tempo-server server tempo "DNS:tempo" \
|
||||
"${RUNTIME_PKI_DIR}/tempo/server.crt" "${RUNTIME_PKI_DIR}/tempo/server.key" 0644
|
||||
|
||||
issue_leaf grafana-server server grafana "DNS:grafana,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/grafana/server.crt" "${RUNTIME_PKI_DIR}/grafana/server.key" 0644
|
||||
|
||||
issue_leaf openbao-server server openbao "DNS:openbao,DNS:localhost,IP:127.0.0.1" \
|
||||
"${RUNTIME_PKI_DIR}/openbao/server.crt" "${RUNTIME_PKI_DIR}/openbao/server.key" 0644
|
||||
|
||||
# 6. Client identity certificates (EKU=clientAuth ONLY, single DNS SAN, per unified-contract.md §1.3)
|
||||
issue_leaf haproxy-client client haproxy-lb-g1 "DNS:haproxy-lb" \
|
||||
"${RUNTIME_PKI_DIR}/haproxy/client.crt" "${RUNTIME_PKI_DIR}/haproxy/client.key" 0644
|
||||
make_bundle "${RUNTIME_PKI_DIR}/haproxy/client.crt" "${RUNTIME_PKI_DIR}/haproxy/client.key" \
|
||||
"${RUNTIME_PKI_DIR}/haproxy/client.pem"
|
||||
|
||||
issue_leaf api-client client messenger-api-g1 "DNS:messenger-api" \
|
||||
"${RUNTIME_PKI_DIR}/api/client.crt" "${RUNTIME_PKI_DIR}/api/client.key" 0644
|
||||
|
||||
issue_leaf worker-client client messenger-worker-g1 "DNS:messenger-worker" \
|
||||
"${RUNTIME_PKI_DIR}/worker/client.crt" "${RUNTIME_PKI_DIR}/worker/client.key" 0644
|
||||
|
||||
issue_leaf migrator-client client messenger-migrator-g1 "DNS:messenger-migrator" \
|
||||
"${RUNTIME_PKI_DIR}/migrate/client.crt" "${RUNTIME_PKI_DIR}/migrate/client.key" 0644
|
||||
|
||||
issue_leaf otel-collector-client client otel-collector "DNS:otel-collector" \
|
||||
"${RUNTIME_PKI_DIR}/otel-collector/client.crt" "${RUNTIME_PKI_DIR}/otel-collector/client.key" 0644
|
||||
|
||||
issue_leaf grafana-client client grafana "DNS:grafana" \
|
||||
"${RUNTIME_PKI_DIR}/grafana/client.crt" "${RUNTIME_PKI_DIR}/grafana/client.key" 0644
|
||||
|
||||
issue_leaf prometheus-client client prometheus "DNS:prometheus" \
|
||||
"${RUNTIME_PKI_DIR}/prometheus/client.crt" "${RUNTIME_PKI_DIR}/prometheus/client.key" 0644
|
||||
|
||||
issue_leaf redis-health client redis-health "DNS:redis-health" \
|
||||
"${RUNTIME_PKI_DIR}/redis/health.crt" "${RUNTIME_PKI_DIR}/redis/health.key" 0644
|
||||
|
||||
# 7. Distribute public CA cert and CRL atomically into runtime PKI dirs
|
||||
atomic_install "${PKI_OP_DIR}/ca.crt" "${RUNTIME_PKI_DIR}/ca.crt" 0644
|
||||
atomic_install "${PKI_OP_DIR}/ca.crl" "${RUNTIME_PKI_DIR}/ca.crl" 0644
|
||||
atomic_install "${PKI_OP_DIR}/ca.crt" "${RUNTIME_PKI_DIR}/s3/CAs/ca.crt" 0644
|
||||
|
||||
for svc in haproxy api worker migrate postgres redis broker otel-gateway otel-collector prometheus loki tempo grafana openbao; do
|
||||
atomic_install "${PKI_OP_DIR}/ca.crt" "${RUNTIME_PKI_DIR}/${svc}/ca.crt" 0644
|
||||
done
|
||||
|
||||
for svc in haproxy api worker migrate postgres redis broker otel-gateway prometheus openbao; do
|
||||
atomic_install "${PKI_OP_DIR}/ca.crl" "${RUNTIME_PKI_DIR}/${svc}/ca.crl" 0644
|
||||
done
|
||||
|
||||
# 8. OTel Gateway mTLS CN & SAN allowlists (mounted via /run/certs:ro; never dirty Git)
|
||||
if [ "$FORCE" -eq 1 ] || [ ! -s "${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-cn.lst" ]; then
|
||||
api_cn="$(openssl x509 -in "${RUNTIME_PKI_DIR}/api/client.crt" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
worker_cn="$(openssl x509 -in "${RUNTIME_PKI_DIR}/worker/client.crt" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
printf '%s\n%s\n' "${api_cn:-messenger-api-g1}" "${worker_cn:-messenger-worker-g1}" > "${TMP_DIR}/allowed-otlp-cn.lst"
|
||||
atomic_install "${TMP_DIR}/allowed-otlp-cn.lst" "${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-cn.lst" 0644
|
||||
fi
|
||||
|
||||
if [ "$FORCE" -eq 1 ] || [ ! -s "${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-san.lst" ]; then
|
||||
printf 'DNS:messenger-api\nDNS:messenger-worker\n' > "${TMP_DIR}/allowed-otlp-san.lst"
|
||||
atomic_install "${TMP_DIR}/allowed-otlp-san.lst" "${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-san.lst" 0644
|
||||
fi
|
||||
|
||||
echo "pki-bootstrap ok: operator_dir=${OPERATOR_DIR} runtime_dir=${RUNTIME_PKI_DIR}"
|
||||
+11
-4
@@ -1,8 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`.
|
||||
# Semantic and evidence notes: tests/README.md ("Проверка сохранности") and REPORT.md.
|
||||
# Restarts all application, stateful data, and telemetry containers with volumes
|
||||
# preserved. OpenBao remains unsealed across ordinary stand restarts (per
|
||||
# contracts/trust-matrix.md); OpenBao restart + manual operator unseal is tested
|
||||
# explicitly in scripts/lab7/openbao_lifecycle.py.
|
||||
set -euo pipefail
|
||||
|
||||
compose=(docker compose --env-file .env)
|
||||
"${compose[@]}" restart postgres redis s3 broker api worker haproxy otel-collector prometheus loki tempo grafana
|
||||
"${compose[@]}" up -d --no-recreate --no-deps --wait postgres redis s3 broker api worker haproxy otel-collector prometheus loki tempo grafana
|
||||
compose=(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}")
|
||||
# Stop otel-collector before restarting otel-gateway (shared netns owner) so
|
||||
# otel-collector cleanly re-attaches to the fresh otel-gateway network namespace.
|
||||
"${compose[@]}" stop otel-collector
|
||||
"${compose[@]}" restart postgres redis s3 broker api worker haproxy otel-gateway prometheus loki tempo grafana
|
||||
"${compose[@]}" up -d --no-build --no-recreate --no-deps --wait postgres redis s3 broker api worker haproxy otel-gateway prometheus loki tempo grafana
|
||||
"${compose[@]}" up -d --no-build --no-deps otel-collector
|
||||
|
||||
Executable
+232
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Grade 5 Track 1 («Компрометация worker»): Full Containment & Recovery.
|
||||
# Zero image rebuild, zero root token (uses operator mTLS cert).
|
||||
# Usage: scripts/revoke-worker.sh [--no-start] [--old-cn <cn>] [--new-cn <cn>]
|
||||
#
|
||||
# Containment actions across ALL control planes:
|
||||
# 1. OpenSSL CA revoke old worker cert -> regenerate & distribute ca.crl ->
|
||||
# upload CRL to OpenBao auth/cert/crls/lab7-ca -> reload api/haproxy/postgres.
|
||||
# 2. Selectively revoke active OpenBao token accessors for messenger-worker
|
||||
# (leaves messenger-api and messenger-operator tokens completely intact).
|
||||
# 3. OTel Gateway: remove old CN from allowed-otlp-cn.lst, add new CN, SIGUSR2.
|
||||
# 4. RabbitMQ: delete_user <old_cn> (kills active AMQPS connections immediately)
|
||||
# and create passwordless EXTERNAL user <new_cn> with consumer-only ACL.
|
||||
# 5. PostgreSQL: rotate messenger_worker password + pg_terminate_backend on
|
||||
# active messenger_worker sessions.
|
||||
# 6. MinIO: create new worker-<hex> IAM user with messenger-worker policy and
|
||||
# delete old worker IAM user over HTTPS + CA.
|
||||
# 7. PKI: issue new worker leaf cert (<new_cn>, SAN=DNS:messenger-worker).
|
||||
# 8. OpenBao KV v2: write version N+1 to secret/messenger/worker.
|
||||
# 9. Unless --no-start is set, start/restart worker with --no-build --wait.
|
||||
# Never prints secrets, passwords, keys, or tokens.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
NO_START=0
|
||||
OLD_CN=""
|
||||
NEW_CN=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--no-start) NO_START=1 ;;
|
||||
--old-cn)
|
||||
shift
|
||||
OLD_CN="${1:?missing value for --old-cn}"
|
||||
;;
|
||||
--new-cn)
|
||||
shift
|
||||
NEW_CN="${1:?missing value for --new-cn}"
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [--no-start] [--old-cn <cn>] [--new-cn <cn>]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
OP_CERT="${OPERATOR_DIR}/operator/operator.crt"
|
||||
OP_KEY="${OPERATOR_DIR}/operator/operator.key"
|
||||
RUNTIME_PKI_DIR="$(pwd)/secrets/pki"
|
||||
CA_CERT="${CA_FILE:-${RUNTIME_PKI_DIR}/ca.crt}"
|
||||
WORKER_CRT="${RUNTIME_PKI_DIR}/worker/client.crt"
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
COMPOSE=(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}")
|
||||
MC_IMAGE="minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727"
|
||||
|
||||
if [ ! -s "$WORKER_CRT" ]; then
|
||||
echo "error: current worker certificate not found at ${WORKER_CRT}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$OLD_CN" ]; then
|
||||
OLD_CN="$(openssl x509 -in "$WORKER_CRT" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
fi
|
||||
OLD_CN="${OLD_CN:-messenger-worker-g1}"
|
||||
|
||||
if [ -z "$NEW_CN" ]; then
|
||||
if [[ "$OLD_CN" =~ ^(.*-g)([0-9]+)$ ]]; then
|
||||
NEW_CN="${BASH_REMATCH[1]}$((BASH_REMATCH[2] + 1))"
|
||||
else
|
||||
NEW_CN="messenger-worker-g2"
|
||||
fi
|
||||
fi
|
||||
|
||||
OLD_SERIAL="$(openssl x509 -in "$WORKER_CRT" -noout -serial | cut -d= -f2)"
|
||||
|
||||
umask 077
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-revoke-wrk.XXXXXX")"
|
||||
OP_CFG="${TMP_DIR}/op-auth.cfg"
|
||||
cleanup() {
|
||||
if [ -s "$OP_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$TMP_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# Authenticate as operator via mTLS cert (zero root token)
|
||||
login_json="$(curl -fsS --cacert "$CA_CERT" --cert "$OP_CERT" --key "$OP_KEY" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${BAO_ADDR}/v1/auth/cert/login")"
|
||||
op_token="$(printf '%s' "$login_json" | jq -r '.auth.client_token // empty')"
|
||||
if [ -z "$op_token" ]; then
|
||||
echo "error: operator mTLS login to OpenBao failed" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$op_token" > "$OP_CFG"
|
||||
chmod 0600 "$OP_CFG"
|
||||
unset login_json op_token
|
||||
|
||||
# 1. Read existing worker KV secret (to identify old MinIO IAM user)
|
||||
cur_worker_kv="$(curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" \
|
||||
"${BAO_ADDR}/v1/secret/data/messenger/worker" | jq -c '.data.data')"
|
||||
old_s3_key="$(printf '%s' "$cur_worker_kv" | jq -r '.s3_access_key_id // empty')"
|
||||
|
||||
# 2. Rotate worker leaf cert WITH CRL revocation & OTel Gateway allowlist update
|
||||
# (handles OpenSSL ca -revoke, ca.crl distribution, OpenBao CRL upload,
|
||||
# OTel allowed-otlp-cn.lst replacement + SIGUSR2, api SIGHUP, haproxy SIGUSR2, postgres reload)
|
||||
rot_out="$(./scripts/rotate-cert.sh worker --revoke --cn "$NEW_CN")"
|
||||
NEW_SERIAL="$(printf '%s' "$rot_out" | sed -n 's/.*new_serial=\([^ ]*\).*/\1/p')"
|
||||
|
||||
# 3. Selectively revoke active OpenBao token accessors for messenger-worker ONLY
|
||||
revoked_accessors=0
|
||||
accessors_json="$(curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X LIST \
|
||||
"${BAO_ADDR}/v1/auth/token/accessors" 2>/dev/null || echo '{"data":{"keys":[]}}')"
|
||||
for acc in $(printf '%s' "$accessors_json" | jq -r '.data.keys[]? // empty'); do
|
||||
lookup="$(jq -n --arg a "$acc" '{accessor: $a}' \
|
||||
| curl -sS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/auth/token/lookup-accessor" 2>/dev/null || true)"
|
||||
cert_name="$(printf '%s' "$lookup" | jq -r '.data.meta.cert_name // empty' 2>/dev/null || true)"
|
||||
common_name="$(printf '%s' "$lookup" | jq -r '.data.meta.common_name // empty' 2>/dev/null || true)"
|
||||
if [ "$cert_name" = "messenger-worker" ] || [ "$common_name" = "$OLD_CN" ]; then
|
||||
jq -n --arg a "$acc" '{accessor: $a}' \
|
||||
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-accessor" >/dev/null 2>&1 || true
|
||||
revoked_accessors=$((revoked_accessors + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
# 4. RabbitMQ: delete compromised EXTERNAL user (closes active connections) & create new generation user
|
||||
"${COMPOSE[@]}" exec -T broker sh -eu -c '
|
||||
old_cn=$1
|
||||
new_cn=$2
|
||||
if rabbitmqctl -q list_users | awk "{print \$1}" | grep -Fxq "$old_cn"; then
|
||||
rabbitmqctl -q delete_user "$old_cn"
|
||||
fi
|
||||
if ! rabbitmqctl -q list_users | awk "{print \$1}" | grep -Fxq "$new_cn"; then
|
||||
rabbitmqctl -q add_user "$new_cn" "tmp-$(head -c 16 /dev/urandom | od -An -tx1 | tr -d " \n")"
|
||||
fi
|
||||
rabbitmqctl -q clear_password "$new_cn"
|
||||
rabbitmqctl -q set_user_tags "$new_cn"
|
||||
rabbitmqctl -q set_permissions -p messenger "$new_cn" "^$" "^$" "^attachments\.process$"
|
||||
' _ "$OLD_CN" "$NEW_CN"
|
||||
|
||||
# 5. PostgreSQL: rotate messenger_worker password & terminate active worker sessions
|
||||
new_pg_pass="$(openssl rand -hex 24)"
|
||||
{
|
||||
printf "SET password_encryption = 'scram-sha-256';\n"
|
||||
printf "ALTER ROLE messenger_worker WITH LOGIN PASSWORD '%s';\n" "$new_pg_pass"
|
||||
printf "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'messenger_worker' AND pid <> pg_backend_pid();\n"
|
||||
} | "${COMPOSE[@]}" exec -T postgres psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -v ON_ERROR_STOP=1 >/dev/null
|
||||
|
||||
# 6. MinIO: add new scoped worker IAM user & immediately remove old compromised IAM user (HTTPS + CA)
|
||||
new_s3_key="worker-$(openssl rand -hex 8)"
|
||||
new_s3_sec="$(openssl rand -hex 24)"
|
||||
|
||||
s3_cid="$("${COMPOSE[@]}" ps -q s3 | head -n 1)"
|
||||
app_data_net="$(docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$s3_cid" \
|
||||
| tr ' ' '\n' | grep '_app_data$' | head -n 1)"
|
||||
|
||||
printf '%s\n%s\n%s\n' "$new_s3_key" "$new_s3_sec" "$old_s3_key" \
|
||||
| docker run --rm -i \
|
||||
--network "$app_data_net" \
|
||||
--user 1000:1000 \
|
||||
--read-only \
|
||||
--cap-drop ALL \
|
||||
--security-opt no-new-privileges:true \
|
||||
--tmpfs /tmp:size=16m,noexec,nosuid,nodev \
|
||||
-v "$(pwd)/secrets/pki/ca.crt:/run/certs/ca.crt:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_user:/run/secrets/minio_root_user:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_password:/run/secrets/minio_root_password:ro" \
|
||||
--entrypoint /bin/sh \
|
||||
"$MC_IMAGE" -c '
|
||||
set -eu
|
||||
IFS= read -r ru < /run/secrets/minio_root_user || [ -n "$ru" ]
|
||||
IFS= read -r rp < /run/secrets/minio_root_password || [ -n "$rp" ]
|
||||
IFS= read -r nk; IFS= read -r ns; IFS= read -r ok || true
|
||||
export HOME=/tmp MC_CONFIG_DIR=/tmp/.mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
export MC_HOST_stand="https://${ru}:${rp}@s3:9000"
|
||||
mc admin user add stand "$nk" "$ns" >/dev/null
|
||||
mc admin policy attach stand messenger-worker --user "$nk" >/dev/null
|
||||
if [ -n "$ok" ] && [ "$ok" != "$nk" ]; then
|
||||
mc admin user remove stand "$ok" >/dev/null 2>&1 || true
|
||||
fi
|
||||
'
|
||||
|
||||
# 7. Write OpenBao KV v2 version N+1 for messenger/worker
|
||||
kv_ver="$(jq -n \
|
||||
--arg db_pass "$new_pg_pass" \
|
||||
--arg s3_key "$new_s3_key" \
|
||||
--arg s3_sec "$new_s3_sec" \
|
||||
--arg broker_user "$NEW_CN" \
|
||||
'{
|
||||
data: {
|
||||
db_user: "messenger_worker",
|
||||
db_password: $db_pass,
|
||||
s3_access_key_id: $s3_key,
|
||||
s3_secret_access_key: $s3_sec,
|
||||
broker_user: $broker_user
|
||||
}
|
||||
}' \
|
||||
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/secret/data/messenger/worker" \
|
||||
| jq -r '.data.version')"
|
||||
|
||||
# 8. Recover worker without image rebuild (unless --no-start was requested)
|
||||
worker_started="false"
|
||||
if [ "$NO_START" -eq 0 ]; then
|
||||
if [ -n "$("${COMPOSE[@]}" ps -q --status running worker 2>/dev/null || true)" ]; then
|
||||
"${COMPOSE[@]}" restart worker >/dev/null
|
||||
fi
|
||||
"${COMPOSE[@]}" up -d --no-build --no-deps --wait worker >/dev/null
|
||||
worker_started="true"
|
||||
fi
|
||||
|
||||
echo "revoke-worker ok: old_cn=${OLD_CN} new_cn=${NEW_CN} old_serial=${OLD_SERIAL} new_serial=${NEW_SERIAL} revoked_accessors=${revoked_accessors} kv_version=${kv_ver} worker_started=${worker_started}"
|
||||
Executable
+405
@@ -0,0 +1,405 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Zero-Rebuild Leaf Certificate Rotation & CRL Revocation.
|
||||
# Modes:
|
||||
# 1. scripts/rotate-cert.sh <target> [--revoke] [--cn <new-cn>]
|
||||
# Rotates leaf cert atomically into ./secrets/pki/<svc>/, optionally revokes
|
||||
# old serial into OpenSSL CRL + distributes ca.crl + uploads CRL to OpenBao,
|
||||
# and triggers live reload (SIGHUP / SIGUSR2 / pg_reload_conf) with ZERO
|
||||
# image rebuild.
|
||||
# 2. scripts/rotate-cert.sh --revoke-cert <pem-path>
|
||||
# Revokes the given certificate PEM in operator CA DB, regenerates and
|
||||
# distributes ca.crl everywhere, uploads CRL to OpenBao, and reloads
|
||||
# CRL-enforcing services (api, haproxy, otel-gateway, postgres).
|
||||
# 3. scripts/rotate-cert.sh --issue-test-client <name> <cn> <san> <out-dir>
|
||||
# Issues a temporary CA-signed EKU=clientAuth leaf cert into <out-dir> for
|
||||
# safe revocation testing without disturbing production service certs.
|
||||
# Never prints private keys or tokens.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
PKI_OP_DIR="${OPERATOR_DIR}/pki"
|
||||
CA_CNF="${PKI_OP_DIR}/ca.cnf"
|
||||
OP_CERT="${OPERATOR_DIR}/operator/operator.crt"
|
||||
OP_KEY="${OPERATOR_DIR}/operator/operator.key"
|
||||
RUNTIME_PKI_DIR="$(pwd)/secrets/pki"
|
||||
CA_CERT="${RUNTIME_PKI_DIR}/ca.crt"
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
COMPOSE=(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}")
|
||||
|
||||
umask 077
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-rot-cert.XXXXXX")"
|
||||
OP_CFG="${TMP_DIR}/op-auth.cfg"
|
||||
cleanup() {
|
||||
if [ -s "$OP_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$TMP_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
atomic_install() {
|
||||
local src="$1"
|
||||
local dst="$2"
|
||||
local mode="$3"
|
||||
mkdir -p "$(dirname "$dst")"
|
||||
local tmp="${dst}.tmp.$$"
|
||||
cp "$src" "$tmp"
|
||||
chmod "$mode" "$tmp"
|
||||
mv -f "$tmp" "$dst"
|
||||
}
|
||||
|
||||
cert_serial() {
|
||||
openssl x509 -in "$1" -noout -serial | cut -d= -f2
|
||||
}
|
||||
|
||||
cert_fp256() {
|
||||
openssl x509 -in "$1" -noout -fingerprint -sha256 | cut -d= -f2
|
||||
}
|
||||
|
||||
cert_cn() {
|
||||
openssl x509 -in "$1" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p'
|
||||
}
|
||||
|
||||
is_running() {
|
||||
[ -n "$("${COMPOSE[@]}" ps -q --status running "$1" 2>/dev/null || true)" ]
|
||||
}
|
||||
|
||||
reload_service() {
|
||||
local svc="$1"
|
||||
local sig="$2"
|
||||
if is_running "$svc"; then
|
||||
"${COMPOSE[@]}" kill -s "$sig" "$svc" >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
refresh_postgres_tls() {
|
||||
if is_running postgres; then
|
||||
"${COMPOSE[@]}" exec -T postgres sh -c '
|
||||
set -eu
|
||||
d=/var/run/postgresql/certs
|
||||
mkdir -p "$d" && chmod 0700 "$d"
|
||||
for f in ca.crt ca.crl server.crt; do
|
||||
cp "/run/certs/$f" "$d/$f.tmp" && chmod 0644 "$d/$f.tmp" && mv -f "$d/$f.tmp" "$d/$f"
|
||||
done
|
||||
cp /run/certs/server.key "$d/server.key.tmp" && chmod 0600 "$d/server.key.tmp" && mv -f "$d/server.key.tmp" "$d/server.key"
|
||||
psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -c "SELECT pg_reload_conf();" >/dev/null
|
||||
' >/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
upload_crl_to_openbao() {
|
||||
[ -s "$CA_CERT" ] && [ -s "$OP_CERT" ] && [ -s "$OP_KEY" ] || return 0
|
||||
local seal_json sealed
|
||||
seal_json="$(curl -fsS --cacert "$CA_CERT" "${BAO_ADDR}/v1/sys/seal-status" 2>/dev/null || true)"
|
||||
sealed="$(printf '%s' "$seal_json" | jq -r '.sealed // "true"' 2>/dev/null || echo true)"
|
||||
if [ "$sealed" != "false" ]; then
|
||||
return 0
|
||||
fi
|
||||
local login_json op_token
|
||||
login_json="$(curl -fsS --cacert "$CA_CERT" --cert "$OP_CERT" --key "$OP_KEY" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${BAO_ADDR}/v1/auth/cert/login" 2>/dev/null || true)"
|
||||
op_token="$(printf '%s' "$login_json" | jq -r '.auth.client_token // empty' 2>/dev/null || true)"
|
||||
[ -n "$op_token" ] || return 0
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$op_token" > "$OP_CFG"
|
||||
chmod 0600 "$OP_CFG"
|
||||
jq -Rs '{crl: .}' < "${PKI_OP_DIR}/ca.crl" \
|
||||
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/auth/cert/crls/lab7-ca" >/dev/null
|
||||
}
|
||||
|
||||
regenerate_and_distribute_crl() {
|
||||
openssl ca -batch -config "$CA_CNF" -gencrl -out "${TMP_DIR}/ca.crl" >/dev/null 2>&1
|
||||
atomic_install "${TMP_DIR}/ca.crl" "${PKI_OP_DIR}/ca.crl" 0644
|
||||
atomic_install "${TMP_DIR}/ca.crl" "${RUNTIME_PKI_DIR}/ca.crl" 0644
|
||||
for svc in haproxy api worker migrate postgres redis broker otel-gateway prometheus openbao; do
|
||||
if [ -d "${RUNTIME_PKI_DIR}/${svc}" ]; then
|
||||
atomic_install "${TMP_DIR}/ca.crl" "${RUNTIME_PKI_DIR}/${svc}/ca.crl" 0644
|
||||
fi
|
||||
done
|
||||
upload_crl_to_openbao
|
||||
refresh_postgres_tls
|
||||
reload_service api HUP
|
||||
reload_service haproxy USR2
|
||||
reload_service otel-gateway USR2
|
||||
}
|
||||
|
||||
revoke_pem() {
|
||||
local pem="$1"
|
||||
if [ ! -s "$pem" ]; then
|
||||
echo "error: certificate not found for revocation: ${pem}" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Revoke (ignore "Already revoked" error cleanly for idempotency)
|
||||
local err_file="${TMP_DIR}/revoke.err"
|
||||
if ! openssl ca -batch -config "$CA_CNF" -revoke "$pem" 2>"$err_file"; then
|
||||
if ! grep -qi "Already revoked" "$err_file"; then
|
||||
cat "$err_file" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
issue_new_leaf() {
|
||||
local kind="$1"
|
||||
local cn="$2"
|
||||
local san="$3"
|
||||
local out_crt="$4"
|
||||
local out_key="$5"
|
||||
local key_mode="$6"
|
||||
|
||||
local ext_section="v3_server"
|
||||
[ "$kind" = "client" ] && ext_section="v3_client"
|
||||
|
||||
local req_cnf="${TMP_DIR}/leaf.req.cnf"
|
||||
local key_tmp="${TMP_DIR}/leaf.key"
|
||||
local csr_tmp="${TMP_DIR}/leaf.csr"
|
||||
local crt_tmp="${TMP_DIR}/leaf.crt"
|
||||
|
||||
cat > "$req_cnf" <<EOF
|
||||
[ req ]
|
||||
default_md = sha256
|
||||
distinguished_name = dn
|
||||
req_extensions = req_ext
|
||||
prompt = no
|
||||
|
||||
[ dn ]
|
||||
O = mtusi-lab7
|
||||
CN = ${cn}
|
||||
|
||||
[ req_ext ]
|
||||
subjectAltName = ${san}
|
||||
EOF
|
||||
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "$key_tmp"
|
||||
openssl req -new -sha256 -key "$key_tmp" -config "$req_cnf" -out "$csr_tmp"
|
||||
openssl ca -batch -notext -config "$CA_CNF" -extensions "$ext_section" \
|
||||
-in "$csr_tmp" -out "$crt_tmp" >/dev/null 2>&1
|
||||
|
||||
atomic_install "$crt_tmp" "$out_crt" 0644
|
||||
atomic_install "$key_tmp" "$out_key" "$key_mode"
|
||||
}
|
||||
|
||||
update_otel_cn_allowlist() {
|
||||
local old_cn="$1"
|
||||
local new_cn="$2"
|
||||
local list_file="${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-cn.lst"
|
||||
[ -f "$list_file" ] || return 0
|
||||
local tmp="${TMP_DIR}/allowed-otlp-cn.lst"
|
||||
grep -Fxv "$old_cn" "$list_file" > "$tmp" || true
|
||||
if ! grep -Fxq "$new_cn" "$tmp"; then
|
||||
printf '%s\n' "$new_cn" >> "$tmp"
|
||||
fi
|
||||
atomic_install "$tmp" "$list_file" 0644
|
||||
reload_service otel-gateway USR2
|
||||
}
|
||||
|
||||
if [ $# -lt 1 ]; then
|
||||
echo "Usage: $0 <target> [--revoke] [--cn <new-cn>] | --revoke-cert <pem> | --issue-test-client <name> <cn> <san> <out-dir>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Mode 2: standalone PEM revocation
|
||||
if [ "$1" = "--revoke-cert" ]; then
|
||||
pem="${2:?missing pem path}"
|
||||
ser="$(cert_serial "$pem")"
|
||||
revoke_pem "$pem"
|
||||
regenerate_and_distribute_crl
|
||||
echo "revoke-cert ok: serial=${ser} crl_updated=true"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Mode 3: issue temporary test client cert
|
||||
if [ "$1" = "--issue-test-client" ]; then
|
||||
t_name="${2:?missing name}"
|
||||
t_cn="${3:?missing cn}"
|
||||
t_san="${4:?missing san}"
|
||||
t_dir="${5:?missing out-dir}"
|
||||
mkdir -p "$t_dir"
|
||||
issue_new_leaf client "$t_cn" "$t_san" "${t_dir}/${t_name}.crt" "${t_dir}/${t_name}.key" 0644
|
||||
cat "${t_dir}/${t_name}.crt" "${t_dir}/${t_name}.key" > "${TMP_DIR}/test.pem"
|
||||
atomic_install "${TMP_DIR}/test.pem" "${t_dir}/${t_name}.pem" 0644
|
||||
echo "issue-test-client ok: name=${t_name} cn=${t_cn} serial=$(cert_serial "${t_dir}/${t_name}.crt") fingerprint=$(cert_fp256 "${t_dir}/${t_name}.crt")"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Mode 1: rotate named target leaf cert
|
||||
TARGET="$1"
|
||||
shift
|
||||
REVOKE=0
|
||||
NEW_CN=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--revoke) REVOKE=1 ;;
|
||||
--cn)
|
||||
shift
|
||||
NEW_CN="${1:?missing value for --cn}"
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 <target> [--revoke] [--cn <new-cn>]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
kind="" cn="" san="" crt_path="" key_path="" bundle_path="" key_mode="0644" reload_svc="" reload_sig=""
|
||||
case "$TARGET" in
|
||||
api|api-server)
|
||||
kind=server; cn="api"; san="DNS:api"
|
||||
crt_path="${RUNTIME_PKI_DIR}/api/server.crt"; key_path="${RUNTIME_PKI_DIR}/api/server.key"
|
||||
reload_svc="api"; reload_sig="HUP"
|
||||
;;
|
||||
api-client)
|
||||
kind=client; cn="messenger-api-g1"; san="DNS:messenger-api"
|
||||
crt_path="${RUNTIME_PKI_DIR}/api/client.crt"; key_path="${RUNTIME_PKI_DIR}/api/client.key"
|
||||
reload_svc="api"; reload_sig="HUP"
|
||||
;;
|
||||
worker|worker-client)
|
||||
kind=client; cn="messenger-worker-g1"; san="DNS:messenger-worker"
|
||||
crt_path="${RUNTIME_PKI_DIR}/worker/client.crt"; key_path="${RUNTIME_PKI_DIR}/worker/client.key"
|
||||
reload_svc="worker"; reload_sig="HUP"
|
||||
;;
|
||||
migrate|migrator-client)
|
||||
kind=client; cn="messenger-migrator-g1"; san="DNS:messenger-migrator"
|
||||
crt_path="${RUNTIME_PKI_DIR}/migrate/client.crt"; key_path="${RUNTIME_PKI_DIR}/migrate/client.key"
|
||||
;;
|
||||
haproxy|haproxy-ingress|haproxy-server)
|
||||
kind=server; cn="localhost"; san="DNS:localhost,DNS:haproxy"
|
||||
crt_path="${RUNTIME_PKI_DIR}/haproxy/server.crt"; key_path="${RUNTIME_PKI_DIR}/haproxy/server.key"
|
||||
bundle_path="${RUNTIME_PKI_DIR}/haproxy/server.pem"
|
||||
reload_svc="haproxy"; reload_sig="USR2"
|
||||
;;
|
||||
haproxy-client)
|
||||
kind=client; cn="haproxy-lb-g1"; san="DNS:haproxy-lb"
|
||||
crt_path="${RUNTIME_PKI_DIR}/haproxy/client.crt"; key_path="${RUNTIME_PKI_DIR}/haproxy/client.key"
|
||||
bundle_path="${RUNTIME_PKI_DIR}/haproxy/client.pem"
|
||||
reload_svc="haproxy"; reload_sig="USR2"
|
||||
;;
|
||||
postgres)
|
||||
kind=server; cn="postgres"; san="DNS:postgres,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/postgres/server.crt"; key_path="${RUNTIME_PKI_DIR}/postgres/server.key"
|
||||
reload_svc="postgres"; reload_sig="PG"
|
||||
;;
|
||||
redis)
|
||||
kind=server; cn="redis"; san="DNS:redis,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/redis/server.crt"; key_path="${RUNTIME_PKI_DIR}/redis/server.key"
|
||||
;;
|
||||
s3)
|
||||
kind=server; cn="s3"; san="DNS:s3,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/s3/public.crt"; key_path="${RUNTIME_PKI_DIR}/s3/private.key"
|
||||
;;
|
||||
broker)
|
||||
kind=server; cn="broker"; san="DNS:broker"
|
||||
crt_path="${RUNTIME_PKI_DIR}/broker/server.crt"; key_path="${RUNTIME_PKI_DIR}/broker/server.key"
|
||||
;;
|
||||
otel-gateway)
|
||||
kind=server; cn="otel-collector"; san="DNS:otel-collector,DNS:otel-gateway"
|
||||
crt_path="${RUNTIME_PKI_DIR}/otel-gateway/server.crt"; key_path="${RUNTIME_PKI_DIR}/otel-gateway/server.key"
|
||||
bundle_path="${RUNTIME_PKI_DIR}/otel-gateway/server.pem"
|
||||
reload_svc="otel-gateway"; reload_sig="USR2"
|
||||
;;
|
||||
otel-collector)
|
||||
kind=client; cn="otel-collector"; san="DNS:otel-collector"
|
||||
crt_path="${RUNTIME_PKI_DIR}/otel-collector/client.crt"; key_path="${RUNTIME_PKI_DIR}/otel-collector/client.key"
|
||||
;;
|
||||
prometheus)
|
||||
kind=server; cn="prometheus"; san="DNS:prometheus,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/prometheus/server.crt"; key_path="${RUNTIME_PKI_DIR}/prometheus/server.key"
|
||||
reload_svc="prometheus"; reload_sig="HUP"
|
||||
;;
|
||||
prometheus-client)
|
||||
kind=client; cn="prometheus"; san="DNS:prometheus"
|
||||
crt_path="${RUNTIME_PKI_DIR}/prometheus/client.crt"; key_path="${RUNTIME_PKI_DIR}/prometheus/client.key"
|
||||
reload_svc="prometheus"; reload_sig="HUP"
|
||||
;;
|
||||
loki)
|
||||
kind=server; cn="loki"; san="DNS:loki"
|
||||
crt_path="${RUNTIME_PKI_DIR}/loki/server.crt"; key_path="${RUNTIME_PKI_DIR}/loki/server.key"
|
||||
;;
|
||||
tempo)
|
||||
kind=server; cn="tempo"; san="DNS:tempo"
|
||||
crt_path="${RUNTIME_PKI_DIR}/tempo/server.crt"; key_path="${RUNTIME_PKI_DIR}/tempo/server.key"
|
||||
;;
|
||||
grafana)
|
||||
kind=server; cn="grafana"; san="DNS:grafana,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/grafana/server.crt"; key_path="${RUNTIME_PKI_DIR}/grafana/server.key"
|
||||
;;
|
||||
grafana-client)
|
||||
kind=client; cn="grafana"; san="DNS:grafana"
|
||||
crt_path="${RUNTIME_PKI_DIR}/grafana/client.crt"; key_path="${RUNTIME_PKI_DIR}/grafana/client.key"
|
||||
;;
|
||||
openbao)
|
||||
kind=server; cn="openbao"; san="DNS:openbao,DNS:localhost,IP:127.0.0.1"
|
||||
crt_path="${RUNTIME_PKI_DIR}/openbao/server.crt"; key_path="${RUNTIME_PKI_DIR}/openbao/server.key"
|
||||
reload_svc="openbao"; reload_sig="HUP"
|
||||
;;
|
||||
operator)
|
||||
kind=client; cn="messenger-operator-g1"; san="DNS:messenger-operator"
|
||||
crt_path="${OP_CERT}"; key_path="${OP_KEY}"; key_mode="0600"
|
||||
;;
|
||||
rogue-client)
|
||||
kind=client; cn="rogue-client"; san="DNS:rogue-client"
|
||||
crt_path="${PKI_OP_DIR}/rogue-client.crt"; key_path="${PKI_OP_DIR}/rogue-client.key"; key_mode="0600"
|
||||
;;
|
||||
*)
|
||||
echo "error: unknown cert target '${TARGET}'" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
old_serial="none"
|
||||
old_cn=""
|
||||
if [ -s "$crt_path" ]; then
|
||||
old_serial="$(cert_serial "$crt_path")"
|
||||
old_cn="$(cert_cn "$crt_path")"
|
||||
cp "$crt_path" "${TMP_DIR}/old.crt"
|
||||
fi
|
||||
|
||||
if [ -n "$NEW_CN" ]; then
|
||||
cn="$NEW_CN"
|
||||
elif [ -n "$old_cn" ]; then
|
||||
cn="$old_cn"
|
||||
fi
|
||||
|
||||
issue_new_leaf "$kind" "$cn" "$san" "$crt_path" "$key_path" "$key_mode"
|
||||
if [ -n "$bundle_path" ]; then
|
||||
cat "$crt_path" "$key_path" > "${TMP_DIR}/bundle.pem"
|
||||
atomic_install "${TMP_DIR}/bundle.pem" "$bundle_path" 0644
|
||||
fi
|
||||
|
||||
if [ -n "$old_cn" ] && [ "$old_cn" != "$cn" ]; then
|
||||
case "$TARGET" in
|
||||
api-client|worker|worker-client)
|
||||
update_otel_cn_allowlist "$old_cn" "$cn"
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
if [ "$REVOKE" -eq 1 ] && [ -s "${TMP_DIR}/old.crt" ]; then
|
||||
revoke_pem "${TMP_DIR}/old.crt"
|
||||
regenerate_and_distribute_crl
|
||||
fi
|
||||
|
||||
if [ "$reload_svc" = "postgres" ]; then
|
||||
refresh_postgres_tls
|
||||
elif [ -n "$reload_svc" ] && [ -n "$reload_sig" ]; then
|
||||
reload_service "$reload_svc" "$reload_sig"
|
||||
fi
|
||||
|
||||
new_serial="$(cert_serial "$crt_path")"
|
||||
new_fp="$(cert_fp256 "$crt_path")"
|
||||
echo "rotate-cert ok: target=${TARGET} cn=${cn} old_serial=${old_serial} new_serial=${new_serial} fingerprint=${new_fp} revoked=$([ "$REVOKE" -eq 1 ] && echo true || echo false)"
|
||||
Executable
+248
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Zero-Rebuild Working Secret Rotation (operator mTLS auth, zero root token).
|
||||
# Usage: scripts/rotate-secret.sh [api-db|api-redis|api-s3|worker-db|worker-s3|migrator-db|api|worker]
|
||||
# Rotates credential in both live backend store AND OpenBao KV v2, then signals
|
||||
# SIGHUP to running workload(s) for immediate live pickup without image rebuild.
|
||||
# Never prints secret values.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
TARGET="${1:-api-db}"
|
||||
case "$TARGET" in
|
||||
api-db|api-redis|api-s3|worker-db|worker-s3|migrator-db|api|worker) ;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [api-db|api-redis|api-s3|worker-db|worker-s3|migrator-db|api|worker]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "error: unknown rotation target '${TARGET}'" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
OP_CERT="${OPERATOR_DIR}/operator/operator.crt"
|
||||
OP_KEY="${OPERATOR_DIR}/operator/operator.key"
|
||||
CA_CERT="${CA_FILE:-$(pwd)/secrets/pki/ca.crt}"
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
COMPOSE=(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}")
|
||||
MC_IMAGE="minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727"
|
||||
|
||||
umask 077
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-rot-sec.XXXXXX")"
|
||||
OP_CFG="${TMP_DIR}/op-auth.cfg"
|
||||
cleanup() {
|
||||
if [ -s "$OP_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$TMP_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
login_json="$(curl -fsS --cacert "$CA_CERT" --cert "$OP_CERT" --key "$OP_KEY" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${BAO_ADDR}/v1/auth/cert/login")"
|
||||
op_token="$(printf '%s' "$login_json" | jq -r '.auth.client_token // empty')"
|
||||
if [ -z "$op_token" ]; then
|
||||
echo "error: operator mTLS auth to OpenBao failed" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$op_token" > "$OP_CFG"
|
||||
chmod 0600 "$OP_CFG"
|
||||
unset login_json op_token
|
||||
|
||||
read_kv() {
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" "${BAO_ADDR}/v1/secret/data/${1}" | jq -c '.data.data'
|
||||
}
|
||||
|
||||
write_kv() {
|
||||
local path="$1"
|
||||
local data_json="$2"
|
||||
printf '%s' "$data_json" \
|
||||
| jq '{data: .}' \
|
||||
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/secret/data/${path}" \
|
||||
| jq -r '.data.version'
|
||||
}
|
||||
|
||||
rotate_pg_role() {
|
||||
local role="$1"
|
||||
local new_pass="$2"
|
||||
{
|
||||
printf "SET password_encryption = 'scram-sha-256';\n"
|
||||
printf "ALTER ROLE %s WITH LOGIN PASSWORD '%s';\n" "$role" "$new_pass"
|
||||
} | "${COMPOSE[@]}" exec -T postgres psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -v ON_ERROR_STOP=1 >/dev/null
|
||||
}
|
||||
|
||||
rotate_redis_api() {
|
||||
local new_pass="$1"
|
||||
printf 'ACL SETUSER messenger_api reset on >%s ~session:sha256:* ~messages:* ~lock:messages:* ~rl:* ~fault:* -@all +ping +hello +client|setinfo +quit +get +set +del +incr +expire +pexpire +ttl +pttl +@scripting +multi +exec +discard\nACL SAVE\n' \
|
||||
"$new_pass" \
|
||||
| "${COMPOSE[@]}" exec -T redis sh -c \
|
||||
'REDISCLI_AUTH="$(cat /run/secrets/redis_admin_password)" redis-cli --tls --cacert /run/certs/ca.crt --cert /run/certs/health.crt --key /run/certs/health.key --user redis_admin -h localhost -p 6379 >/dev/null'
|
||||
}
|
||||
|
||||
minio_exec() {
|
||||
local s3_cid app_data_net
|
||||
s3_cid="$("${COMPOSE[@]}" ps -q s3 | head -n 1)"
|
||||
app_data_net="$(docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$s3_cid" \
|
||||
| tr ' ' '\n' | grep '_app_data$' | head -n 1)"
|
||||
docker run --rm -i \
|
||||
--network "$app_data_net" \
|
||||
--user 1000:1000 \
|
||||
--read-only \
|
||||
--cap-drop ALL \
|
||||
--security-opt no-new-privileges:true \
|
||||
--tmpfs /tmp:size=16m,noexec,nosuid,nodev \
|
||||
-v "$(pwd)/secrets/pki/ca.crt:/run/certs/ca.crt:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_user:/run/secrets/minio_root_user:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_password:/run/secrets/minio_root_password:ro" \
|
||||
--entrypoint /bin/sh \
|
||||
"$MC_IMAGE" -c "$1"
|
||||
}
|
||||
|
||||
add_minio_user() {
|
||||
local policy="$1"
|
||||
local user="$2"
|
||||
local secret="$3"
|
||||
printf '%s\n%s\n%s\n' "$policy" "$user" "$secret" | minio_exec '
|
||||
set -eu
|
||||
IFS= read -r ru < /run/secrets/minio_root_user || [ -n "$ru" ]
|
||||
IFS= read -r rp < /run/secrets/minio_root_password || [ -n "$rp" ]
|
||||
IFS= read -r pol; IFS= read -r u; IFS= read -r s
|
||||
export HOME=/tmp MC_CONFIG_DIR=/tmp/.mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
export MC_HOST_stand="https://${ru}:${rp}@s3:9000"
|
||||
mc admin user add stand "$u" "$s" >/dev/null
|
||||
mc admin policy attach stand "$pol" --user "$u" >/dev/null
|
||||
'
|
||||
}
|
||||
|
||||
remove_minio_user() {
|
||||
local old_user="$1"
|
||||
[ -n "$old_user" ] || return 0
|
||||
printf '%s\n' "$old_user" | minio_exec '
|
||||
set -eu
|
||||
IFS= read -r ru < /run/secrets/minio_root_user || [ -n "$ru" ]
|
||||
IFS= read -r rp < /run/secrets/minio_root_password || [ -n "$rp" ]
|
||||
IFS= read -r u
|
||||
export HOME=/tmp MC_CONFIG_DIR=/tmp/.mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
export MC_HOST_stand="https://${ru}:${rp}@s3:9000"
|
||||
mc admin user remove stand "$u" >/dev/null 2>&1 || true
|
||||
'
|
||||
}
|
||||
|
||||
signal_service() {
|
||||
local svc="$1"
|
||||
if [ -n "$("${COMPOSE[@]}" ps -q --status running "$svc" 2>/dev/null)" ]; then
|
||||
"${COMPOSE[@]}" kill -s HUP "$svc" >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
kv_ver=""
|
||||
case "$TARGET" in
|
||||
api-db)
|
||||
cur="$(read_kv messenger/api)"
|
||||
new_pass="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_api "$new_pass"
|
||||
updated="$(printf '%s' "$cur" | jq --arg p "$new_pass" '.db_password = $p')"
|
||||
kv_ver="$(write_kv messenger/api "$updated")"
|
||||
signal_service api
|
||||
;;
|
||||
api-redis)
|
||||
cur="$(read_kv messenger/api)"
|
||||
new_pass="$(openssl rand -hex 24)"
|
||||
rotate_redis_api "$new_pass"
|
||||
updated="$(printf '%s' "$cur" | jq --arg p "$new_pass" '.redis_password = $p')"
|
||||
kv_ver="$(write_kv messenger/api "$updated")"
|
||||
signal_service api
|
||||
;;
|
||||
api-s3)
|
||||
cur="$(read_kv messenger/api)"
|
||||
old_key="$(printf '%s' "$cur" | jq -r '.s3_access_key_id')"
|
||||
new_key="api-$(openssl rand -hex 8)"
|
||||
new_sec="$(openssl rand -hex 24)"
|
||||
add_minio_user messenger-api "$new_key" "$new_sec"
|
||||
updated="$(printf '%s' "$cur" | jq --arg k "$new_key" --arg s "$new_sec" '.s3_access_key_id = $k | .s3_secret_access_key = $s')"
|
||||
kv_ver="$(write_kv messenger/api "$updated")"
|
||||
signal_service api
|
||||
sleep 2
|
||||
remove_minio_user "$old_key"
|
||||
;;
|
||||
api)
|
||||
cur="$(read_kv messenger/api)"
|
||||
old_key="$(printf '%s' "$cur" | jq -r '.s3_access_key_id')"
|
||||
new_db="$(openssl rand -hex 24)"
|
||||
new_redis="$(openssl rand -hex 24)"
|
||||
new_key="api-$(openssl rand -hex 8)"
|
||||
new_sec="$(openssl rand -hex 24)"
|
||||
new_metrics="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_api "$new_db"
|
||||
rotate_redis_api "$new_redis"
|
||||
add_minio_user messenger-api "$new_key" "$new_sec"
|
||||
updated="$(printf '%s' "$cur" | jq \
|
||||
--arg db "$new_db" --arg rd "$new_redis" \
|
||||
--arg k "$new_key" --arg s "$new_sec" --arg m "$new_metrics" \
|
||||
'.db_password=$db | .redis_password=$rd | .s3_access_key_id=$k | .s3_secret_access_key=$s | .metrics_token=$m')"
|
||||
kv_ver="$(write_kv messenger/api "$updated")"
|
||||
signal_service api
|
||||
sleep 2
|
||||
remove_minio_user "$old_key"
|
||||
;;
|
||||
worker-db)
|
||||
cur="$(read_kv messenger/worker)"
|
||||
new_pass="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_worker "$new_pass"
|
||||
updated="$(printf '%s' "$cur" | jq --arg p "$new_pass" '.db_password = $p')"
|
||||
kv_ver="$(write_kv messenger/worker "$updated")"
|
||||
signal_service worker
|
||||
;;
|
||||
worker-s3)
|
||||
cur="$(read_kv messenger/worker)"
|
||||
old_key="$(printf '%s' "$cur" | jq -r '.s3_access_key_id')"
|
||||
new_key="worker-$(openssl rand -hex 8)"
|
||||
new_sec="$(openssl rand -hex 24)"
|
||||
add_minio_user messenger-worker "$new_key" "$new_sec"
|
||||
updated="$(printf '%s' "$cur" | jq --arg k "$new_key" --arg s "$new_sec" '.s3_access_key_id = $k | .s3_secret_access_key = $s')"
|
||||
kv_ver="$(write_kv messenger/worker "$updated")"
|
||||
signal_service worker
|
||||
sleep 2
|
||||
remove_minio_user "$old_key"
|
||||
;;
|
||||
worker)
|
||||
cur="$(read_kv messenger/worker)"
|
||||
old_key="$(printf '%s' "$cur" | jq -r '.s3_access_key_id')"
|
||||
new_db="$(openssl rand -hex 24)"
|
||||
new_key="worker-$(openssl rand -hex 8)"
|
||||
new_sec="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_worker "$new_db"
|
||||
add_minio_user messenger-worker "$new_key" "$new_sec"
|
||||
updated="$(printf '%s' "$cur" | jq \
|
||||
--arg db "$new_db" --arg k "$new_key" --arg s "$new_sec" \
|
||||
'.db_password=$db | .s3_access_key_id=$k | .s3_secret_access_key=$s')"
|
||||
kv_ver="$(write_kv messenger/worker "$updated")"
|
||||
signal_service worker
|
||||
sleep 2
|
||||
remove_minio_user "$old_key"
|
||||
;;
|
||||
migrator-db)
|
||||
cur="$(read_kv messenger/migrator)"
|
||||
new_pass="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_migrator "$new_pass"
|
||||
updated="$(printf '%s' "$cur" | jq --arg p "$new_pass" '.db_password = $p')"
|
||||
kv_ver="$(write_kv messenger/migrator "$updated")"
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "rotate-secret ok: target=${TARGET} kv_version=${kv_ver}"
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# Восстанавливает недостающую API-реплику до объявленного числа реплик.
|
||||
# Восстанавливает недостающую API-реплику до объявленного числа реплик без пересборки образа.
|
||||
set -eu
|
||||
|
||||
env_file="${COMPOSE_ENV_FILE:-.env}"
|
||||
@@ -8,4 +8,4 @@ if [ -z "$replicas" ] && [ -f "$env_file" ]; then
|
||||
replicas=$(sed -n 's/^API_REPLICAS=//p' "$env_file" | tail -n 1)
|
||||
fi
|
||||
replicas="${replicas:-2}"
|
||||
exec docker compose --env-file "$env_file" up -d --no-deps --scale "api=${replicas}" api
|
||||
exec docker compose --env-file "$env_file" up -d --no-build --no-deps --wait --scale "api=${replicas}" api
|
||||
|
||||
+11
-8
@@ -1,10 +1,8 @@
|
||||
#!/bin/sh
|
||||
# Останавливает ровно одну API-реплику стенда — ту, которую обслужила текущая
|
||||
# сессия. TARGET_INSTANCE_ID приходит из теста (значение X-Instance-Id ответа),
|
||||
# а в Docker hostname контейнера равен его короткому ID, поэтому сопоставление
|
||||
# однозначно. Ничего, кроме этой реплики, скрипт не трогает: ни LB, ни БД, ни
|
||||
# тома. Возврат управления — быстрый (SIGTERM -> дрейн DRAIN_DELAY_MS=3s ->
|
||||
# выход), останавливать реплику "навсегда" не требуется.
|
||||
# Останавливает ровно одну API-реплику стенда — ту, которая обслужила текущую
|
||||
# сессию. В lab7 X-Instance-Id — непрозрачный случайный алиас (без hostname/IP),
|
||||
# который API записывает в /tmp/instance-id внутри tmpfs контейнера.
|
||||
# Ничего, кроме целевой реплики, скрипт не трогает.
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
@@ -17,6 +15,11 @@ for container in $(
|
||||
--filter 'label=com.docker.compose.service=api' \
|
||||
--format '{{.ID}}'
|
||||
); do
|
||||
alias_val="$(docker exec "$container" cat /tmp/instance-id 2>/dev/null || true)"
|
||||
if [ -n "$alias_val" ] && [ "$alias_val" = "$TARGET_INSTANCE_ID" ]; then
|
||||
target="$container"
|
||||
break
|
||||
fi
|
||||
case "$container" in
|
||||
"$TARGET_INSTANCE_ID"*)
|
||||
target="$container"
|
||||
@@ -26,10 +29,10 @@ for container in $(
|
||||
done
|
||||
|
||||
if [ -z "$target" ]; then
|
||||
printf 'stop-one: no running api replica of project %s whose id starts with %s\n' \
|
||||
printf 'stop-one: no running api replica of project %s matching instance alias %s\n' \
|
||||
"$project" "$TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf 'stop-one: stopping api replica %s\n' "$target" >&2
|
||||
printf 'stop-one: stopping api replica %s (alias=%s)\n' "$target" "$TARGET_INSTANCE_ID" >&2
|
||||
docker stop --time 10 "$target" >/dev/null
|
||||
|
||||
Reference in New Issue
Block a user