forked from mtusi2026/mtusi2026lab7
lab7: PKI, mTLS infra, OpenBao non-dev, hardening, lifecycle scripts
This commit is contained in:
+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:
|
||||
|
||||
Reference in New Issue
Block a user