Защита стенда и управление секретами через OpenBao

This commit is contained in:
EgorAnti
2026-11-25 19:36:12 +03:00
parent 20afc2c790
commit d23847f953
159 changed files with 9135 additions and 82 deletions
+27
View File
@@ -0,0 +1,27 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetBucketLocation",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__/attachments/*",
"arn:aws:s3:::__S3_BUCKET__/staging/*"
]
}
]
}
+115
View File
@@ -0,0 +1,115 @@
worker_processes auto;
worker_shutdown_timeout 10s;
events {
worker_connections 1024;
}
http {
# Let the application enforce the exact 10 MiB contract and return JSON.
client_max_body_size 11m;
client_body_timeout 10s;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log warn;
# Docker embedded DNS returns current Compose replicas. Nginx OSS 1.27.3+
# refreshes these addresses without a configuration reload.
resolver 127.0.0.11 valid=2s ipv6=off;
resolver_timeout 1s;
upstream api_backend {
zone api_backend 64k;
least_conn;
server api:8443 resolve max_fails=1 fail_timeout=2s;
keepalive 32;
}
server {
listen 8443 ssl;
server_name localhost;
ssl_certificate /run/pki/ingress/tls.crt;
ssl_certificate_key /run/pki/ingress/tls.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_tickets off;
add_header Strict-Transport-Security "max-age=31536000" always;
proxy_ssl_certificate /run/pki/lb/tls.crt;
proxy_ssl_certificate_key /run/pki/lb/tls.key;
proxy_ssl_trusted_certificate /run/pki/service-ca/ca.crt;
proxy_ssl_verify on;
proxy_ssl_verify_depth 2;
proxy_ssl_server_name on;
proxy_ssl_name api;
proxy_intercept_errors on;
error_page 502 503 504 = @no_ready_api;
location = /nginx-health {
access_log off;
default_type application/json;
return 200 '{"status":"ok"}';
}
# After both peers have refused traffic or become unreachable, Nginx
# would normally emit its own HTML 502. Keep the public API contract:
# no ready backend is a JSON 503 with the required tracing headers.
location @no_ready_api {
internal;
default_type application/json;
add_header X-Request-Id $request_id always;
add_header X-Instance-Id nginx always;
add_header Cache-Control "no-store" always;
return 503 '{"error":{"code":"unavailable","message":"No ready API backend","request_id":"$request_id"}}';
}
# Message POST is the only non-idempotent HTTP method that is safe to
# replay here: the API requires Idempotency-Key and commits the message
# together with its shared PostgreSQL idempotency record.
location ~ ^/api/v1/chats/[0-9a-fA-F-]+/messages$ {
proxy_pass https://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_request_buffering on;
proxy_connect_timeout 500ms;
proxy_send_timeout 4s;
proxy_read_timeout 4s;
proxy_next_upstream error timeout http_502 http_503 http_504 non_idempotent;
proxy_next_upstream_tries 2;
}
location ~ ^/api/v1/chats/[0-9a-fA-F-]+/attachments$ {
proxy_pass https://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_request_buffering on;
proxy_connect_timeout 500ms;
proxy_send_timeout 20s;
proxy_read_timeout 20s;
# Upload is not replayed: it has no idempotency key. The client may retry explicitly.
proxy_next_upstream off;
}
location / {
proxy_pass https://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 500ms;
proxy_send_timeout 4s;
proxy_read_timeout 4s;
# No sticky sessions. Failed/unready peers are retried elsewhere.
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
}
}
+104 -4
View File
@@ -1,7 +1,107 @@
# OpenBao — реализовать конфигурацию и политики
# OpenBao: эксплуатация стенда
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
OpenBao запускается обычным `server`, а не `dev`: данные хранятся в named volume `openbao-data` через integrated Raft storage. TLS обязателен, порт опубликован только на loopback. После перезапуска данные сохраняются, но сервер снова sealed до ручного unseal.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
## Первичная инициализация
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
1. Создайте локальные credentials и PKI:
```powershell
.\scripts\bootstrap-secrets.ps1
.\scripts\bootstrap-pki.ps1
```
2. Запустите только OpenBao и проверьте состояние `uninitialized`:
```powershell
docker compose --env-file .env up -d openbao
docker compose --env-file .env exec openbao bao status
```
3. Один раз выполните init из интерактивного терминала оператора:
```powershell
docker compose --env-file .env exec openbao bao operator init -key-shares=3 -key-threshold=2
```
Команда выводит три unseal share и initial root token. Оператор немедленно переносит их в защищённое внешнее хранилище; доли передаются разным хранителям. Их запрещено сохранять в `.env`, `secrets/`, shell history, отчёт, скриншот или Git. Скрипты проекта намеренно не автоматизируют и не перехватывают init.
4. Введите любые две разные доли вручную. Значения вместо маркеров в команду не вставляйте: команда запросит их скрыто интерактивно.
```powershell
docker compose --env-file .env exec openbao bao operator unseal
docker compose --env-file .env exec openbao bao operator unseal
docker compose --env-file .env exec openbao bao status
```
5. Только на время bootstrap задайте root token в окружении текущего PowerShell-процесса и создайте KV, политики и AppRole:
```powershell
$env:BAO_TOKEN = Read-Host 'OpenBao root token'
.\scripts\bootstrap-openbao.ps1
Remove-Item Env:BAO_TOKEN
```
Скрипт не печатает secret values. Он загружает их в KV v2 через stdin, включает file audit, создаёт отдельные `messenger-api` и `messenger-worker` policies и кладёт только стартовые AppRole RoleID/SecretID в игнорируемый каталог `secrets/openbao/`.
6. Запустите весь стенд:
```powershell
docker compose --env-file .env up -d
```
OpenBao Agent у API и worker аутентифицируется своим AppRole, получает renewable token с TTL 15 минут и max TTL 1 час и рендерит только разрешённый набор runtime credentials в отдельный named volume. Root token и unseal shares в контейнеры приложений не передаются.
## Политики и проверяемые отказы
- `messenger-api` читает только `secret/data/messenger/api` и его metadata.
- `messenger-worker` читает только `secret/data/messenger/worker` и его metadata.
- У ролей нет доступа к чужому KV, `sys/policies/*`, auth configuration, init или unseal.
- AppRole SecretID действует 24 часа; token TTL — 15 минут, max TTL — 1 час. `token_num_uses=0` необходим для renewal и повторного чтения Agent, но область доступа ограничивает named policy.
После bootstrap выполните:
```powershell
.\scripts\test-openbao-policies.ps1
```
Тест требует существующие игнорируемые AppRole-файлы и доказывает allow для собственного пути, deny для чужого пути и deny изменения policy. Токены и SecretID не выводятся.
## Перезапуск, seal и восстановление
После перезапуска `openbao-data` сохраняется. Оператор снова выполняет две интерактивные команды `bao operator unseal`. Пока OpenBao sealed, agents не получают и не обновляют token; hardcoded или `.env` fallback у приложений отсутствует. После unseal agents повторяют authentication. Если приложение ещё не запущено, entrypoint ждёт rendered file до 120 секунд и завершает работу при его отсутствии.
Статические DB/Redis/RabbitMQ/S3 credentials читаются приложением при старте. После создания новой KV version следует последовательно перезапустить API/worker, проверить новые соединения, затем отозвать старые credentials в зависимости. OpenBao token rotation выполняется Agent автоматически.
## Ротация AppRole bootstrap credential
SecretID нужно менять до истечения 24 часов:
```powershell
$env:BAO_TOKEN = Read-Host 'OpenBao operator token'
.\scripts\rotate-openbao-secret-ids.ps1
Remove-Item Env:BAO_TOKEN
docker compose --env-file .env restart openbao-agent-api openbao-agent-worker
```
Скрипт заменяет локальные SecretID-файлы и не печатает их. В production вместо root token для этой операции создаётся отдельная узкая operator policy; root token после первичного bootstrap хранится offline.
## Эксплуатационные ограничения
`disable_mlock=true` выбран для локального Docker Desktop стенда: контейнеру не выдаётся `IPC_LOCK`. Это осознанный компромисс лабораторного окружения; swap/дампы хоста остаются в зоне доверия оператора. Agents запускаются как root только для записи в выделенные named volumes, при этом имеют `cap_drop: ALL`, `no-new-privileges`, read-only mounts конфигурации/PKI/bootstrap и не получают Docker socket.
Удаление volume уничтожает OpenBao storage и требует нового init. Выполнять следующую команду можно только при намеренном полном сбросе стенда и наличии решения оператора о судьбе старых shares:
```powershell
docker compose --env-file .env down --volumes
```
## Что не хранится в репозитории
- initial root token;
- unseal shares;
- AppRole SecretID и RoleID стенда;
- private keys и рабочие service credentials;
- содержимое Raft storage и audit log.
Справка: [operator init](https://openbao.org/docs/commands/operator/init/), [AppRole](https://openbao.org/docs/auth/approle/), [Agent auto-auth](https://openbao.org/docs/agent-and-proxy/autoauth/), [Raft storage](https://openbao.org/docs/configuration/storage/raft/), [KV CLI stdin](https://openbao.org/docs/commands/).
+31
View File
@@ -0,0 +1,31 @@
vault {
address = "https://openbao:8200"
ca_cert = "/run/pki/service-ca/ca.crt"
}
auto_auth {
method "approle" {
mount_path = "auth/approle"
config = {
role_id_file_path = "/run/bootstrap/role-id"
secret_id_file_path = "/run/bootstrap/secret-id"
remove_secret_id_file_after_reading = false
}
}
}
template_config {
static_secret_render_interval = "5m"
exit_on_retry_failure = false
}
template {
contents = <<EOT
{{ with secret "secret/data/messenger/api" -}}
DATABASE_PASSWORD={{ .Data.data.database_password }}
REDIS_PASSWORD={{ .Data.data.redis_password }}
RABBITMQ_PASSWORD={{ .Data.data.rabbitmq_password }}
S3_ACCESS_KEY_ID={{ .Data.data.s3_access_key_id }}
S3_SECRET_ACCESS_KEY={{ .Data.data.s3_secret_access_key }}
{{- end }}
EOT
destination = "/run/rendered/runtime.env"
perms = "0644"
}
+31
View File
@@ -0,0 +1,31 @@
vault {
address = "https://openbao:8200"
ca_cert = "/run/pki/service-ca/ca.crt"
}
auto_auth {
method "approle" {
mount_path = "auth/approle"
config = {
role_id_file_path = "/run/bootstrap/role-id"
secret_id_file_path = "/run/bootstrap/secret-id"
remove_secret_id_file_after_reading = false
}
}
}
template_config {
static_secret_render_interval = "5m"
exit_on_retry_failure = false
}
template {
contents = <<EOT
{{ with secret "secret/data/messenger/worker" -}}
DATABASE_PASSWORD={{ .Data.data.database_password }}
REDIS_PASSWORD={{ .Data.data.redis_password }}
RABBITMQ_PASSWORD={{ .Data.data.rabbitmq_password }}
S3_ACCESS_KEY_ID={{ .Data.data.s3_access_key_id }}
S3_SECRET_ACCESS_KEY={{ .Data.data.s3_secret_access_key }}
{{- end }}
EOT
destination = "/run/rendered/runtime.env"
perms = "0644"
}
+6
View File
@@ -0,0 +1,6 @@
path "secret/data/messenger/api" {
capabilities = ["read"]
}
path "secret/metadata/messenger/api" {
capabilities = ["read"]
}
+24
View File
@@ -0,0 +1,24 @@
ui = false
disable_mlock = true
default_lease_ttl = "15m"
max_lease_ttl = "1h"
api_addr = "https://openbao:8200"
cluster_addr = "https://openbao:8201"
storage "raft" {
path = "/openbao/data"
node_id = "openbao-stand"
}
listener "tcp" {
address = "0.0.0.0:8200"
cluster_address = "0.0.0.0:8201"
tls_cert_file = "/run/pki/openbao/tls.crt"
tls_key_file = "/run/pki/openbao/tls.key"
tls_min_version = "tls12"
tls_disable_client_certs = true
}
telemetry {
disable_hostname = true
}
+6
View File
@@ -0,0 +1,6 @@
path "secret/data/messenger/worker" {
capabilities = ["read"]
}
path "secret/metadata/messenger/worker" {
capabilities = ["read"]
}
+27 -4
View File
@@ -1,7 +1,30 @@
# Конфигурация наблюдаемости — реализовать
# Стек наблюдаемости
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Поток данных:
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
`messenger-api / messenger-worker -> OTLP/HTTP -> otel-collector -> Prometheus / Loki / Tempo -> Grafana`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Версии закреплены в `compose.yaml`: Java agent 2.33.1 (SDK 1.67.0), Collector Contrib 0.165.0, Prometheus 3.14.0, Loki 3.7.8, Tempo 3.1.1 и Grafana 13.3.0.
## Файлы
- `collector.yaml` — OTLP receivers, memory limiter, redaction, batch и bounded retry queues;
- `prometheus.yaml` и `prometheus-alerts.yaml` — scrape, SLO/queue/worker/export alerts;
- `loki.yaml` — локальное хранилище структурных OTLP logs;
- `tempo.yaml` — локальное хранилище traces;
- `grafana/provisioning` — три datasources и dashboard provisioning;
- `grafana/dashboards/messenger-overview.json` — импортируемый dashboard;
- `runbooks.md` — локальные действия для каждого alert.
Grafana доступна только на `127.0.0.1:3000`, Prometheus — на `127.0.0.1:9090`. Для автоматизированных incident snapshots Loki и Tempo доступны только на loopback-портах 3100 и 3200. OTLP Collector не публикуется на интерфейсы хоста.
## Проверка корреляции
1. Выполнить `python tests/smoke.py --base-url http://localhost:8080`.
2. В Tempo найти server span upload и перейти к RabbitMQ producer/consumer span.
3. Скопировать `trace_id` и выполнить в Loki `{service_name=~"messenger-(api|worker)"} | json | trace_id="..."`.
4. Убедиться, что у API и worker разные `service.name`, но общий trace context.
Для durable retry `traceparent/tracestate` сохраняются рядом с job в PostgreSQL и восстанавливаются перед outbox republish. Проверяемый сценарий: `scripts/incident-retry-trace.ps1`; он требует минимум два producer/consumer span в одной trace и сохраняет их parent IDs.
Collector удаляет потенциально чувствительные HTTP/message/body/DB parameter attributes. Java agent не настроен на захват request/response headers или bodies. Метрики используют только route template, status/method, job type/outcome и queue name.
+104
View File
@@ -0,0 +1,104 @@
extensions:
health_check:
endpoint: 0.0.0.0:13133
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /run/pki/otel-collector/tls.crt
key_file: /run/pki/otel-collector/tls.key
client_ca_file: /run/pki/workload-client-ca/ca.crt
min_version: "1.2"
processors:
memory_limiter:
check_interval: 1s
limit_mib: 384
spike_limit_mib: 96
attributes/redact:
actions:
- key: http.request.header.authorization
action: delete
- key: http.request.body
action: delete
- key: http.response.body
action: delete
- key: messaging.message.body
action: delete
- key: db.statement.parameters
action: delete
- key: url.query
action: delete
batch:
send_batch_size: 512
timeout: 5s
exporters:
prometheus:
endpoint: 0.0.0.0:8889
tls:
cert_file: /run/pki/otel-collector/tls.crt
key_file: /run/pki/otel-collector/tls.key
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
send_timestamps: true
resource_constant_labels:
included: ["service.*", "deployment.environment.name"]
otlp_http/tempo:
endpoint: https://tempo:4318
tls:
ca_file: /run/pki/service-ca/ca.crt
cert_file: /run/pki/collector-client/tls.crt
key_file: /run/pki/collector-client/tls.key
sending_queue:
enabled: true
queue_size: 2048
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 60s
otlp_http/loki:
endpoint: https://loki:3100/otlp
tls:
ca_file: /run/pki/service-ca/ca.crt
cert_file: /run/pki/collector-client/tls.crt
key_file: /run/pki/collector-client/tls.key
sending_queue:
enabled: true
queue_size: 2048
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 60s
service:
extensions: [health_check]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
without_type_suffix: false
without_units: false
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [otlp_http/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [otlp_http/loki]
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
set -eu
if [ -n "${OPENBAO_RENDERED_ENV:-}" ]; then
deadline=$(( $(date +%s) + ${OPENBAO_STARTUP_TIMEOUT_SECONDS:-120} ))
while [ ! -s "$OPENBAO_RENDERED_ENV" ]; do
if [ "$(date +%s)" -ge "$deadline" ]; then
echo "OpenBao did not render runtime credentials before startup deadline" >&2
exit 1
fi
sleep 1
done
while IFS='=' read -r name value; do
case "$name" in
DATABASE_PASSWORD|REDIS_PASSWORD|RABBITMQ_PASSWORD|S3_ACCESS_KEY_ID|S3_SECRET_ACCESS_KEY)
export "$name=$value" ;;
'') ;;
*) echo "Unexpected key in OpenBao rendered environment: $name" >&2; exit 1 ;;
esac
done < "$OPENBAO_RENDERED_ENV"
fi
if [ -f /run/pki/service-ca/ca.crt ]; then
keytool -importcert -noprompt -alias hla-lab7-service-ca \
-file /run/pki/service-ca/ca.crt -keystore /tmp/service-truststore.p12 \
-storetype PKCS12 -storepass changeit >/dev/null 2>&1
export JAVA_TOOL_OPTIONS="${JAVA_TOOL_OPTIONS:-} -Djavax.net.ssl.trustStore=/tmp/service-truststore.p12 -Djavax.net.ssl.trustStorePassword=changeit"
fi
if [ "${OTEL_SDK_DISABLED:-false}" = "true" ]; then
exec java -jar /app/app.jar "$@"
fi
exec java -javaagent:/opt/opentelemetry-javaagent.jar -jar /app/app.jar "$@"
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
export SERVICE_CA_PEM="$(cat /run/pki/service-ca/ca.crt)"
export GRAFANA_CLIENT_CERT_PEM="$(cat /run/pki/grafana-client/tls.crt)"
export GRAFANA_CLIENT_KEY_PEM="$(cat /run/pki/grafana-client/tls.key)"
exec /run.sh
@@ -0,0 +1,141 @@
{
"annotations": {"list": []},
"editable": false,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"liveNow": false,
"panels": [
{
"id": 1,
"title": "API requests / second",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "sum by (http_request_method) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m]))", "legendFormat": "{{http_request_method}}"}],
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 0}
},
{
"id": 2,
"title": "API 5xx ratio",
"description": "5xx business responses divided by all business responses over 5 minutes; health routes are excluded. Displayed as percent (0..100%).",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "(sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_code=~\"5..\",http_route!~\"/health/.*\"}[5m])) or vector(0)) / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])), 0.001)", "legendFormat": "5xx / all"}],
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 0}
},
{
"id": 3,
"title": "API duration p50 / p95 / p99",
"description": "Seconds. histogram_quantile is calculated from the summed Prometheus histogram buckets of all API replicas; replica percentiles are never averaged.",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p99"}
],
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 0}
},
{
"id": 4,
"title": "Job outcomes / second",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "sum by (outcome) (rate(messenger_jobs_processed_total{service_name=\"messenger-worker\"}[5m]))", "legendFormat": "{{outcome}}"}],
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 8}
},
{
"id": 5,
"title": "Job duration p95",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_job_processing_duration_seconds_bucket{service_name=\"messenger-worker\"}[5m])))", "legendFormat": "{{outcome}}"}],
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 8}
},
{
"id": 6,
"title": "Time to ready p95",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{service_name=\"messenger-worker\"}[10m])))", "legendFormat": "p95"}],
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 8}
},
{
"id": 7,
"title": "Queue depth and oldest age",
"description": "Left axis: durable queued jobs (count). Right axis: age of the oldest unfinished job (seconds). Backlog age is not processing latency.",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [
{"refId": "A", "expr": "max(messenger_queue_depth{service_name=\"messenger-api\"})", "legendFormat": "depth"},
{"refId": "B", "expr": "max(messenger_queue_oldest_job_age_seconds{service_name=\"messenger-api\"})", "legendFormat": "oldest age (s)"}
],
"fieldConfig": {
"defaults": {},
"overrides": [
{"matcher": {"id": "byName", "options": "depth"}, "properties": [{"id": "unit", "value": "short"}, {"id": "custom.axisPlacement", "value": "left"}]},
{"matcher": {"id": "byName", "options": "oldest age (s)"}, "properties": [{"id": "unit", "value": "s"}, {"id": "custom.axisPlacement", "value": "right"}]}
]
},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 16}
},
{
"id": 8,
"title": "Worker saturation",
"description": "busy workers / configured worker capacity. Dimensionless ratio displayed as percent.",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "messenger_worker_busy{service_name=\"messenger-worker\"} / clamp_min(messenger_worker_capacity{service_name=\"messenger-worker\"}, 1)", "legendFormat": "{{service_instance_id}}"}],
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 16}
},
{
"id": 9,
"title": "DB pool used / waiting",
"description": "Number of HikariCP connections by state plus pending acquisition requests. Unit: connections/requests (count).",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [
{"refId": "A", "expr": "sum by (service_name, state) (db_client_connections_usage{service_name=~\"messenger-(api|worker)\"})", "legendFormat": "{{service_name}} {{state}}"},
{"refId": "B", "expr": "sum by (service_name) (db_client_connections_pending_requests{service_name=~\"messenger-(api|worker)\"})", "legendFormat": "{{service_name}} waiting"}
],
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 16}
},
{
"id": 10,
"title": "Correlated application logs",
"type": "logs",
"datasource": {"type": "loki", "uid": "loki"},
"targets": [{"refId": "A", "expr": "{service_name=~\"messenger-(api|worker)\"} | json", "queryType": "range"}],
"options": {"showTime": true, "showLabels": false, "wrapLogMessage": true, "prettifyLogMessage": true, "enableLogDetails": true, "sortOrder": "Descending", "dedupStrategy": "none"},
"gridPos": {"h": 10, "w": 16, "x": 0, "y": 24}
},
{
"id": 11,
"title": "Recent traces",
"type": "traces",
"datasource": {"type": "tempo", "uid": "tempo"},
"targets": [{"refId": "A", "queryType": "search", "serviceName": "messenger-api", "limit": 20}],
"gridPos": {"h": 10, "w": 8, "x": 16, "y": 24}
}
],
"refresh": "10s",
"schemaVersion": 41,
"tags": ["hla", "lab6", "opentelemetry"],
"templating": {"list": []},
"time": {"from": "now-30m", "to": "now"},
"timepicker": {},
"timezone": "browser",
"title": "Messenger observability",
"uid": "messenger-observability",
"version": 3,
"weekStart": ""
}
@@ -0,0 +1,13 @@
apiVersion: 1
providers:
- name: Messenger Lab 6
orgId: 1
folder: HLA Lab 6
type: file
disableDeletion: true
updateIntervalSeconds: 30
allowUiUpdates: false
options:
path: /var/lib/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,77 @@
apiVersion: 1
deleteDatasources:
- name: Prometheus
orgId: 1
- name: Loki
orgId: 1
- name: Tempo
orgId: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
timeInterval: 10s
exemplarTraceIdDestinations:
- name: trace_id
datasourceUid: tempo
secureJsonData:
tlsCACert: ${SERVICE_CA_PEM}
tlsClientCert: ${GRAFANA_CLIENT_CERT_PEM}
tlsClientKey: ${GRAFANA_CLIENT_KEY_PEM}
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
derivedFields:
- name: TraceID
matcherRegex: '"trace_id":"([a-f0-9]{32})"'
datasourceUid: tempo
url: '$${__value.raw}'
secureJsonData:
tlsCACert: ${SERVICE_CA_PEM}
tlsClientCert: ${GRAFANA_CLIENT_CERT_PEM}
tlsClientKey: ${GRAFANA_CLIENT_KEY_PEM}
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
httpMethod: GET
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: -1m
spanEndTimeShift: 1m
filterByTraceID: true
filterBySpanID: false
customQuery: true
query: '{$${__tags}} | json | trace_id="$${__trace.traceId}"'
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
search:
hide: false
secureJsonData:
tlsCACert: ${SERVICE_CA_PEM}
tlsClientCert: ${GRAFANA_CLIENT_CERT_PEM}
tlsClientKey: ${GRAFANA_CLIENT_KEY_PEM}
+42
View File
@@ -0,0 +1,42 @@
auth_enabled: false
server:
http_listen_port: 3100
http_tls_config:
cert_file: /run/pki/loki/tls.crt
key_file: /run/pki/loki/tls.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
common:
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 72h
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+51
View File
@@ -0,0 +1,51 @@
groups:
- name: messenger-slo
rules:
- alert: MessengerApiHighErrorRate
expr: |
(
(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5..",http_route!~"/health/.*"}[5m])) or vector(0))
/
clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*"}[5m])), 0.001)
) > 0.05
for: 2m
labels:
severity: warning
slo: api-availability
annotations:
summary: Messenger API 5xx ratio exceeds 5%
description: Five-minute 5xx ratio is above 5% for two minutes.
runbook: infra/otel/runbooks.md#api-high-error-rate
- alert: AttachmentQueueLagHigh
expr: messenger_queue_oldest_job_age_seconds{service_name="messenger-api"} > 60
for: 1m
labels:
severity: warning
slo: attachment-time-to-ready
annotations:
summary: Oldest attachment job is over 60 seconds old
description: The durable worker queue has not drained within the SLO threshold.
runbook: infra/otel/runbooks.md#queue-lag
- alert: AttachmentWorkerSaturated
expr: |
messenger_worker_busy{service_name="messenger-worker"}
/ clamp_min(messenger_worker_capacity{service_name="messenger-worker"}, 1) >= 1
for: 2m
labels:
severity: warning
annotations:
summary: All attachment workers are busy
description: Worker busy/capacity has remained at 100% for two minutes.
runbook: infra/otel/runbooks.md#worker-saturation
- alert: TelemetryExportFailures
expr: sum(rate(otelcol_exporter_send_failed_spans_total[5m])) + sum(rate(otelcol_exporter_send_failed_log_records_total[5m])) > 0
for: 1m
labels:
severity: info
annotations:
summary: Collector is dropping traces or logs
description: A telemetry backend is unavailable or rejecting data.
runbook: infra/otel/runbooks.md#telemetry-backend
+8
View File
@@ -0,0 +1,8 @@
tls_server_config:
cert_file: /run/pki/prometheus/tls.crt
key_file: /run/pki/prometheus/tls.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
client_allowed_sans:
- spiffe://hla-lab7/grafana
min_version: TLS12
+17
View File
@@ -0,0 +1,17 @@
global:
scrape_interval: 10s
evaluation_interval: 10s
rule_files:
- /etc/prometheus/prometheus-alerts.yaml
scrape_configs:
- job_name: otel-collector-exported-metrics
scheme: https
tls_config:
ca_file: /run/pki/service-ca/ca.crt
server_name: otel-collector
cert_file: /run/pki/prometheus-client/tls.crt
key_file: /run/pki/prometheus-client/tls.key
static_configs:
- targets: ["otel-collector:8889"]
+27
View File
@@ -0,0 +1,27 @@
# Runbooks
## API high error rate
1. In Grafana, compare the 5xx ratio with `db_client_*` pool metrics.
2. Open a failed server span in Tempo and inspect child JDBC/Redis/S3 spans.
3. Search Loki by the trace ID. Do not search by a user, chat or message ID.
4. Restore the failing dependency and confirm the alert resolves after the five-minute window.
## Queue lag
1. Check `messenger_queue_depth` and `messenger_queue_oldest_job_age_seconds`.
2. Check worker busy/capacity and the rate of `messenger_jobs_processed_total` by outcome.
3. Search worker errors in Loki, then open the linked consumer trace in Tempo.
4. Restore or scale the worker and confirm depth and age return to zero.
## Worker saturation
1. Compare busy/capacity with job duration p95 and container CPU/RAM.
2. Inspect slow consumer spans and their S3/JDBC children.
3. Remove the bottleneck before increasing concurrency; memory is explicitly bounded.
## Telemetry backend
1. Inspect Collector exporter failure and queue metrics on port 8888 through Prometheus.
2. Restore Loki or Tempo. Collector retries for at most 60 seconds with a 2048-item queue.
3. Confirm the application remained available; telemetry loss is allowed and bounded.
+40
View File
@@ -0,0 +1,40 @@
server:
http_listen_port: 3200
http_tls_config:
cert_file: /run/pki/tempo/tls.crt
key_file: /run/pki/tempo/tls.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /run/pki/tempo/tls.crt
key_file: /run/pki/tempo/tls.key
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
live_store:
max_trace_idle: 10s
max_block_duration: 5m
wal:
path: /var/tempo/live-store/traces
storage:
trace:
backend: local
local:
path: /var/tempo/blocks
overrides:
defaults:
compaction:
block_retention: 72h
usage_report:
reporting_enabled: false
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
psql --set=ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \
--set=api_password="$DATABASE_API_PASSWORD" \
--set=worker_password="$DATABASE_WORKER_PASSWORD" \
--set=migration_password="$DATABASE_MIGRATION_PASSWORD" <<'SQL'
CREATE ROLE messenger_api LOGIN PASSWORD :'api_password';
CREATE ROLE messenger_worker LOGIN PASSWORD :'worker_password';
CREATE ROLE messenger_migration LOGIN PASSWORD :'migration_password';
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker, messenger_migration;
GRANT USAGE, CREATE ON SCHEMA public TO messenger_migration;
SQL
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
install -d -m 0700 -o postgres -g postgres /var/lib/postgresql/tls
install -m 0600 -o postgres -g postgres /run/pki/postgres/tls.key /var/lib/postgresql/tls/server.key
install -m 0644 -o postgres -g postgres /run/pki/postgres/tls.crt /var/lib/postgresql/tls/server.crt
exec docker-entrypoint.sh postgres \
-c ssl=on \
-c ssl_min_protocol_version=TLSv1.2 \
-c ssl_cert_file=/var/lib/postgresql/tls/server.crt \
-c ssl_key_file=/var/lib/postgresql/tls/server.key \
-c hba_file=/etc/postgresql/pg_hba.conf
+5
View File
@@ -0,0 +1,5 @@
local all all trust
hostnossl all all 0.0.0.0/0 reject
hostnossl all all ::0/0 reject
hostssl all all 0.0.0.0/0 scram-sha-256
hostssl all all ::0/0 scram-sha-256
+14
View File
@@ -0,0 +1,14 @@
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.cacertfile = /run/pki/workload-client-ca/ca.crt
ssl_options.certfile = /run/pki/rabbitmq/tls.crt
ssl_options.keyfile = /run/pki/rabbitmq/tls.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
management.tcp.port = none
management.ssl.port = 15671
management.ssl.cacertfile = /run/pki/service-ca/ca.crt
management.ssl.certfile = /run/pki/rabbitmq/tls.crt
management.ssl.keyfile = /run/pki/rabbitmq/tls.key