Защита стенда и управление секретами через 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 -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