Лабораторная 7: TLS, mTLS и OpenBao
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-11-28 01:28:30 +03:00
parent 20afc2c790
commit 2c2734df60
119 changed files with 8651 additions and 104 deletions
+12
View File
@@ -0,0 +1,12 @@
FROM public.ecr.aws/docker/library/golang:1.24.2-alpine@sha256:7772cb5322baa875edd74705556d08f0eeca7b9c4b5367754ce3f2f00041ccee AS build
ENV CGO_ENABLED=0 GOPROXY="https://proxy.golang.org|https://goproxy.io|direct"
WORKDIR /src/minio
ADD https://codeload.github.com/minio/minio/tar.gz/refs/tags/RELEASE.2025-09-07T16-13-09Z /tmp/minio.tar.gz
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build tar -xzf /tmp/minio.tar.gz --strip-components=1 && go build -o /out/minio .
WORKDIR /src/mc
ADD https://codeload.github.com/minio/mc/tar.gz/refs/tags/RELEASE.2025-08-13T08-35-41Z /tmp/mc.tar.gz
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build tar -xzf /tmp/mc.tar.gz --strip-components=1 && go build -o /out/mc .
FROM python:3.12-slim-bookworm@sha256:392307d22300de8b5986851a12d9176dfc0fc073e65bf6523ebd7dcbeb23564e
COPY --from=build /out/minio /out/mc /usr/local/bin/
ENTRYPOINT ["minio"]
+8 -4
View File
@@ -1,7 +1,11 @@
# Инфраструктура студента
# Инфраструктура лабораторной 7
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
Стенд задаёт compose.yaml, сборку приложения — Dockerfile, MinIO/mc — Dockerfile.s3. Проект mtusi-lab7 использует собственные volumes. Запуск с bootstrap и operator init/unseal выполняет scripts/up.sh.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Публичный API — https://localhost:8443, Grafana — https://localhost:17400, OpenBao — https://localhost:18200. Локальные TLS-порты Prometheus/Loki/Tempo предназначены для оператора с client certificate. Все проверки используют CA из secrets/ca/ca.crt. Plaintext API-порт на хост не публикуется.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
API-a/b, worker, publisher и cleaner запускаются через cert-auth OpenBao agent. Секреты поступают в tmpfs. Root token/unseal share в серверы и приложения не монтируются. PostgreSQL, Redis, S3 и RabbitMQ используют native TLS. RabbitMQ EXTERNAL связывает сертификат с username и queue ACL. Prometheus/Loki/Tempo/Collector имеют отдельные identity-aware boundaries с закрытым loopback hop.
Все сервисы имеют CPU/RAM limits. API/worker и proxies работают non-root, read_only, no-new-privileges и cap_drop ALL. Stateful сервисы сохраняют writable data volumes. Root filesystem также read-only, где совместимо. PostgreSQL/Redis/RabbitMQ имеют явный небольшой набор bootstrap capabilities для chown/setuid/setgid и доступа к данным, без сетевых/admin capabilities. MinIO сохраняет только DAC_OVERRIDE, данные пишет в volume. Модель угроз и ограничения находятся в security/THREAT_MODEL.md.
Список связей, identities, ACL, bootstrap и отрицательные проверки приведены в contracts/trust-matrix.md. Результаты и команды — в REPORT.md. Fault-сценарии выполняются последовательно. Безопасная остановка — docker compose down с сохранением volumes.
+446
View File
@@ -0,0 +1,446 @@
{
"uid": "messenger",
"title": "Messenger",
"schemaVersion": 40,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"tags": [
"lab6"
],
"panels": [
{
"id": 1,
"title": "API requests per second",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 0
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (method,route)(rate(messenger_http_requests_total[1m]))",
"legendFormat": "{{method}} {{route}}"
}
]
},
{
"id": 2,
"title": "API latency p50 / p95 / p99",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 0
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le)(rate(messenger_http_duration_seconds_bucket[1m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le)(rate(messenger_http_duration_seconds_bucket[1m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le)(rate(messenger_http_duration_seconds_bucket[1m])))",
"legendFormat": "p99"
}
]
},
{
"id": 3,
"title": "API 5xx ratio and 5-minute SLI",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total[1m])),0.001)",
"legendFormat": "5xx ratio"
},
{
"refId": "B",
"expr": "(1 - ((sum(increase(messenger_http_requests_total{status_class=\"5xx\"}[5m])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total[5m])),1))) and (sum(increase(messenger_http_requests_total[5m])) > 0)",
"legendFormat": "SLI 5m"
}
]
},
{
"id": 4,
"title": "Unfinished jobs and RabbitMQ ready messages",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "max((messenger_queue_depth) and on(service_instance_id) (time() - messenger_queue_observed_at_seconds < 10))",
"legendFormat": "unfinished jobs"
},
{
"refId": "B",
"expr": "max((messenger_queue_broker_ready) and on(service_instance_id) (time() - messenger_queue_observed_at_seconds < 10))",
"legendFormat": "broker ready"
}
]
},
{
"id": 5,
"title": "PostgreSQL pool use / capacity / acquisition",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 16
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(messenger_db_pool_used) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "used {{service_name}} {{service_instance_id}}"
},
{
"refId": "B",
"expr": "(messenger_db_pool_capacity) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "capacity {{service_name}} {{service_instance_id}}"
},
{
"refId": "C",
"expr": "(messenger_db_pool_waiting) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "acquiring {{service_name}} {{service_instance_id}}"
}
]
},
{
"id": 6,
"title": "Oldest unfinished job age",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 16
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "max((messenger_queue_oldest_age_seconds) and on(service_instance_id) (time() - messenger_queue_observed_at_seconds < 10))",
"legendFormat": "age"
}
]
},
{
"id": 7,
"title": "Worker busy / capacity",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 24
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum((messenger_worker_busy{service_name=\"messenger-worker\"}) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)) or vector(0)",
"legendFormat": "busy"
},
{
"refId": "B",
"expr": "sum((messenger_worker_capacity{service_name=\"messenger-worker\"}) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)) or vector(0)",
"legendFormat": "capacity"
}
]
},
{
"id": 8,
"title": "Worker attempts by outcome",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 24
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome)(rate(messenger_jobs_processed_total[1m]))",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 9,
"title": "Worker processing p95 and accepted-to-ready p95",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 32
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_job_duration_seconds_bucket[1m])))",
"legendFormat": "processing p95"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "time to ready p95"
}
]
},
{
"id": 10,
"title": "Process resident memory",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 32
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(messenger_process_memory_bytes) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
]
},
{
"id": 11,
"title": "Process CPU cores",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 40
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(rate(messenger_process_cpu_seconds_total[1m])) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
]
},
{
"id": 12,
"title": "Collector exporter failures / lost records",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 40
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "{__name__=~\"otelcol_exporter_(send_failed|enqueue_failed)_(spans|log_records|metric_points).*\"}",
"legendFormat": "{{__name__}} {{exporter}}"
}
]
},
{
"id": 13,
"title": "Application logs with trace IDs",
"type": "logs",
"gridPos": {
"h": 9,
"w": 24,
"x": 0,
"y": 48
},
"datasource": {
"type": "loki",
"uid": "loki"
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"messenger-.*\"}"
}
],
"options": {
"showTime": true,
"wrapLogMessage": true
}
},
{
"id": 14,
"title": "Recent application traces",
"type": "table",
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 57
},
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"targets": [
{
"refId": "A",
"queryType": "traceql",
"query": "{resource.service.name =~ \"messenger-.*\"}",
"tableType": "traces"
}
]
}
],
"annotations": {
"list": []
},
"templating": {
"list": []
}
}
@@ -0,0 +1,10 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: true
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
+53
View File
@@ -0,0 +1,53 @@
#!/bin/sh
# Active readiness bridge for open-source Nginx. No Docker socket or credentials.
set -eu
probe() {
if curl --max-time 2 --cacert /run/ca/ca.crt --cert /run/tls/server.crt --key /run/tls/server.key --fail --silent --output /dev/null "https://$1:8080/health/ready" 2>/dev/null; then
echo up > "/tmp/$1.health"
else
echo down > "/tmp/$1.health"
fi
}
control() { cat "/tmp/control-$1" 2>/dev/null || echo serve:boot; }
echo $$ > /tmp/healthwatch.pid
while :; do
sleep 1
probe api-a &
first=$!
probe api-b &
second=$!
wait "$first"
wait "$second"
# Read desired state AFTER probes. A generation is acknowledged only after
# the matching upstream configuration has been applied, never from a stale probe.
a_control=$(control api-a)
b_control=$(control api-b)
a_state=$(cat /tmp/api-a.health)
b_state=$(cat /tmp/api-b.health)
case "$a_control" in drain:*) a_state=down;; esac
case "$b_control" in drain:*) b_state=down;; esac
: > /tmp/upstreams.next
for service in api-a api-b; do
if [ "$service" = api-a ]; then state=$a_state; else state=$b_state; fi
suffix=''
[ "$state" = up ] || suffix=' down'
printf 'server %s:8080 resolve max_fails=1 fail_timeout=2s%s;\n' "$service" "$suffix" >> /tmp/upstreams.next
done
if ! cmp -s /tmp/upstreams.next /tmp/upstreams.conf; then
cp /tmp/upstreams.conf /tmp/upstreams.previous
# Rename on the same filesystem: readers never see missing/partial config.
cp /tmp/upstreams.next /tmp/upstreams.apply
mv -f /tmp/upstreams.apply /tmp/upstreams.conf
if nginx -t && nginx -s reload; then
echo 'readiness upstream set updated'
else
cp /tmp/upstreams.previous /tmp/upstreams.apply
mv -f /tmp/upstreams.apply /tmp/upstreams.conf
exit 1
fi
fi
printf '%s %s\n' "$a_control" "$a_state" > /tmp/applied-api-a.next
mv -f /tmp/applied-api-a.next /tmp/applied-api-a
printf '%s %s\n' "$b_control" "$b_state" > /tmp/applied-api-b.next
mv -f /tmp/applied-api-b.next /tmp/applied-api-b
done
+34
View File
@@ -0,0 +1,34 @@
auth_enabled: false
server:
http_listen_port: 13100
http_listen_address: 127.0.0.1
grpc_listen_address: 127.0.0.1
common:
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
instance_addr: 127.0.0.1
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
+60
View File
@@ -0,0 +1,60 @@
worker_processes 1;
pid /tmp/nginx.pid;
worker_shutdown_timeout 6s;
events { worker_connections 1024; }
http {
resolver 127.0.0.11 valid=1s ipv6=off;
resolver_timeout 1s;
log_format lab '$time_iso8601 $request_method $uri $status upstream=$upstream_addr '
'instance=$upstream_http_x_instance_id time=$request_time';
access_log /dev/stdout lab;
error_log /dev/stderr warn;
upstream api {
zone api 64k;
include /tmp/upstreams.conf;
}
server {
listen 8443 ssl;
ssl_certificate /run/tls/server.crt;
ssl_certificate_key /run/tls/server.key;
ssl_protocols TLSv1.2 TLSv1.3;
proxy_ssl_certificate /run/tls/server.crt;
proxy_ssl_certificate_key /run/tls/server.key;
proxy_ssl_trusted_certificate /run/ca/ca.crt;
proxy_ssl_crl /run/ca/crl.pem;
proxy_ssl_verify on;
proxy_ssl_server_name on;
proxy_ssl_name messenger-api;
client_max_body_size 1m;
client_body_timeout 5s;
proxy_http_version 1.1;
proxy_set_header Connection close;
proxy_set_header Host $host;
proxy_set_header X-Request-Id $http_x_request_id;
proxy_connect_timeout 1s;
proxy_read_timeout 5s;
proxy_send_timeout 5s;
proxy_next_upstream error timeout http_502 http_504;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 6s;
location ~ ^/api/v1/chats/[^/]+/attachments$ {
# Keep a proxy ceiling above the API limit so the API can return its JSON 413.
client_max_body_size 11m;
proxy_read_timeout 45s;
proxy_send_timeout 30s;
proxy_next_upstream off;
proxy_pass https://api;
}
location ~ ^/api/v1/attachments/[^/]+/content$ {
proxy_buffering off;
proxy_read_timeout 10s;
# A shared S3 outage returns 503 without marking the API itself down.
proxy_next_upstream error timeout http_502 http_504;
proxy_pass https://api;
}
location / {
proxy_pass https://api;
}
}
}
+10 -4
View File
@@ -1,7 +1,13 @@
# OpenBao — реализовать конфигурацию и политики
# OpenBao в лабораторной 7
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
Используется ghcr.io/openbao/openbao:2.2.2, обычный server mode, persistent file storage bao_data и TLS listener с клиентским сертификатом. Dev-mode выключен. disable_mlock — учебное ограничение контейнерного стенда, описанное в threat model.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
Оператор запускает scripts/bootstrap.py, затем scripts/bao.py init. Init создаёт одну unseal share с threshold1. Ответ init хранится только в secrets/operator/bao_init.json с правами0600. Каталог оператора имеет0700. Root token и share не монтируются в OpenBao и приложения. После restart сервера требуется scripts/bao.py unseal. API/worker restart сам по себе не требует unseal.
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
Политики находятся в policies/. Cert-auth роли api, worker, publisher и cleaner ограничены разрешёнными common names сертификатов. API-a/b используют policy api. Каждая policy читает только secret/data/своя-роль и допускает renew-self. Чтение чужого KV и изменение ACL policy запрещены.
Token имеет TTL60 секунд и max TTL120 секунд. Agent держит token в памяти, обновляет его или повторно выполняет cert login, читает KV и пишет только собственные секреты в tmpfs. Изменение KV/certificate перезапускает дочерний процесс без сборки image. Успешное renewal не продлевает cache deadline без успешного чтения KV. Deny401/403 останавливает child сразу. При sealed/unavailable Bao старый child работает только до истечения своей текущей границы.
scripts/rotate.py worker-secret меняет пароль DB worker и scoped KV. Перед ALTER сохраняется operator-only pending target. При потере ответа PUT выполняется read-back. Если результат неизвестен, повтор той же команды согласует сохранённый target без опасного rollback. scripts/rotate.py api-leaf перевыпускает API-a leaf, добавляет старый serial в CRL и OpenBao cert-auth CRL. Proxy stream connections ограничены60 секундами, новые соединения проверяют CRL.
Bootstrap trust основан на локальной CA, владельцем которой является оператор. Сервисный leaf действует двое суток. Bootstrap обновляет истекающие leaves; up.sh пересоздаёт контейнеры, чтобы native серверы и file mounts использовали новые certificates. Для немедленного отзыва выбранной старой identity используется отдельный проверенный rotation script. Автоматический rollover CA относится к следующему уровню исследования.
+12
View File
@@ -0,0 +1,12 @@
ui = false
disable_mlock = true
storage "file" { path = "/bao/data" }
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/run/tls/server.crt"
tls_key_file = "/run/tls/server.key"
tls_client_ca_file = "/run/ca/ca.crt"
tls_require_and_verify_client_cert = true
tls_min_version = "tls12"
}
api_addr = "https://openbao:8200"
+6
View File
@@ -0,0 +1,6 @@
path "secret/data/api" {
capabilities = ["read"]
}
path "auth/token/renew-self" {
capabilities = ["update"]
}
+6
View File
@@ -0,0 +1,6 @@
path "secret/data/cleaner" {
capabilities = ["read"]
}
path "auth/token/renew-self" {
capabilities = ["update"]
}
+6
View File
@@ -0,0 +1,6 @@
path "secret/data/publisher" {
capabilities = ["read"]
}
path "auth/token/renew-self" {
capabilities = ["update"]
}
+6
View File
@@ -0,0 +1,6 @@
path "secret/data/worker" {
capabilities = ["read"]
}
path "auth/token/renew-self" {
capabilities = ["update"]
}
+8 -4
View File
@@ -1,7 +1,11 @@
# Конфигурация наблюдаемости — реализовать
# Наблюдаемость через TLS в lab7
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Используются OpenTelemetry SDK/API/exporter1.45.2 и Collector contrib0.123.0. SDK создаёт metrics/logs/traces для API, publisher и worker. Контекст сохраняется в PostgreSQL и передаётся в RabbitMQ headers. Входящий HTTP propagation принимает только traceparent/tracestate с ограниченной длиной.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
SDK отправляет OTLP/gRPC по mTLS на otel-collector:4317. Boundary проверяет CA, CRL и exact client SAN api-a/api-b/worker/publisher. Native receiver доступен только на 127.0.0.1:43170 в том же namespace. ALPN h2 сохраняет совместимость с gRPC. Stream connections ограничены60 секундами, TLS tickets выключены.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Collector отправляет logs через mTLS в Loki, traces через mTLS в Tempo. Loki разрешает collector только POST /otlp/v1/logs. Prometheus забирает метрики Collector по TLS со своей identity. Grafana использует свою mTLS identity для query/read endpoints. Локальные HTTP hops не маршрутизируются в Docker network и проверены отрицательными TCP probes.
Collector применяет memory_limiter и batch. Очереди SDK/Collector и retry имеют конечные ограничения, сохранённые из lab6. История находится в persistent volumes. Dashboard14 панелей и alert rules сохранены в infra. Grafana datasource provisioning генерируется bootstrap в игнорируемый secrets/grafana-datasources.yaml, поскольку secureJsonData содержит собственный Grafana leaf key. В Git private key не находится.
Проверка сигналов, сквозной trace, коррелированных логов и отсутствия canary/token в логах выполняется make test-observability. Матрица mTLS и HTTP read/write ACL проверяется make test-tls-matrix.
+90
View File
@@ -0,0 +1,90 @@
receivers:
otlp:
protocols:
grpc:
endpoint: 127.0.0.1:43170
processors:
memory_limiter:
check_interval: 1s
limit_mib: 128
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 256
send_batch_max_size: 512
exporters:
prometheus:
endpoint: 127.0.0.1:18889
resource_to_telemetry_conversion:
enabled: true
otlphttp/loki:
endpoint: https://loki:3100/otlp
timeout: 2s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 128
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 10s
tls:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/server.crt
key_file: /run/tls/server.key
otlp/tempo:
endpoint: tempo:4317
tls:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/server.crt
key_file: /run/tls/server.key
timeout: 2s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 128
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 10s
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/tempo
metrics:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- prometheus
logs:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- otlphttp/loki
+3
View File
@@ -0,0 +1,3 @@
local all all trust
hostnossl all all all reject
hostssl all all all scram-sha-256
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
mkdir -p /tmp/postgres-tls
cp /run/tls/server.crt /tmp/postgres-tls/server.crt
cp /run/tls/server.key /tmp/postgres-tls/server.key
chown -R postgres:postgres /tmp/postgres-tls
chmod 600 /tmp/postgres-tls/server.key
if [ ! -f "$PGDATA/PG_VERSION" ]; then
rm -f "$PGDATA/server.crt" "$PGDATA/server.key"
fi
exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/tmp/postgres-tls/server.crt -c ssl_key_file=/tmp/postgres-tls/server.key -c hba_file=/etc/postgresql/pg_hba.conf
+33
View File
@@ -0,0 +1,33 @@
groups:
- name: messenger
rules:
- alert: HighApiErrorRate
expr: sum(rate(messenger_http_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])),
0.001) > 0.01
for: 6s
labels:
severity: warning
annotations:
summary: API 5xx exceeds 1% over 1 minute
description: SLO is 99% non-5xx business requests over 5 minutes. Inspect PostgreSQL
client spans and pool metrics.
runbook_url: https://localhost:17400/d/messenger/messenger?viewPanel=5
- alert: QueueLagGrowing
expr: messenger_queue_oldest_age_seconds > 15 and messenger_queue_depth > 0 and
on(service_instance_id) (time() - messenger_queue_observed_at_seconds < 10)
for: 6s
labels:
severity: warning
annotations:
summary: Oldest unfinished job exceeds 15 seconds
description: Inspect worker capacity, busy gauge and consumer traces. Restore
worker and verify backlog drains. See infra/runbook.md.
- alert: QueueObservationStale
expr: time() - max(messenger_queue_observed_at_seconds) > 15
for: 6s
labels:
severity: warning
annotations:
summary: Publisher backlog observations are stale
description: Check publisher and PostgreSQL availability before trusting queue
gauges.
+26
View File
@@ -0,0 +1,26 @@
global:
scrape_interval: 3s
evaluation_interval: 3s
rule_files:
- /etc/prometheus/alerts.yaml
scrape_configs:
- job_name: application
static_configs:
- targets:
- otel-collector:8889
scheme: https
tls_config:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/server.crt
key_file: /run/tls/server.key
server_name: otel-collector
- job_name: collector
static_configs:
- targets:
- otel-collector:8888
scheme: https
tls_config:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/server.crt
key_file: /run/tls/server.key
server_name: otel-collector
+1
View File
@@ -0,0 +1 @@
[rabbitmq_auth_mechanism_ssl].
+2
View File
@@ -0,0 +1,2 @@
{lookup, [file, dns]}.
{host, {127,0,0,1}, ["rabbitmq", "localhost"]}.
+11
View File
@@ -0,0 +1,11 @@
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.cacertfile = /run/ca/ca.crt
ssl_options.certfile = /run/tls/server.crt
ssl_options.keyfile = /run/tls/server.key
ssl_options.verify = verify_peer
ssl_options.fail_if_no_peer_cert = true
ssl_options.versions.1 = tlsv1.3
ssl_options.versions.2 = tlsv1.2
auth_mechanisms.1 = EXTERNAL
ssl_cert_login_from = common_name
+11
View File
@@ -0,0 +1,11 @@
# Диагностика lab7
При 5xx проверить HTTPS readiness, состояние API agent и sealed status OpenBao. При sealed сервере оператор выполняет scripts/bao.py unseal. Если cache lifetime истёк, API не открывает listener до восстановления сервисной аутентификации. KV policy denial останавливает child сразу. Root token в приложение передавать не требуется.
При TLS-ошибке проверить CA, hostname/SAN, срок действия leaf, client identity и CRL. Без проверки сертификата запросы не повторяются. Native TLS серверы и file mounts обновляются при bootstrap/recreate. Проверенный сценарий API leaf rotation выполняется scripts/rotate.py api-leaf.
При незавершённой worker secret rotation сохранить secrets/operator/worker-rotation-pending.json и повторить scripts/rotate.py worker-secret после восстановления OpenBao. Script согласует тот же target и выполняет read-back после неоднозначного ответа. Подробности и регрессионная проверка находятся в REPORT.md.
Grafana доступна по HTTPS на localhost:17400. Для операторских запросов Prometheus/Loki/Tempo использовать scripts/local_https.py, который соединяется с loopback, проверяя правильное service hostname. Не отключать hostname или CA verification.
Рост queue lag диагностируется по backlog, oldest age и связанным publisher/worker spans. Ошибки DB/S3 видны в client spans. Частота 429 относится к общему login budget30/10 секунд. При DB недоступности admission fail closed. Ошибки самого LB не входят в API-only SLI, что сохраняет ограничение lab6.
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -eu
export SSL_CERT_FILE=/run/ca/ca.crt
export MC_CONFIG_DIR=/tmp/mc
mc alias set local https://s3:9000 lab7-root "$(cat /run/bootstrap/s3_root_password)" >/dev/null
mc mb --ignore-existing local/messenger-attachments >/dev/null
mc anonymous set none local/messenger-attachments >/dev/null
python - <<'PY'
import json,subprocess
from pathlib import Path
roles=json.loads(Path('/run/bootstrap/roles.json').read_text())
policies={
'api':[{'Effect':'Allow','Action':['s3:PutObject'],'Resource':['arn:aws:s3:::messenger-attachments/attachments/staging/*']},{'Effect':'Allow','Action':['s3:GetObject'],'Resource':['arn:aws:s3:::messenger-attachments/attachments/final/*']}],
'worker':[{'Effect':'Allow','Action':['s3:GetObject'],'Resource':['arn:aws:s3:::messenger-attachments/attachments/staging/*']},{'Effect':'Allow','Action':['s3:PutObject'],'Resource':['arn:aws:s3:::messenger-attachments/attachments/final/*']}],
'cleaner':[{'Effect':'Allow','Action':['s3:DeleteObject'],'Resource':['arn:aws:s3:::messenger-attachments/attachments/*']}]
}
for role,statements in policies.items():
data=roles[role];path=Path('/tmp/policy-'+role+'.json');path.write_text(json.dumps({'Version':'2012-10-17','Statement':statements}))
subprocess.run(['mc','admin','user','add','local',data['s3_access_key_id'],data['s3_secret_access_key']],check=True,stdout=subprocess.DEVNULL)
subprocess.run(['mc','admin','policy','create','local',role,str(path)],check=True,stdout=subprocess.DEVNULL)
subprocess.run(['mc','admin','policy','attach','local',role,'--user',data['s3_access_key_id']],check=True,stdout=subprocess.DEVNULL)
print('PASS: private bucket and prefix-scoped S3 roles configured')
PY
+22
View File
@@ -0,0 +1,22 @@
server:
http_listen_port: 13200
http_listen_address: 127.0.0.1
grpc_listen_address: 127.0.0.1
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 127.0.0.1:43170
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
compactor:
compaction:
block_retention: 72h
usage_report:
reporting_enabled: false
+2
View File
@@ -0,0 +1,2 @@
server api-a:8080 resolve max_fails=1 fail_timeout=2s;
server api-b:8080 resolve max_fails=1 fail_timeout=2s;