lab7: безопасность, mTLS, OpenBao и PKI lifecycle
Application / Go invariants and static checks (pull_request) Canceled after 0s
Application / Lab7 verified TLS and retained features (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Vladislav Kunetskiy
2026-11-10 14:39:57 +03:00
parent 20afc2c790
commit 1b6e96ccc0
570 changed files with 298308 additions and 137 deletions
+86 -4
View File
@@ -1,7 +1,89 @@
# Инфраструктура студента
# Инфраструктура lab7
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
## Телеметрия и границы ролей
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
`telemetry-gateway/*.cfg` — штатные HAProxy 3.2 gateways в network namespace
соответствующего backend. Только gateway принимает соединения из Docker-сети;
native HTTP, admin, metrics, OTLP и вспомогательный gRPC/gossip bind — loopback.
Внутренние listeners требуют проверенный client certificate; роль определяется
точным **CN**, не URI SAN и не переданным HTTP header. Неизвестная CN, даже от
того же CA, и неразрешённые method/path получают отказ по умолчанию.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
| TLS endpoint | Разрешённая роль и операция | Native loopback |
| --- | --- | --- |
| `otel-collector:4318` | `api`/`worker`/`relay`: POST `/v1/traces`, `/v1/metrics`, `/v1/logs` | `14318` |
| `otel-collector:8888`, `:8889` | `prometheus`/`operator`: GET `/metrics` | `18888`, `18889` |
| `otel-collector:13134` | `prometheus`/`operator`: GET `/` (health) | `13133` |
| `prometheus:9090` | `grafana`: query/labels/series/metadata; `prometheus`: GET metrics/health; `operator`: отдельный query/status allowlist | `19090` |
| `loki:3100` | `collector`: POST `/otlp/v1/logs` или `/loki/api/v1/push`; `grafana`: query/labels/series/Explore; `prometheus`: GET metrics/ready; `operator`: отдельный read allowlist | `13100` |
| `tempo:3200` | `grafana`: GET trace/search/tag/TraceQL-metrics/echo; `prometheus`: GET metrics/ready; `operator`: отдельный read allowlist | `13200` |
| `tempo:4437` | только `collector`: OTLP gRPC | `14317` |
| `grafana:3000` | browser HTTPS, без client certificate; штатная аутентификация Grafana | `13000` |
Полные allowlists — в gateway configs. Grafana не получает push/delete/admin,
Collector не получает query API, scrape identity не получает data queries.
Loki/Tempo gateway перезаписывает `X-Scope-OrgID` в `fake`: внешний tenant header
не является полномочием; существующий single-tenant store сохраняется.
Prometheus не включает lifecycle/admin API; даже `operator` не получает
reload/quit/remote-write через gateway. Prometheus buildinfo GET доступен Grafana
для проверки datasource/version; остальные status endpoints — только operator.
У каждого владельца монтируется только его identity readonly в `/run/identity`:
`current/tls.pem`, `tls.crt`, `tls.key`, `ca.crt`, `ca.crl`. Gateways используют
CA/CRL verification, TLS >=1.2, session tickets/cache выключены. Они загружают
сертификаты/CRLs при старте: atomic replacement `current` требует bounded
reload/restart gateway и закрытия старых соединений; обновление файлов само по
себе не доказывает применение CRL/CA rollover. Штатные Collector/Prometheus/
Grafana clients проверяют CA и hostname, отправляют только собственный leaf.
Их native TLS config не объявляется самостоятельной CRL проверкой; lifecycle
должен обновлять trust consumers и разрывать прежние соединения.
Go использует `TLS_VERSION_FILE=/run/identity/current-version`: один bounded
regular-file read выбирает immutable `versions/<name>` сразу для leaf/key/CA/CRL.
Это не native `current` symlink; unreadable/malformed selectors fail closed.
Publisher делает staging selector runtime-readable до atomic rename. `up`
пересоздаёт native gateways даже при reused owners; `revoke` reloads/drains
HAProxy CRL consumers. Offline root CRLs обновляются до последних24h validity.
## Native запуск и сохранённые pipelines
- Prometheus: `--web.listen-address=127.0.0.1:19090`, без
`--web.enable-lifecycle`/`--web.enable-admin-api`; прежние retention flags,
scrape-job names, recording rules и alert tests сохраняются. Все шесть
scrape targets HTTPS/mTLS с identity `prometheus`, broker теперь `:15693`.
- Grafana: `GF_SERVER_HTTP_ADDR=127.0.0.1`, `GF_SERVER_HTTP_PORT=13000`,
`GF_SERVER_PROTOCOL=http`, `GF_SERVER_ROOT_URL=https://localhost:3000/`;
anonymous/auth-proxy login выключены, admin password — только private runtime
file. Backend не публикуется, browser использует TLS gateway.
- Collector: все три OTLP pipelines сохранены; memory limiter 140 MiB, batch
5 с/1024, exporter queues 10 MiB с retry <=30 с. Loki export — HTTPS `/otlp`
(OTLP добавляет `/v1/logs`), Tempo — GRPCS `:4437`; native Collector gRPC OTLP
listener отсутствует. Loopback health не зависит от доступности gateway.
- Loki: filesystem/schema v13, retention 168h, index labels только
`service.name`/`deployment.environment.name`; internal gRPC `127.0.0.1:9096`.
- Tempo: local storage, retention 72h; internal gRPC `127.0.0.1:9095`, gossip
loopback, advertised self-dial addresses loopback. Grafana использует
synchronous trace/search APIs, без внешнего query-gRPC listener.
- Datasource UIDs, dashboards, trace-to-log/derived-field links сохранены.
Tracked `grafana/provisioning/datasources/datasources.yaml` — **template**:
`__LAB7_CA_CERT__`, `__LAB7_CLIENT_CERT__`, `__LAB7_CLIENT_KEY__` заменяются
operator bootstrap только на material роли `grafana`. PEM хранится в
`secureJsonData`, datasource `editable: false`. В Grafana монтируется
сгенерированный private file вне Git, не этот template и не общий directory
с чужими ключами. Для YAML block scalars каждая PEM строка получает тот же
отступ; JSON сериализация как YAML также допустима. Rotation/CA rollover
требует повторного render и restart/reprovision Grafana.
- cAdvisor/Docker socket не используются; CPU/RAM приложения — cgroup v2,
брокерные queue labels — `rabbitmq_prometheus`. Runbooks находятся в `runbooks/`.
Это описание configuration boundaries, не заявление о пройденной проверке.
Совместимость pinned images, все dashboards, wrong-CN/verb/path negatives,
fresh/resumed revocation и отсутствие plaintext bypass проверяются отдельно
интеграционным acceptance driver после сборки всего стенда.
Синтаксис и поля: [HAProxy](https://github.com/haproxy/haproxy/blob/v3.2.0/doc/configuration.txt),
[Collector TLS](https://github.com/open-telemetry/opentelemetry-collector/blob/v0.164.0/config/configtls/README.md),
[Prometheus TLS](https://prometheus.io/docs/prometheus/latest/configuration/#tls_config),
[Grafana provisioning](https://github.com/grafana/grafana/blob/v13.2.4/docs/sources/administration/provisioning/index.md),
[Loki](https://github.com/grafana/loki/blob/v3.6.7/docs/sources/shared/configuration.md),
[Tempo 2.9](https://github.com/grafana/tempo/blob/v2.9.0/docs/sources/tempo/configuration/_index.md).
+612
View File
@@ -0,0 +1,612 @@
{
"annotations": {
"list": []
},
"editable": false,
"graphTooltip": 1,
"panels": [
{
"id": 1,
"title": "API RPS",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 0
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(http_server_request_duration_seconds_count[5m]))",
"legendFormat": "rps",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"options": {}
},
{
"id": 2,
"title": "API error ratio (edge SLI)",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 0
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "slo:api_error_ratio:5m",
"legendFormat": "5xx ratio",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "slo:api_error_ratio:1h",
"legendFormat": "1h",
"refId": "B",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {}
},
{
"id": 3,
"title": "API latency p50/p95/p99",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 7
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))",
"legendFormat": "p50",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))",
"legendFormat": "p95",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))",
"legendFormat": "p99",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 4,
"title": "Jobs processed / failed / retried",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 7
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_jobs_processed_total{outcome=\"succeeded\"}[5m]))",
"legendFormat": "succeeded",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_jobs_processed_total{outcome=\"failed\"}[5m]))",
"legendFormat": "failed",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_jobs_processed_total{outcome=\"retried\"}[5m]))",
"legendFormat": "retried",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {}
},
{
"id": 5,
"title": "Time-to-ready p50/p95/p99",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 14
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p50",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p95",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p99",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 6,
"title": "TTR bad ratio (missed / (within 30s + missed))",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 14
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "slo:job_ttr_bad_ratio:5m",
"legendFormat": "5m",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "slo:job_ttr_bad_ratio:1h",
"legendFormat": "1h",
"refId": "B",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {}
},
{
"id": 7,
"title": "Queue depth",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 21
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(rabbitmq_queue_messages_ready{queue=\"attachment.process.v1\"})",
"legendFormat": "ready",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 8,
"title": "Oldest job age",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 21
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(messenger_queue_oldest_job_age_seconds)",
"legendFormat": "oldest job seconds",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 9,
"title": "Worker saturation",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 21
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_worker_busy)",
"legendFormat": "busy",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_worker_capacity)",
"legendFormat": "capacity",
"refId": "B",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 10,
"title": "DB pool used / idle / max",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 28
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_used)",
"legendFormat": "used",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_idle)",
"legendFormat": "idle",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_max)",
"legendFormat": "max",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 11,
"title": "DB empty acquire / wait",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 28
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_db_pool_empty_acquire_total[5m]))",
"legendFormat": "empty acquire/s",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_db_pool_empty_acquire_wait_seconds_total[5m]))",
"legendFormat": "wait seconds/s",
"refId": "B",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 12,
"title": "API logs",
"type": "logs",
"gridPos": {
"h": 9,
"w": 12,
"x": 0,
"y": 35
},
"datasource": {
"type": "loki",
"uid": "loki"
},
"targets": [
{
"datasource": {
"type": "loki",
"uid": "loki"
},
"expr": "{service_name=\"messenger-api\"}",
"refId": "A",
"queryType": "range"
}
],
"fieldConfig": {
"defaults": {},
"overrides": []
},
"options": {}
},
{
"id": 13,
"title": "Traces: job.process",
"type": "traces",
"gridPos": {
"h": 9,
"w": 12,
"x": 12,
"y": 35
},
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"targets": [
{
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"query": "{ name = \"job.process\" }",
"refId": "A",
"queryType": "traceql"
}
],
"fieldConfig": {
"defaults": {},
"overrides": []
},
"options": {}
},
{
"id": 14,
"type": "stat",
"title": "API error budget remaining (7d)",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"expr": "slo:api_budget_remaining:7d",
"refId": "A",
"legendFormat": "remaining"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0,
"max": 1
},
"overrides": []
},
"gridPos": {
"h": 6,
"w": 6,
"x": 0,
"y": 0
}
}
],
"refresh": "5s",
"schemaVersion": 39,
"tags": [
"lab6",
"messenger"
],
"templating": {
"list": []
},
"time": {
"from": "now-30m",
"to": "now"
},
"timezone": "browser",
"title": "Lab6 — messenger observability",
"uid": "lab6-overview",
"version": 1
}
@@ -0,0 +1,452 @@
{
"annotations": {
"list": []
},
"editable": false,
"panels": [
{
"id": 1,
"title": "API RPS",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 0
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(http_server_request_duration_seconds_count[5m]))",
"legendFormat": "rps",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"options": {}
},
{
"id": 3,
"title": "API latency p50/p95/p99",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 7
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))",
"legendFormat": "p50",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))",
"legendFormat": "p95",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))",
"legendFormat": "p99",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 10,
"title": "DB pool used / idle / max",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 28
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_used)",
"legendFormat": "used",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_idle)",
"legendFormat": "idle",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_max)",
"legendFormat": "max",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "none"
},
"overrides": []
},
"options": {}
},
{
"id": 11,
"title": "DB empty acquire / wait",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 28
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_db_pool_empty_acquire_total[5m]))",
"legendFormat": "empty acquire/s",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_db_pool_empty_acquire_wait_seconds_total[5m]))",
"legendFormat": "wait seconds/s",
"refId": "B",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "none"
},
"overrides": [
{
"matcher": {
"id": "byFrameRefID",
"options": "A"
},
"properties": [
{
"id": "unit",
"value": "ops"
}
]
},
{
"matcher": {
"id": "byFrameRefID",
"options": "B"
},
"properties": [
{
"id": "unit",
"value": "s"
}
]
}
]
},
"options": {}
},
{
"id": 12,
"title": "API logs",
"type": "logs",
"gridPos": {
"h": 9,
"w": 12,
"x": 0,
"y": 35
},
"datasource": {
"type": "loki",
"uid": "loki"
},
"targets": [
{
"datasource": {
"type": "loki",
"uid": "loki"
},
"expr": "{service_name=\"messenger-api\"}",
"refId": "A",
"queryType": "range"
}
],
"fieldConfig": {
"defaults": {},
"overrides": []
},
"options": {}
},
{
"id": 30,
"title": "Process memory usage",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 28
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name) (messenger_process_memory_usage_bytes)",
"legendFormat": "{{service_name}}",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {}
},
{
"id": 31,
"title": "Collector exporter queue",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 28
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(otelcol_exporter_queue_size)",
"legendFormat": "queue",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {}
},
{
"id": 32,
"title": "Scrape targets up",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 35
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "up",
"legendFormat": "{{job}}",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "none"
},
"overrides": []
},
"options": {}
},
{
"id": 33,
"type": "timeseries",
"title": "Process CPU by service",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"expr": "sum by (service_name) (rate(messenger_process_cpu_seconds_total[5m]))",
"refId": "A",
"legendFormat": "{{service_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "cores"
},
"overrides": []
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 0
}
},
{
"id": 34,
"type": "timeseries",
"title": "Process memory vs limit",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"expr": "sum by (service_name) (messenger_process_memory_usage_bytes) / clamp_min(sum by (service_name) (messenger_process_memory_limit_bytes), 1)",
"refId": "A",
"legendFormat": "{{service_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 0
}
},
{
"id": 35,
"type": "timeseries",
"title": "RPS by route and status",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"expr": "sum by (http_route,http_response_status_class) (rate(http_server_request_duration_seconds_count[5m]))",
"refId": "A",
"legendFormat": "{{http_route}} {{http_response_status_code}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 0
}
}
],
"refresh": "5s",
"schemaVersion": 39,
"tags": [
"lab6",
"infra"
],
"templating": {
"list": []
},
"time": {
"from": "now-30m",
"to": "now"
},
"title": "Lab6 — infrastructure saturation",
"uid": "lab6-infra",
"version": 1
}
+430
View File
@@ -0,0 +1,430 @@
{
"annotations": {
"list": []
},
"editable": false,
"panels": [
{
"id": 4,
"title": "Jobs processed / failed / retried",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 7
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_jobs_processed_total{outcome=\"succeeded\"}[5m]))",
"legendFormat": "succeeded",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_jobs_processed_total{outcome=\"failed\"}[5m]))",
"legendFormat": "failed",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(messenger_jobs_processed_total{outcome=\"retried\"}[5m]))",
"legendFormat": "retried",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {}
},
{
"id": 5,
"title": "Time-to-ready p50/p95/p99",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 14
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p50",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p95",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p99",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 6,
"title": "TTR bad ratio (missed / (within 30s + missed))",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 14
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "slo:job_ttr_bad_ratio:5m",
"legendFormat": "5m",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "slo:job_ttr_bad_ratio:1h",
"legendFormat": "1h",
"refId": "B",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {}
},
{
"id": 7,
"title": "Queue depth",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 21
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(rabbitmq_queue_messages_ready{queue=\"attachment.process.v1\"})",
"legendFormat": "ready",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 8,
"title": "Oldest job age",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 21
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(messenger_queue_oldest_job_age_seconds)",
"legendFormat": "oldest job seconds",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 9,
"title": "Worker saturation",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 21
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_worker_busy)",
"legendFormat": "busy",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_worker_capacity)",
"legendFormat": "capacity",
"refId": "B",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 10,
"title": "DB pool used / idle / max",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 28
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_used)",
"legendFormat": "used",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_idle)",
"legendFormat": "idle",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_max)",
"legendFormat": "max",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 20,
"title": "Job duration p50/p95/p99",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 42
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
"legendFormat": "p50",
"refId": "A",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
"legendFormat": "p95",
"refId": "B",
"range": true
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
"legendFormat": "p99",
"refId": "C",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 21,
"title": "Overdue jobs (>30s)",
"type": "timeseries",
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 42
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(messenger_jobs_overdue)",
"legendFormat": "overdue",
"refId": "A",
"range": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
}
],
"refresh": "5s",
"schemaVersion": 39,
"tags": [
"lab6",
"jobs"
],
"templating": {
"list": []
},
"time": {
"from": "now-30m",
"to": "now"
},
"title": "Lab6 — jobs and queue",
"uid": "lab6-jobs",
"version": 1
}
@@ -0,0 +1,10 @@
apiVersion: 1
providers:
- name: lab6
orgId: 1
folder: Lab6
type: file
disableDeletion: false
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,73 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
tlsSkipVerify: false
serverName: prometheus
secureJsonData:
tlsCACert: |
__LAB7_CA_CERT__
tlsClientCert: |
__LAB7_CLIENT_CERT__
tlsClientKey: |
__LAB7_CLIENT_KEY__
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
tlsSkipVerify: false
serverName: loki
derivedFields:
- datasourceUid: tempo
matcherType: label
matcherRegex: trace_id
url: "$${__value.raw}"
urlDisplayLabel: Open trace
secureJsonData:
tlsCACert: |
__LAB7_CA_CERT__
tlsClientCert: |
__LAB7_CLIENT_CERT__
tlsClientKey: |
__LAB7_CLIENT_KEY__
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
tlsSkipVerify: false
serverName: tempo
streamingEnabled:
search: false
metrics: false
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
filterBySpanID: false
tags:
- key: service.name
value: service_name
secureJsonData:
tlsCACert: |
__LAB7_CA_CERT__
tlsClientCert: |
__LAB7_CLIENT_CERT__
tlsClientKey: |
__LAB7_CLIENT_KEY__
+101
View File
@@ -0,0 +1,101 @@
# Lab7 TLS ingress and mTLS backend; only the authenticated LB URI reaches API.
#
# Почему активные проверки, а не пассивные: nginx OSS умел только пассивные, и
# реплика, которая осталась доступной по сети, но потеряла БД, продолжала получать
# трафик и отвечала 503 (измерено: 20 из 40 запросов /health/live). HAProxy сам
# опрашивает /health/ready и полностью убирает неготовую реплику из ротации.
#
# Почему повторы безопасны: `retry-on conn-failure` — повтор только когда
# соединение не установилось и запрос НЕ ушёл. Если запрос уже передан серверу,
# повтора нет, поэтому прозрачного дублирования POST (создание чата, сообщения)
# балансировщик не делает. Неопределённый результат повторяет клиент, а сообщение
# защищено обязательным Idempotency-Key (контракт 1.3.0).
global
log stdout format raw local0
maxconn 2048
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
tune.ssl.cachesize 0
defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
timeout connect 1s
timeout client 70s
timeout server 45s
# Проверка готовности: одна проба не может висеть дольше 1 с, поэтому при
# inter 2s fall 2 реплика уходит из ротации максимум за ~4 с, даже если она
# держит соединение открытым и не отвечает.
#
# timeout server увеличен для 10 MiB загрузок: spool + S3 Put не всегда
# укладываются в прежние 5 с под конкурентной нагрузкой. Readiness-проба
# остаётся с timeout check 1s, поэтому обнаружение мёртвой реплики не
# замедляется.
timeout check 1s
retry-on conn-failure
retries 2
option redispatch
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 5s
hold nx 2s
hold timeout 1s
hold refused 1s
hold obsolete 5s
backend api_backend
balance leastconn
# Период проверки 2 с; реплика исключается после 2 неудач (<=4 с) и
# возвращается в ротацию после 2 успехов (<=4 с).
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
# Одно имя -> все адреса реплик (общий network alias в compose.yaml),
# адреса переразрешаются каждые 5 с: масштабирование и замена контейнеров
# не зависят от их номеров и IP.
default-server check inter 2s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
# Слотов больше, чем типовых реплик (1/2/4 в треке 1): свободный слот нужен
# ещё и сценарию scripts/lb_readiness_check.sh, который поднимает рядом
# «неготовую» реплику.
server-template api 8 api-replica:8080 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required verifyhost api-replica sni str(api-replica) check-sni api-replica no-ssl-reuse
backend api_health
balance leastconn
# Dedicated backend for client readiness/liveness endpoints. Keeping it
# separate keeps /health traffic out of the API availability SLI.
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
default-server check inter 2s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
server-template api 8 api-replica:8080 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required verifyhost api-replica sni str(api-replica) check-sni api-replica no-ssl-reuse
frontend https_front
bind *:8443 ssl crt /run/identity/current/tls.pem
http-request set-header X-Forwarded-For %[src]
http-request del-header Forwarded
http-request del-header X-User-Id
http-response set-header Strict-Transport-Security "max-age=31536000"
use_backend api_health if { path_beg /health/ }
default_backend api_backend
frontend stats_front
# Только для оператора и доказательств: видно, какие реплики UP/DOWN и почему.
bind *:8404 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl known_role ssl_c_s_dn(CN) -m str operator prometheus
acl monitor ssl_c_s_dn(CN) -m str prometheus
http-request deny deny_status 403 unless known_role
http-request deny deny_status 403 if monitor !{ path /metrics }
# Built-in Prometheus exporter (HAProxy built with USE_PROMEX). The edge
# SLI uses backend api_backend; /health/* is routed to api_health and is not
# part of the availability numerator or denominator.
http-request use-service prometheus-exporter if { path /metrics }
stats enable
stats uri /stats
stats refresh 2s
http-request return status 200 content-type text/plain string ok if { path /healthz }
+72
View File
@@ -0,0 +1,72 @@
auth_enabled: false
server:
http_listen_address: 127.0.0.1
http_listen_port: 13100
grpc_listen_address: 127.0.0.1
grpc_listen_port: 9096
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
# Any optional gossip traffic remains inside this service namespace.
memberlist:
bind_addr: [127.0.0.1]
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
storage_config:
filesystem:
directory: /loki/storage
tsdb_shipper:
active_index_directory: /loki/tsdb-index
cache_location: /loki/tsdb-cache
limits_config:
retention_period: 168h
allow_structured_metadata: true
max_line_size: 32KB
max_line_size_truncate: true
otlp_config:
resource_attributes:
ignore_defaults: true
attributes_config:
- action: index_label
attributes:
- service.name
- deployment.environment.name
- action: structured_metadata
attributes:
- service.instance.id
- service.version
log_attributes:
- action: structured_metadata
regex: .*
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
ruler:
storage:
type: local
local:
directory: /loki/rules
+129 -4
View File
@@ -1,7 +1,132 @@
# OpenBao — реализовать конфигурацию и политики
# OpenBao: bootstrap, policies и PKI lifecycle
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
Pinned OpenBao2.7.2 runs as UID100:1000, **not dev-mode**. NativeHTTPS8200,
Raftvolume `/openbao/file`, auditvolume `/openbao/audit`; clusterlistener8201
is loopback. `server.hcl` declares TLS1.2+, clientCA and persistentHMAC audit
with `log_raw=false`. Browser/operator endpoint is loopbackHTTPS, not publicadmin.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
## Запуск и custody
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
```sh
cp .env.example .env
make prepare
make up
make test test-security test-lab7
```
`make up` builds the application, preparesrolefiles, runsvolumeownershipjob,
startsBao, performs firstinit (3shares, threshold2), operatorunseal and scoped
provisioning, createsDB/S3roles/bucket, runsmigrations, startsapps andwaits for
CA/hostname-verifiedHTTPS **and full64KiBS3bodyreadiness**. RunningAPI restart does
not requireunseal. AfterBao restart:
```sh
make bao-unseal
# Or complete namespace-aware storage/application restart:
python3 scripts/securityctl.py restart
```
Offline rootCA/privatekey and `operator-unseal.json` are outsidecheckout:
`~/.local/share/mtusi-lab7/<COMPOSE_PROJECT_NAME>` (0700directory,0600files),
optionally overridden by `LAB7_OPERATOR_STATE`. They are never mounted into
containers. Operatorhost/Dockeraccess is trusted. Protect and back up this state;
losingunsealshares cannot be repaired by readingBao'sencryptedRaftvolume.
Initialroot token is used only for provisioning. After verifyingseparate
operatorcert-auth, bootstraprevokesit, confirms403 and removesit fromstate.
App/worker/relay receive only ownleaf+ownconfidentialKVconfiguration, notroot,
unsealshares, sharedBAO_TOKEN or a staticbootstrapsecret.
## Identity и policies
`securityctl.py` applies KVv2 at `secret/`, `cert/` auth and `pki/`intermediate.
Operator signs anintermediateCSR withoffline root; itsprivatekey remains inside
BaoRaft, not at thehost. Serviceauth binds bothCN and URI`spiffe://mtusi/<role>`.
| Role | ReadableKV | Issuance | Othercapabilities |
| --- | --- | --- | --- |
| api | secret/data/api | pki/issue/api | tokenlookup/renew/revoke-self |
| worker | secret/data/worker | pki/issue/worker | tokenlookup/renew/revoke-self |
| relay | secret/data/relay | pki/issue/relay | tokenlookup/renew/revoke-self |
| Othernative service | None | Itsownpki/issue/<role> | tokenlookup/renew/revoke-self |
| operator | ManagedKVandPKI | Managedroles/issuers | Restrictedlab7policies/certauth/seal/auditinspection; no permanentroot token |
Servicepolicy cannot readforeignKV, issueforeignrole or writepolicy. Live
`make test-lab7` returns ownKV200 andforeignKV/issuer/policyadmin403. KVbackend
passwords/keys remain static until explicitrotation; tokenTTL is not theirTTL.
Cert-auth tokenTTL60s/max300s. Go admission is bounded independently by
actualtokenlease, KVfreshness60s and currentleafNotAfter, with a1s safetymargin.
Renewal/reauth must succeed beforedeadlines; sealed/unavailableBao cannot widen
a cachedlease. A firstcancellation fixes one30s shutdownbudget for allcleanup.
## Leaf publication и renewal
```sh
make pki-issue ROLE=api CERT_TTL=1h
make pki-renew ROLE=api CERT_TTL=1h
make renew-watch ROLE=api CERT_TTL=1h
```
NormalleafTTL1h/max24h. Watcher uses ownservicecert-auth and renews at half of
remaininglifetime. Allcertificate/key/CA/CRL files are prepared in immutable
`pki/<role>/versions/<name>` with runtime-readableownership. Nativeconsumers
use `current`; Go uses one atomicregular `current-version` selector. TLSfile
settings still namecurrentbasenames; `TLS_VERSION_FILE` identifies theselector.
Go cannot mixfiles or fail because a hot-swap traversed thesymlink. Invalid,
missing, stale or revokedmaterial remains fail-closed; no insecure/cachefallback.
Go hotloadsleaf/CRL; CAtrustchanges restartprocesses. NativeHAProxy, PostgreSQL,
S3, RabbitMQ, Collector/Grafana clients use explicitreload/recreate paths. A shared
namespaceconsumer is recreated against actualowner afterownerrestart. `up`
also reappliesnativegateways whenownercontainers are reused.
## Отзыв, staticsecret и CArollover
```sh
# Issue/reload the replacement before revoking itsoldserial:
python3 scripts/securityctl.py revoke lb --serial OLD_SERIAL
python3 scripts/securityctl.py rotate-secret worker
python3 scripts/securityctl.py ca-rollover --phase prepare
python3 scripts/securityctl.py ca-rollover --phase issue
python3 scripts/securityctl.py ca-rollover --phase retire
python3 scripts/securityctl.py audit-summary
```
Revocation publishesissuerCRLs toallroles/Baoauth, then reloads anddrains native
HAProxy consumers. Go validates CRLissuer/signature/ThisUpdate/NextUpdate/serial
for everyissuer, includingroot-issuedintermediateCRL. Offline rootCRLs refresh
before their final24h. This does not claim revocation of RabbitMQprincipal from
CRL alone: compromise requires user/connection closure and token/credential/auth
role disable as documented inthreatmodel.
WorkerS3rotation changesonlyitskey, updatesownKV, restartsS3+worker withoutimage
build andchecksnewqueuedattachmentprocessing. Oldkey must return403.
CAprepare retainsold/newCA+CRLtrust; issue switchesissuer andallmanagedleaves;
retire removesoldCA/issuer/authCRLs. Nativeconsumers reload/drain at eachphase.
No statement of zero-downtimeCArollover: errors/recovery are measured underload.
## Recovery и безопасная остановка
```sh
python3 scripts/securityctl.py recover openbao
python3 scripts/securityctl.py recover api
make up
make down
```
ExpiredBao/operatortransport can be replaced byofflineoperatorleaf for verified
restart/unseal, then a restrictedBao-issuedleaf. Never disableCAverification.
`make down` preservesRaft/applicationvolumes andoperatorstate. Intentional deletion
of **your syntheticstand data**: `docker compose --env-file .env down --volumes`;
it does not deleteofflineoperatorstate, which must be managed separately and
never reused accidentally with unrelatedvolumes.
`make test-pki` executes3freshisolatedprojects with20s APIleaves, renewal/expiry,
oldleafrevoke, workerkeyrotation, CAprepare/issue/retire, telemetry/nativeTLS checks
and retaineddata. Cleanup is restricted to itsgeneratedproject/volumes/operator
state; existinglab6volumes are not removed. Fullresults/limitations belong in
[REPORT](../../REPORT.md), [trustmatrix](../../contracts/trust-matrix.md) and
`evidence/lab7/track2.json`.
+28
View File
@@ -0,0 +1,28 @@
ui = true
api_addr = "https://openbao:8200"
cluster_addr = "https://127.0.0.1:8201"
storage "raft" {
path = "/openbao/file"
node_id = "mtusi-lab7"
performance_multiplier = 1
}
listener "tcp" {
address = "0.0.0.0:8200"
cluster_address = "127.0.0.1:8201"
tls_cert_file = "/run/identity/current/tls.crt"
tls_key_file = "/run/identity/current/tls.key"
tls_client_ca_file = "/run/identity/current/ca.crt"
tls_min_version = "tls12"
tls_disable_client_certs = false
tls_require_client_cert = true
}
audit "file" "file" {
description = "Persistent protected lab7 operator and service audit"
options {
file_path = "/openbao/audit/audit.log"
log_raw = "false"
}
}
+21 -4
View File
@@ -1,7 +1,24 @@
# Конфигурация наблюдаемости — реализовать
# OTel Collector
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
`collector.yaml` сохраняет traces/metrics/logs pipelines. API/worker/relay шлют
OTLP HTTP через mTLS gateway `otel-collector:4318`: только authenticated CN
`api`, `worker`, `relay` и POST `/v1/traces`, `/v1/metrics`, `/v1/logs`.
Native receiver — `127.0.0.1:14318`; отдельного gRPC receiver нет.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Collector экспортирует:
- метрики — loopback pull-exporter `18889`, через mTLS gateway `:8889`;
- логи — HTTPS/mTLS в `https://loki:3100/otlp` (итоговый `/otlp/v1/logs`);
- трассы — GRPCS/mTLS в `tempo:4437`, где допускается только CN `collector`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Exporters используют own identity `current/{ca.crt,tls.crt,tls.key}` в readonly
`/run/identity`. Проверка CA/hostname не отключается. Native self-metrics —
`127.0.0.1:18888`, health — `127.0.0.1:13133`; mTLS gateways — `:8888`
(GET `/metrics`) и `:13134` (GET `/`), только CN `prometheus`/`operator`.
Native plaintext endpoints не публикуются и недоступны соседним namespaces.
`memory_limiter` — 140 MiB, batch — 5 с/1024. Loki/Tempo очереди ограничены
10 MiB (`sizer: bytes`), retry не дольше 30 с; отказ телеметрии не должен
блокировать business readiness. Gateway ACL/TLS config находятся в
`../telemetry-gateway/collector.cfg`; namespace mounts/restarts и lifecycle
trust consumers выполняет operator orchestration. Конфигурация не заменяет
live проверки доставки трёх signals, wrong-CN rejection и revocation.
+92
View File
@@ -0,0 +1,92 @@
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
processors:
memory_limiter:
check_interval: 1s
# limit_mib, not limit_percentage: Docker Desktop cgroup limits are easy to
# misread and a percentage would fall back to the VM total.
limit_mib: 140
spike_limit_mib: 40
batch:
timeout: 5s
send_batch_size: 1024
exporters:
# Pull-based: no sending_queue/retry for this exporter.
prometheus:
endpoint: 127.0.0.1:18889
translation_strategy: UnderscoreEscapingWithSuffixes
resource_constant_labels:
included:
- service.name
- service.instance.id
- deployment.environment.name
- service.version
otlp_http/loki:
endpoint: https://loki:3100/otlp
tls:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: "1.2"
sending_queue:
enabled: true
sizer: bytes
queue_size: 10485760
num_consumers: 2
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 30s
timeout: 5s
otlp_grpc/tempo:
endpoint: tempo:4437
tls:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: "1.2"
sending_queue:
enabled: true
sizer: bytes
queue_size: 10485760
num_consumers: 2
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 30s
timeout: 5s
extensions:
health_check:
endpoint: 127.0.0.1:13133
service:
extensions: [health_check]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 127.0.0.1
port: 18888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_grpc/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/loki]
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
set -eu
# PostgreSQL requires its private key to be owned by postgres and mode 0600.
# The role mount remains read-only; this copy is in the container's tmpfs.
umask 077
cp /run/identity/current/tls.key /tmp/postgres.key
chmod 600 /tmp/postgres.key
exec /usr/local/bin/docker-entrypoint.sh postgres \
-c ssl=on \
-c ssl_cert_file=/run/identity/current/tls.crt \
-c ssl_key_file=/tmp/postgres.key \
-c ssl_ca_file=/run/identity/current/ca.crt \
-c hba_file=/etc/postgresql/pg_hba.conf \
-c password_encryption=scram-sha-256 \
-c log_statement=none
+7
View File
@@ -0,0 +1,7 @@
# Only the operator inside this container can use the local Unix socket.
# No PostgreSQL socket directory is mounted into application containers.
local all all trust
hostnossl all all 0.0.0.0/0 reject
hostnossl all all ::/0 reject
hostssl all all 0.0.0.0/0 scram-sha-256
hostssl all all ::/0 scram-sha-256
+64
View File
@@ -0,0 +1,64 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: otel-collector
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
static_configs:
- targets: ["otel-collector:8889"]
- job_name: otel-collector-self
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
static_configs:
- targets: ["otel-collector:8888"]
- job_name: haproxy
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
metrics_path: /metrics
static_configs:
- targets: ["lb:8404"]
- job_name: rabbitmq
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
static_configs:
- targets: ["broker:15693"]
- job_name: loki
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
static_configs:
- targets: ["loki:3100"]
- job_name: tempo
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
metrics_path: /metrics
static_configs:
- targets: ["tempo:3200"]
+160
View File
@@ -0,0 +1,160 @@
groups:
- name: lab6-alerts
interval: 5s
rules:
- alert: APIErrorBudgetFastBurn
expr: slo:api_error_ratio:1h > 0.072 and slo:api_error_ratio:5m > 0.072 and on() sum(increase(haproxy_backend_http_responses_total{proxy="api_backend"}[5m])) >= 20
for: 0s
labels:
severity: page
slo: api-availability
annotations:
summary: API 5xx burn rate is above 14.4x
runbook: infra/runbooks/slo-burn.md
- alert: APIErrorBudgetSlowBurn
expr: slo:api_error_ratio:6h > 0.03 and slo:api_error_ratio:30m > 0.03 and on() sum(increase(haproxy_backend_http_responses_total{proxy="api_backend"}[30m])) >= 100
for: 0s
labels:
severity: ticket
slo: api-availability
annotations:
summary: API 5xx burn rate is above 6x
runbook: infra/runbooks/slo-burn.md
- alert: TTRErrorBudgetFastBurn
expr: slo:job_ttr_bad_ratio:1h > 0.144 and slo:job_ttr_bad_ratio:5m > 0.144 and on() (sum(increase(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[5m])) or vector(0)) + (sum(increase(messenger_jobs_ttr_missed_total[5m])) or vector(0)) >= 10
for: 0s
labels:
severity: page
slo: time-to-ready
annotations:
summary: Jobs are missing the 30s time-to-ready objective
runbook: infra/runbooks/queue-lag.md
- alert: TTRErrorBudgetSlowBurn
expr: slo:job_ttr_bad_ratio:6h > 0.06 and slo:job_ttr_bad_ratio:30m > 0.06 and on() (sum(increase(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[30m])) or vector(0)) + (sum(increase(messenger_jobs_ttr_missed_total[30m])) or vector(0)) >= 30
for: 0s
labels:
severity: ticket
slo: time-to-ready
annotations:
summary: Time-to-ready budget is burning slowly
runbook: infra/runbooks/queue-lag.md
- alert: QueueOldestJobAgeHigh
expr: max(messenger_queue_oldest_job_age_seconds) > 120
for: 10m
labels:
severity: warning
annotations:
summary: The oldest queued/processing job is older than 2 minutes
runbook: infra/runbooks/queue-lag.md
- alert: QueueOldestJobAgeCritical
expr: max(messenger_queue_oldest_job_age_seconds) > 600
for: 5m
labels:
severity: page
annotations:
summary: The oldest queued/processing job is older than 10 minutes
runbook: infra/runbooks/queue-lag.md
- alert: QueueDepthGrowing
expr: |
max(rabbitmq_queue_messages_ready{queue="attachment.process.v1"}) > 20
and on() max(deriv(rabbitmq_queue_messages_ready{queue="attachment.process.v1"}[10m])) > 0
for: 10m
labels:
severity: warning
annotations:
summary: RabbitMQ ready depth is growing
runbook: infra/runbooks/queue-lag.md
- alert: JobsOverdue
expr: max(messenger_jobs_overdue) > 0
for: 2m
labels:
severity: warning
slo: time-to-ready
annotations:
summary: Jobs have been queued/processing for more than 30 seconds
runbook: infra/runbooks/queue-lag.md
- alert: WorkerSaturated
expr: |
(sum(messenger_worker_busy) / clamp_min(sum(messenger_worker_capacity), 1) > 0.8)
and (max(messenger_queue_oldest_job_age_seconds) > 120)
for: 10m
labels:
severity: warning
annotations:
summary: Worker slots are saturated while the queue is aging
runbook: infra/runbooks/queue-lag.md
- alert: DBPoolSaturated
expr: |
(
(
sum(rate(messenger_db_pool_empty_acquire_wait_seconds_total[5m]))
/
clamp_min(sum(rate(messenger_db_pool_empty_acquire_total[5m])), 1e-9)
> 0.05
)
and (sum(rate(messenger_db_pool_empty_acquire_total[5m])) > 0.1)
)
or (sum(messenger_db_pool_used) / clamp_min(sum(messenger_db_pool_max), 1) > 0.8)
for: 5m
labels:
severity: warning
annotations:
summary: PostgreSQL pool is waiting or nearly exhausted
runbook: infra/runbooks/db-availability.md
- alert: CollectorDroppedTelemetry
expr: |
sum(rate(otelcol_receiver_failed_spans[5m])) > 0
or sum(rate(otelcol_receiver_failed_metric_points[5m])) > 0
or sum(rate(otelcol_receiver_failed_log_records[5m])) > 0
or sum(rate(otelcol_receiver_refused_spans[5m])) > 0
or sum(rate(otelcol_receiver_refused_metric_points[5m])) > 0
or sum(rate(otelcol_receiver_refused_log_records[5m])) > 0
or sum(rate(otelcol_exporter_send_failed_spans[5m])) > 0
or sum(rate(otelcol_exporter_send_failed_log_records[5m])) > 0
or sum(rate(otelcol_exporter_send_failed_metric_points[5m])) > 0
or sum(rate(otelcol_exporter_enqueue_failed_spans[5m])) > 0
or sum(rate(otelcol_exporter_enqueue_failed_log_records[5m])) > 0
or sum(rate(otelcol_exporter_enqueue_failed_metric_points[5m])) > 0
or sum(otelcol_exporter_queue_size) >= sum(otelcol_exporter_queue_capacity) * 0.9
for: 5m
labels:
severity: warning
annotations:
summary: Collector is dropping or refusing telemetry
runbook: infra/runbooks/telemetry-backend-down.md
- alert: TelemetryStorageDown
expr: up{job=~"loki|tempo"} == 0
for: 2m
labels:
severity: warning
component: telemetry
annotations:
summary: Loki or Tempo is unavailable; Collector queues are bounded
runbook: infra/runbooks/telemetry-backend-down.md
- alert: TelemetryCollectorDown
expr: up{job="otel-collector"} == 0
for: 2m
labels:
severity: warning
component: telemetry
annotations:
summary: OTel Collector is unavailable; application keeps running
runbook: infra/runbooks/telemetry-backend-down.md
- alert: APISLIMissing
expr: absent(slo:api_error_ratio:5m) or up{job="haproxy"} == 0
for: 2m
labels:
severity: page
annotations:
summary: Edge availability data is missing
runbook: infra/runbooks/api-errors.md
- alert: QueueMetricsStale
expr: |
(absent(messenger_queue_oldest_job_age_seconds) or absent(messenger_jobs_accepted_total))
and on() (up{job="otel-collector"} == 1)
for: 2m
labels:
severity: warning
annotations:
summary: Queue/backlog metrics are missing
runbook: infra/runbooks/queue-lag.md
+95
View File
@@ -0,0 +1,95 @@
groups:
- name: slo
interval: 5s
rules:
- record: slo:api_error_ratio:5m
expr: |
sum(rate(haproxy_backend_http_responses_total{proxy="api_backend",code=~"5.."}[5m]))
/
clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="api_backend"}[5m])), 0.001)
- record: slo:api_error_ratio:1h
expr: |
sum(rate(haproxy_backend_http_responses_total{proxy="api_backend",code=~"5.."}[1h]))
/
clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="api_backend"}[1h])), 0.001)
- record: slo:api_error_ratio:6h
expr: |
sum(rate(haproxy_backend_http_responses_total{proxy="api_backend",code=~"5.."}[6h]))
/
clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="api_backend"}[6h])), 0.001)
- record: slo:api_error_ratio:30m
expr: |
sum(rate(haproxy_backend_http_responses_total{proxy="api_backend",code=~"5.."}[30m]))
/
clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="api_backend"}[30m])), 0.001)
- record: slo:job_ttr_bad_ratio:5m
expr: |
(
(sum(rate(messenger_jobs_ttr_missed_total[5m])) or vector(0))
/
clamp_min(
(sum(rate(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[5m])) or vector(0))
+ (sum(rate(messenger_jobs_ttr_missed_total[5m])) or vector(0)),
0.001
)
)
and on() (
(sum(increase(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[5m])) or vector(0))
+ (sum(increase(messenger_jobs_ttr_missed_total[5m])) or vector(0))
) >= 10
- record: slo:job_ttr_bad_ratio:1h
expr: |
(
(sum(rate(messenger_jobs_ttr_missed_total[1h])) or vector(0))
/
clamp_min(
(sum(rate(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[1h])) or vector(0))
+ (sum(rate(messenger_jobs_ttr_missed_total[1h])) or vector(0)),
0.001
)
)
and on() (
(sum(increase(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[1h])) or vector(0))
+ (sum(increase(messenger_jobs_ttr_missed_total[1h])) or vector(0))
) >= 10
- record: slo:job_ttr_bad_ratio:6h
expr: |
(
(sum(rate(messenger_jobs_ttr_missed_total[6h])) or vector(0))
/
clamp_min(
(sum(rate(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[6h])) or vector(0))
+ (sum(rate(messenger_jobs_ttr_missed_total[6h])) or vector(0)),
0.001
)
)
and on() (
(sum(increase(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[6h])) or vector(0))
+ (sum(increase(messenger_jobs_ttr_missed_total[6h])) or vector(0))
) >= 30
- record: slo:job_ttr_bad_ratio:30m
expr: |
(
(sum(rate(messenger_jobs_ttr_missed_total[30m])) or vector(0))
/
clamp_min(
(sum(rate(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[30m])) or vector(0))
+ (sum(rate(messenger_jobs_ttr_missed_total[30m])) or vector(0)),
0.001
)
)
and on() (
(sum(increase(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[30m])) or vector(0))
+ (sum(increase(messenger_jobs_ttr_missed_total[30m])) or vector(0))
) >= 30
- name: slo-long
interval: 1m
rules:
- record: slo:api_error_ratio:7d
expr: |
sum(rate(haproxy_backend_http_responses_total{proxy="api_backend",code=~"5.."}[7d]))
/
clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="api_backend"}[7d])), 0.001)
- record: slo:api_budget_remaining:7d
expr: clamp(1 - (slo:api_error_ratio:7d / 0.005), 0, 1)
+65
View File
@@ -0,0 +1,65 @@
rule_files:
- ../rules/slo.yml
- ../rules/alerts.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'messenger_job_time_to_ready_seconds_bucket{le="30.0"}'
values: '0+10x10'
- series: 'messenger_job_time_to_ready_seconds_count'
values: '0+10x10'
promql_expr_test:
- expr: slo:job_ttr_bad_ratio:5m
eval_time: 5m
exp_samples:
- labels: '{__name__="slo:job_ttr_bad_ratio:5m"}'
value: 0
- interval: 1m
input_series:
- series: 'messenger_jobs_ttr_missed_total'
values: '0+10x10'
promql_expr_test:
- expr: slo:job_ttr_bad_ratio:5m
eval_time: 5m
exp_samples:
- labels: '{__name__="slo:job_ttr_bad_ratio:5m"}'
value: 1
- interval: 1m
input_series:
- series: 'messenger_job_time_to_ready_seconds_bucket{le="30.0"}'
values: '10+0x5 stale'
- series: 'messenger_job_time_to_ready_seconds_count'
values: '10+0x5 stale'
- series: 'messenger_jobs_ttr_missed_total'
values: '0+10x20'
promql_expr_test:
- expr: slo:job_ttr_bad_ratio:5m
eval_time: 15m
exp_samples:
- labels: '{__name__="slo:job_ttr_bad_ratio:5m"}'
value: 1
- interval: 1m
input_series:
- series: 'messenger_job_time_to_ready_seconds_bucket{le="30.0"}'
values: '0+5x10'
- series: 'messenger_job_time_to_ready_seconds_count'
values: '0+10x10'
- series: 'messenger_jobs_ttr_missed_total'
values: '0+2x10'
promql_expr_test:
- expr: slo:job_ttr_bad_ratio:5m
eval_time: 5m
exp_samples:
- labels: '{__name__="slo:job_ttr_bad_ratio:5m"}'
value: 0.2857142857142857
- interval: 1m
input_series:
- series: 'messenger_job_time_to_ready_seconds_bucket{le="30.0"}'
values: '0x10'
- series: 'messenger_jobs_ttr_missed_total'
values: '0 6 6 6 6 6 6 6 6 6 6'
alert_rule_test:
- eval_time: 5m
alertname: TTRErrorBudgetFastBurn
exp_alerts: []
+31
View File
@@ -0,0 +1,31 @@
global
log stdout format raw local0
maxconn 256
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
timeout connect 3s
timeout client 10s
timeout server 10s
frontend operator_management
bind *:15671 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl operator ssl_c_s_dn(CN) -m str operator
http-request deny deny_status 403 unless operator
default_backend management_loopback
backend management_loopback
server management 127.0.0.1:15672
frontend prometheus_scrape
bind *:15693 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl monitor ssl_c_s_dn(CN) -m str prometheus operator
http-request deny deny_status 403 unless monitor
http-request deny deny_status 403 unless { method GET } { path /metrics }
default_backend metrics_loopback
backend metrics_loopback
server metrics 127.0.0.1:15692
+1
View File
@@ -0,0 +1 @@
[rabbitmq_management,rabbitmq_prometheus,rabbitmq_auth_mechanism_ssl].
+24
View File
@@ -0,0 +1,24 @@
# Native AMQP TLS, no plaintext or password-mechanism fallback.
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.cacertfile = /run/identity/current/ca.crt
ssl_options.certfile = /run/identity/current/tls.crt
ssl_options.keyfile = /run/identity/current/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
auth_mechanisms.1 = EXTERNAL
ssl_cert_login_from = subject_alternative_name
ssl_cert_login_san_type = dns
ssl_cert_login_san_index = 0
definitions.import_backend = local_filesystem
definitions.local.path = /run/backend/definitions.json
# Admin/scrape transports never leave this container's shared loopback boundary.
management.tcp.ip = 127.0.0.1
management.tcp.port = 15672
prometheus.tcp.ip = 127.0.0.1
prometheus.tcp.port = 15692
prometheus.return_per_object_metrics = true
+15
View File
@@ -0,0 +1,15 @@
bind 0.0.0.0
port 0
tls-port 6379
tls-cert-file /run/identity/current/tls.crt
tls-key-file /run/identity/current/tls.key
tls-ca-cert-file /run/identity/current/ca.crt
tls-auth-clients no
tls-protocols "TLSv1.2 TLSv1.3"
aclfile /run/backend/users.acl
dir /data
appendonly yes
appendfsync everysec
save 60 1
maxmemory 64mb
maxmemory-policy allkeys-lru
+8
View File
@@ -0,0 +1,8 @@
# API error / availability SLI
1. Grafana → Lab6 → API overview. Check `slo:api_error_ratio:5m` and the edge panel; 5xx at HAProxy is the SLI, API-side 5xx is diagnostic.
2. Prometheus → Status → Targets: `haproxy`, `otel-collector`, `rabbitmq` must be UP. If HAProxy is DOWN, no edge SLI exists; inspect `docker compose ps lb`.
3. HAProxy stats `http://127.0.0.1:8404/stats`: look for DOWN replicas and `check` errors. A stale `X-Instance-Id` is the stopped replica.
4. If all replicas are DOWN, check `/health/ready` of one replica (5xx means DB/S3 dependency) and PostgreSQL logs.
5. For a slow handler, open a Tempo trace from the error panel; DB child span (`SELECT`/`INSERT`/`UPDATE`/`BEGIN`/`COMMIT`) duration vs HTTP span shows whether PostgreSQL or the handler is slow. Correlate `trace_id` in Loki.
6. Recover DB/S3, wait for HAProxy `rise 2`, then verify a 2xx through the LB and resolved alert.
+8
View File
@@ -0,0 +1,8 @@
# PostgreSQL slow/unavailable
1. Edge SLI first: HAProxy may return 503/504 while API replicas are removed by `/health/ready`; API-side 5xx can therefore be near zero. Use the HAProxy panel and `up{job="haproxy"}`.
2. `docker compose ps postgres`; `docker compose logs --tail=100 postgres`; `pg_isready` from a replica.
3. Prometheus: `messenger_db_pool_used/idle/max`, `messenger_db_pool_empty_acquire_total`, `rate(...wait_seconds)`; API/worker DB spans in Tempo (`SELECT`/`INSERT`/`UPDATE`/`BEGIN`/`COMMIT`, `pool.acquire`) show failures/latency.
4. Loki: `{service_name=~"messenger-api|messenger-worker"} | severity_text="error" | trace_id="<id>"`. A handler span with a long DB child span is a DB problem; a long handler without a DB child is an application problem.
5. If PostgreSQL was stopped, start it, wait for health, then let the pool reconnect. Worker deliveries are requeued; verify no accepted job is lost (jobs accepted/ready/failed counts).
6. Confirm the alert resolved; record injection/restore and first successful request timestamps.
+8
View File
@@ -0,0 +1,8 @@
# Queue lag / time-to-ready
1. Grafana → Lab6 → Jobs and queue: `messenger_queue_oldest_job_age_seconds`, `rabbitmq_queue_messages_ready`, `messenger_worker_busy/capacity`, TTR p95.
2. If oldest age grows and `worker_busy == capacity`, the worker is saturated: inspect `worker` logs (`job claimed`, `job retry scheduled`) and `WORKER_CONCURRENCY`.
3. If queue depth grows but `worker_busy == 0`, the worker is stopped or cannot connect to the broker: `docker compose ps worker`, worker `/health/ready`, broker `rabbitmqctl list_queues`.
4. If retries grow, filter Loki `{service_name="messenger-worker"} | severity_text="error"` and trace `job.process` attempts; check `error_code`.
5. For a lost delivery, relay logs `outbox publish cycle` / `lost queued jobs reconciled` and `jobctl failed`.
6. Restore worker/broker, verify queue depth < 5 and oldest age < 5s for two scrapes, then confirm the alert resolved.
+15
View File
@@ -0,0 +1,15 @@
# SLO burn-rate
1. Open Grafana → Lab6 → API overview and Jobs and queue.
2. Check `slo:api_error_ratio:1h` + `5m` for fast burn, `6h` + `30m`
for slow burn; TTR uses `slo:job_ttr_bad_ratio:*`.
3. Fast page means the current hour is consuming the 7-day error budget at
≥14.4×. Confirm edge traffic in HAProxy (`proxy="api_backend"`), then inspect
API traces for 5xx and DB spans (`SELECT`/`INSERT`/`UPDATE`/`BEGIN`/`COMMIT`)
or missing worker `job.process` spans.
4. Slow ticket means a sustained 6-hour burn. It can fire with a low current
rate; do not suppress it until the 30m window is below 3% (API) or 6% (TTR).
5. Resolve only after the SLO ratio stays below the fast/slow thresholds and
the underlying dependency (worker, PostgreSQL, broker) is healthy.
6. Record injection/restore UTC and the first firing/resolved timestamps in
`evidence/lab6/track2/`.
+8
View File
@@ -0,0 +1,8 @@
# Telemetry backend down
1. This is an observability incident, not a business outage. First verify API: `curl -fsS http://127.0.0.1:8080/health/ready` and a smoke request.
2. `docker compose ps otel-collector prometheus loki tempo grafana`.
3. If Tempo/Loki is down, Collector exporter queues fill; inspect `otelcol_exporter_queue_size`, `otelcol_exporter_send_failed_*`, `otelcol_processor_refused_*`. Queues are bounded by `sizer: bytes`; the Collector does not grow without limit.
4. If the Collector is down, Prometheus `up{job="otel-collector"}=0`; the application continues to accept work. Application OTLP export failures are best-effort and do not affect `/health/ready`.
5. Restart the failed backend/collector; confirm `up`, queue drains, and no new refused records. Lost telemetry is bounded and documented; business data in PostgreSQL/S3 is unaffected.
6. Do not stop Prometheus while diagnosing another alert: without Prometheus there is no rule evaluation. Use HAProxy stats and container logs as fallback.
+76
View File
@@ -0,0 +1,76 @@
# SeaweedFS identities and recovery
The pinned SeaweedFS 4.51 image runs as one logical `s3` role: the
`seaweedfs` container owns the network namespace and persistent volume;
the `s3` container shares that namespace and serves native HTTPS.
Do not downgrade to 3.80: its COPY authorization allowed foreign-source reads.
Owned COPY plus forbidden foreign-source/destination COPY checks remain required.
`infra/s3/s3.json` declares permissions, not credentials. `securityctl.py`
renders operator-local credentials into the read-only `/run/backend/s3.json`
mount of `s3`. Only `s3-init` and the host operator use the operator identity
as clients; application processes receive only their own credentials.
- `operator` creates the application bucket and maintains the recovery sentinel.
- `api` reads attachment/staging objects and writes staging objects only.
- `worker` reads/writes attachment/staging objects and lists the application
bucket. Bucket-level LIST can disclose foreign-prefix metadata; Write also
permits DELETE within the allowed prefixes.
## Listener isolation
| Listener | Binding and policy |
| --- | --- |
| S3 HTTPS 8333 | Native TLS; SigV4 credentials and prefix ACLs. Host publication is loopback-only. |
| S3 auxiliary gRPC 18333 | Shared namespace; mTLS trusts the role CA and permits only CN `s3`. |
| Master HTTP 9333, filer HTTP 8888, volume HTTP 8080 | Namespace loopback only; not published. |
| Master gRPC 19333, filer gRPC 18888, volume gRPC 18080 | Namespace loopback only, with the same CN `s3` mTLS restriction. |
| Iceberg HTTP 8181, Lance HTTP 9101 | Disabled by `-port.iceberg=0` and `-port.lance=0`; absence must be probed, not excluded from isolation checks. |
The three internal gRPC Unix sockets stay in the owner's private `/tmp`.
The S3 HTTP Unix socket stays in the S3 container's private `/tmp`.
No additional PKI role, client allowance, or certificate SAN is needed.
Auxiliary 18333 is not an HTTP readiness port: test TLS rejection for
`api`, `worker`, and `operator`, and successful mTLS only for `s3`.
Flags were obtained from the pinned binary with `weed s3 -help` and
`weed server -help`. The configured filer address uses SeaweedFS's explicit
HTTP/gRPC form, `127.0.0.1:8888.18888`, matching the master discovery registry.
The shipped [address parser](https://github.com/seaweedfs/seaweedfs/blob/ffa87c25f/weed/pb/server_address.go)
supports this form. The
[discovery implementation](https://github.com/seaweedfs/seaweedfs/blob/ffa87c25f/weed/wdclient/filer_client.go)
compares raw address spellings and refreshes every five minutes; removing
`127.0.0.1:8888` when discovering its explicit-gRPC equivalent does not mean
that no filer remains.
## Persistent body readiness
The filer's `/healthz` and the public API's DB/OpenBao health cannot prove that
previously stored volume bytes are readable. In the observed restart, S3
started before master leadership and volume topology had recovered.
`Controller.wait_s3()` uses the operator CA, verifies `localhost`, presents
the operator leaf, and signs requests for the published HTTPS S3 endpoint.
It creates exactly one random `operator-readiness/<key>` object in the
configured application bucket on first initialization. Its 64 KiB body forces
volume-backed storage rather than a metadata-only/HEAD probe. Expected bytes
and establishment state live in private `LAB7_OPERATOR_STATE/s3-readiness.json`.
The application identities cannot read, overwrite, or delete this prefix.
After establishment, readiness performs GET and full byte comparison only:
it never rewrites a missing object or reseeds a volume. Missing/unavailable
storage is retried within the readiness deadline; changed bytes or permanent
authorization errors fail the operation. Network operations use five-second
timeouts and body reads are size-capped and deadline-checked.
`wait_ready()` requires this body check before public HTTPS health succeeds.
Store restart first checks the old sentinel, restarts owners, recreates
shared-namespace consumers, checks old bytes again, then restarts applications.
This preserves the existing volumes and does not retry or alter public tests.
Required targeted verification after applying configuration: retain an uploaded
attachment, perform the operator restart hook, read its complete body once,
then compare it byte-for-byte. Also exercise a new staging upload/async COPY,
the existing COPY ACL matrix, auxiliary listener isolation, and the failure
case where an established readiness object is unavailable. Do not remove the
private readiness state to make a persistence check pass.
+26
View File
@@ -0,0 +1,26 @@
{
"identities": [
{
"name": "operator",
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
},
{
"name": "api",
"actions": [
"Read:messenger-attachments/attachments/*",
"Read:messenger-attachments/staging/*",
"Write:messenger-attachments/staging/*"
]
},
{
"name": "worker",
"actions": [
"Read:messenger-attachments/attachments/*",
"Write:messenger-attachments/attachments/*",
"Read:messenger-attachments/staging/*",
"Write:messenger-attachments/staging/*",
"List:messenger-attachments"
]
}
]
}
+35
View File
@@ -0,0 +1,35 @@
# One logical s3 role: HTTP 9333/8888/8080 and gRPC 19333/18888/18080
# stay on namespace loopback. S3 HTTPS 8333 is published only on host loopback.
# Auxiliary gRPC 18333 requires mTLS CN s3; Iceberg 8181 and Lance 9101
# are disabled by the standalone S3 command, not hidden by test exclusions.
[grpc]
ca = "/run/identity/current/ca.crt"
[grpc.master]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
allowed_commonNames = "s3"
[grpc.volume]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
allowed_commonNames = "s3"
[grpc.filer]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
allowed_commonNames = "s3"
[grpc.s3]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
allowed_commonNames = "s3"
[grpc.client]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
[access]
ui = false
[filer.expose_directory_metadata]
enabled = false
+69
View File
@@ -0,0 +1,69 @@
# HAProxy 3.2; shares only the Collector network namespace.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
frontend collector_ingest
bind :4318 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
# The authenticated certificate CN, never an HTTP header, is the role.
acl writer ssl_c_s_dn(CN) -m str api worker relay
acl write_method method POST
acl write_path path -m str /v1/traces /v1/metrics /v1/logs
http-request allow if writer write_method write_path
http-request deny deny_status 403
default_backend collector_otlp
frontend collector_metrics
bind :8888 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl reader ssl_c_s_dn(CN) -m str prometheus operator
acl read_method method GET
acl metrics_path path -m str /metrics
http-request allow if reader read_method metrics_path
http-request deny deny_status 403
default_backend collector_self_metrics
frontend application_metrics
bind :8889 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl reader ssl_c_s_dn(CN) -m str prometheus operator
acl read_method method GET
acl metrics_path path -m str /metrics
http-request allow if reader read_method metrics_path
http-request deny deny_status 403
default_backend collector_application_metrics
frontend collector_health
# 13133 is already the private receiver; the TLS gateway uses 13134.
bind :13134 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl reader ssl_c_s_dn(CN) -m str prometheus operator
acl read_method method GET
acl health_path path -m str /
http-request allow if reader read_method health_path
http-request deny deny_status 403
default_backend collector_private_health
backend collector_otlp
server local 127.0.0.1:14318
backend collector_self_metrics
server local 127.0.0.1:18888
backend collector_application_metrics
server local 127.0.0.1:18889
backend collector_private_health
server local 127.0.0.1:13133
+36
View File
@@ -0,0 +1,36 @@
# HAProxy 3.2 public browser ingress; Grafana enforces its normal user auth.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
timeout tunnel 30s
frontend grafana_browser_https
# Browsers verify the server certificate; no client certificate is needed.
bind :3000 ssl crt /run/identity/current/tls.pem
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto https
http-request set-header X-Forwarded-Port 3000
# No auth-proxy identity may be supplied by a browser.
http-request del-header X-WEBAUTH-USER
http-request del-header X-WEBAUTH-EMAIL
http-request del-header X-WEBAUTH-NAME
http-response set-header Strict-Transport-Security "max-age=31536000"
default_backend grafana_private
backend grafana_private
server local 127.0.0.1:13000
+56
View File
@@ -0,0 +1,56 @@
# HAProxy 3.2; Loki HTTP and gRPC remain on loopback.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
frontend loki_https
bind :3100 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl collector ssl_c_s_dn(CN) -m str collector
acl grafana ssl_c_s_dn(CN) -m str grafana
acl prometheus ssl_c_s_dn(CN) -m str prometheus
acl operator ssl_c_s_dn(CN) -m str operator
acl read_method method GET
acl write_method method POST
acl query_method method GET POST
acl ingest_path path -m str /otlp/v1/logs /loki/api/v1/push
acl query_path path -m str /loki/api/v1/query /loki/api/v1/query_range /loki/api/v1/labels /loki/api/v1/series
acl label_values path -m reg ^/loki/api/v1/label/[A-Za-z_][A-Za-z0-9_]*/values$
acl explore_path path -m str /loki/api/v1/index/stats /loki/api/v1/index/volume /loki/api/v1/index/volume_range /loki/api/v1/patterns /loki/api/v1/detected_fields /loki/api/v1/detected_labels
acl field_values path -m reg ^/loki/api/v1/detected_field/[A-Za-z_][A-Za-z0-9_]*/values$
acl health_path path -m str /metrics /ready
acl status_path path -m str /loki/api/v1/status/buildinfo /config /services /ring
# Preserve the existing single-tenant store; a client cannot select a tenant.
http-request set-header X-Scope-OrgID fake
http-request allow if collector write_method ingest_path
http-request allow if grafana query_method query_path
http-request allow if grafana read_method label_values
http-request allow if grafana read_method explore_path
http-request allow if grafana read_method field_values
http-request allow if prometheus read_method health_path
http-request allow if operator query_method query_path
http-request allow if operator read_method label_values
http-request allow if operator read_method explore_path
http-request allow if operator read_method field_values
http-request allow if operator read_method health_path
http-request allow if operator read_method status_path
# Collector cannot query; Grafana cannot push, delete or administer.
http-request deny deny_status 403
default_backend loki_private
backend loki_private
server local 127.0.0.1:13100
+46
View File
@@ -0,0 +1,46 @@
# HAProxy 3.2; Prometheus must listen only on 127.0.0.1:19090.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
frontend prometheus_https
bind :9090 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl grafana ssl_c_s_dn(CN) -m str grafana
acl prometheus ssl_c_s_dn(CN) -m str prometheus
acl operator ssl_c_s_dn(CN) -m str operator
acl read_method method GET
acl query_method method GET POST
acl query_path path -m str /api/v1/query /api/v1/query_range /api/v1/labels /api/v1/series /api/v1/metadata
acl label_values path -m reg ^/api/v1/label/[A-Za-z_][A-Za-z0-9_]*/values$
acl buildinfo_path path -m str /api/v1/status/buildinfo
acl health_path path -m str /metrics /-/healthy /-/ready
acl status_path path -m str /api/v1/status/buildinfo /api/v1/status/runtimeinfo /api/v1/status/flags /api/v1/status/config /api/v1/status/tsdb /api/v1/targets /api/v1/rules /api/v1/alerts
http-request allow if grafana query_method query_path
http-request allow if grafana read_method label_values
http-request allow if grafana read_method buildinfo_path
http-request allow if prometheus read_method health_path
http-request allow if operator query_method query_path
http-request allow if operator read_method label_values
http-request allow if operator read_method health_path
http-request allow if operator read_method status_path
# No role gets reload, quit, admin, federation, remote-write or OTLP writes.
http-request deny deny_status 403
default_backend prometheus_private
backend prometheus_private
server local 127.0.0.1:19090
+66
View File
@@ -0,0 +1,66 @@
# HAProxy 3.2; only the collector principal can use the OTLP gRPC gateway.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults tempo_http_defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
frontend tempo_https
bind :3200 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl grafana ssl_c_s_dn(CN) -m str grafana
acl prometheus ssl_c_s_dn(CN) -m str prometheus
acl operator ssl_c_s_dn(CN) -m str operator
acl read_method method GET
acl query_path path -m str /api/search /api/search/tags /api/v2/search/tags /api/metrics/query /api/metrics/query_range /api/echo
acl trace_path path -m reg ^/api/(v2/)?traces/[0-9a-fA-F]{1,32}$
acl tag_values path -m reg ^/api/(v2/)?search/tag/[A-Za-z0-9_.:-]+/values$
acl health_path path -m str /metrics /ready
acl status_path path -m str /status /api/status/buildinfo
http-request set-header X-Scope-OrgID fake
http-request allow if grafana read_method query_path
http-request allow if grafana read_method trace_path
http-request allow if grafana read_method tag_values
http-request allow if prometheus read_method health_path
http-request allow if operator read_method query_path
http-request allow if operator read_method trace_path
http-request allow if operator read_method tag_values
http-request allow if operator read_method health_path
http-request allow if operator read_method status_path
# The HTTP listener has no collector write, admin or alternate gRPC route.
http-request deny deny_status 403
default_backend tempo_private_http
backend tempo_private_http
server local 127.0.0.1:13200
# Separate defaults prevent inheriting HTTP options or HTTP log fields in TCP.
defaults tempo_grpc_defaults
mode tcp
log global
log-format "%Tt %b"
option dontlognull
timeout connect 2s
timeout client 30s
timeout server 30s
frontend tempo_otlp_tls
bind :4437 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required alpn h2
acl collector ssl_c_s_dn(CN) -m str collector
tcp-request content reject unless collector
default_backend tempo_private_otlp
backend tempo_private_otlp
server local 127.0.0.1:14317
+50
View File
@@ -0,0 +1,50 @@
server:
http_listen_address: 127.0.0.1
http_listen_port: 13200
grpc_listen_address: 127.0.0.1
grpc_listen_port: 9095
memberlist:
bind_addr: [127.0.0.1]
distributor:
ring:
instance_addr: 127.0.0.1
receivers:
otlp:
protocols:
grpc:
endpoint: 127.0.0.1:14317
ingester:
lifecycler:
address: 127.0.0.1
metrics_generator:
ring:
instance_addr: 127.0.0.1
querier:
frontend_worker:
frontend_address: 127.0.0.1:9095
query_frontend:
search:
default_result_limit: 20
max_result_limit: 1000
max_duration: 24h
storage:
trace:
backend: local
local:
path: /var/tempo/traces
wal:
path: /var/tempo/wal
compactor:
compaction:
block_retention: 72h
usage_report:
reporting_enabled: false