Публичный вход — HTTPS с проверкой SAN, LB ходит в каждую реплику по mTLS и пускает только CN=lb. Worker не читает хеши паролей и чужие префиксы S3; после смены его ключа и возврата ACL то же вложение становится ready.

Автор / группа: ivanstorozhev, БВТ2304
Целевая оценка (3/4/5): 5
Трек 5, если заявлен: трек 1, компрометация worker

Что реализовано и что перенесено: из lab6 перенесены Spring Boot API, PostgreSQL, Redis-кэш сессий, Liquibase через одноразовый сервис migrate, HAProxy без sticky session, две реплики, X-Instance-Id, обязательный Idempotency-Key, scripts/stop-one.sh и scripts/restart.sh, приватный SeaweedFS, ответ 202, staging, transactional outbox, отдельный worker, Kafka 3.9.1 (KRaft, volume kafka-data), состояния queued/processing/ready/failed, JPEG thumbnail и crop, lossy WebP, retry с backoff и jitter, топик attachments.failed, явный replay и lease, OTLP в Collector 0.139.0, Prometheus v3.2.1, Loki 3.4.2, Tempo 2.7.2 и Grafana 11.6.1. Оригинал принимается в S3 в одной транзакции со строкой outbox. Worker коммитит смещение только после записи вариантов в фиксированные ключи. Сообщение брокера содержит идентификаторы и W3C traceparent, без тела сообщения и ключа объекта. Добавлены локальный CA (scripts/bootstrap.sh), публичный TLS на 127.0.0.1:8443 с SAN localhost и 127.0.0.1, mTLS-шлюз каждой реплики с allowlist CN=lb и CRL, JDBC sslmode=verify-full к Postgres, роли messenger / messenger_api / messenger_worker, TLS и ACL Redis, TLS-шлюз S3 с префиксами worker, mTLS Kafka с ACL User:api и User:worker, mTLS к Collector и далее к Prometheus, Loki и Tempo. OpenBao 2.6.6 не в dev mode, file storage, cert auth, токен 45 с, политики только на свой KV. Argon2id m=19456,t=2,p=1, перехеш при успешном входе, общий лимит 8/30 в Redis до подсчёта хеша. Приложение и worker не root, cap_drop ALL, read_only, no-new-privileges. Секреты читаются сертификатом сервиса при старте и не лежат в образе.

Команды запуска из чистого clone:
bash scripts/up.sh
make test CA_FILE="$PWD/secrets/ca/ca.crt"
make test-security CA_FILE="$PWD/secrets/ca/ca.crt"

Результаты проверок и ссылка на REPORT.md: подробности и числа в REPORT.md и evidence/grade7.txt
make check — PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
make test — PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
make test-security — PASS: trusted HTTPS works; untrusted CA rejected.
mTLS https://api-a:8443/health/ready: без сертификата, чужой CA, CN=stranger и CN=api — отказ; CN=lb — 200. Collector: CN=stranger — отказ, CN=api — HTTP 415. Отозванный лист CN=lb после CRL — отказ, публичный health остаётся 200, id образа не менялся. SET ROLE messenger_worker не читает password_hash и читает attachments. S3 worker: staging/* 200, forbidden/ 403, CreateBucket 403; admin CreateBucket 200. Kafka worker produce в attachments.process — TopicAuthorizationException. Вход: восемь 401, девятый 429 и Retry-After 60; один успешный вход 105 мс. OpenBao: чужой путь 403, renew-self с тем же сертификатом даёт lease 45 с, через 50 с токен 403. Sealed OpenBao: health работающего API 200, новый cert login 503. Трек 1: вложение 74b90666-d1df-47d1-9b1b-40f7c3af4860 принято как 202 queued при остановленном worker, осталось queued после смены ключа S3 и снятия Read ACL, после возврата ACL стало ready.
Argon2ParamsTest и TextRulesTest — PASS. Полный mvn test и make test-persistence / make test-failover на этом стенде не перезапускались.

Ограничения / известные ошибки: один Docker-хост, единственные PostgreSQL, Redis, SeaweedFS, Kafka, Loki, Tempo и Prometheus остаются точками отказа. Replication factor топиков равен 1. Доставка at least once. Unseal OpenBao — один ключ оператора, не Shamir. Контроллер Kafka на 127.0.0.1:9093 без TLS пускает User:ANONYMOUS только для KRaft; порт снаружи не опубликован. У API ключ S3 на весь bucket и bootstrap Admin, у worker только три префикса. File storage OpenBao 2.6.6 помечен как устаревающий к 2.7. Postgres, Redis, Kafka, SeaweedFS, OpenBao и телеметрия не read_only, потому что пишут свои данные. /tmp приложения смонтирован с exec: туда распаковывается библиотека WebP. Trivy 0.67.2: Ubuntu 22.04 — 18 HIGH и 0 CRITICAL, jar — 12 записей (4 CRITICAL); разбор применимости в security/SCAN.md, сокета Docker и root у приложения нет.

Источники и использование ИИ: контракт contracts/openapi.json, contracts/trust-matrix.md, COURSE.md и README задания; код lab6; Spring Boot 4.1.1, Spring Data JPA, spring-security-crypto, Spring Data Redis, Spring Kafka, Liquibase, Actuator, OpenTelemetry, AWS SDK for Java 2.31.50, Thumbnailator 0.4.20, webp-imageio 0.11.0, PostgreSQL 16.10, Redis 7.4.6, HAProxy 3.2.6, SeaweedFS 4.52, Apache Kafka 3.9.1, OpenBao 2.6.6, Collector 0.139.0, Prometheus v3.2.1, Loki 3.4.2, Tempo 2.7.2, Grafana 11.6.1, Trivy 0.67.2. Помощь ИИ использована при переносе lab6, mTLS, OpenBao, треке 1 и отчёте.

Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
Контракт и публичные тесты не ослаблены.
make check и make test выполнены; приложен реальный вывод.
Сценарии отказов/безопасности своего уровня воспроизведены.
Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
README задания сохранён, REPORT.md содержит инструкцию именно моего решения.

Лабораторная 7

Автор / группа: TODO
Целевая оценка (3/4/5): TODO
Трек 5, если заявлен: TODO

Что реализовано и что перенесено: TODO
Команды запуска из чистого clone: TODO
Результаты проверок и ссылка на REPORT.md: TODO
Ограничения / известные ошибки: TODO
Источники и использование ИИ: TODO

Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
Контракт и публичные тесты не ослаблены.
make check и make test выполнены; приложен реальный вывод.
Сценарии отказов/безопасности своего уровня воспроизведены.
Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
README задания сохранён, REPORT.md содержит инструкцию именно моего решения.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ivanstorozhev
2026-11-26 21:46:22 +03:00
co-authored by Cursor
parent 20afc2c790
commit f424658b1d
172 changed files with 10663 additions and 100 deletions
+6
View File
@@ -1,3 +1,9 @@
# Инфраструктура
Стенд — корневой `compose.yaml`, проект `messenger-lab7`. Публичный вход — HAProxy на `127.0.0.1:8443`. У каждой реплики API свой шлюз mTLS. Postgres проверяет сертификат сам (`verify-full`). Redis, S3 и Collector шифрует соседний HAProxy на `127.0.0.1`. Kafka — свой mTLS и ACL. Секреты читает OpenBao, не dev mode, каталог `/openbao/data`.
Наблюдаемость: `otel-collector`, `prometheus`, `loki`, `tempo`, `grafana`. Конфиг Collector — `infra/otel/collector.yaml`. Шлюзы — `infra/haproxy/`. Политики OpenBao — `infra/openbao/`.
# Инфраструктура студента
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
+239
View File
@@ -0,0 +1,239 @@
{
"uid": "messenger-lab6",
"title": "Messenger",
"tags": ["messenger", "lab6"],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"refresh": "10s",
"time": {"from": "now-30m", "to": "now"},
"panels": [
{
"id": 1,
"type": "text",
"title": "SLI / SLO",
"gridPos": {"h": 5, "w": 24, "x": 0, "y": 0},
"options": {
"mode": "markdown",
"content": "**Availability SLI:** 5xx / all business HTTP requests. Health (`/health/*`) and client 4xx are outside the numerator. **SLO:** 99% success over 5 minutes.\n\n**Latency:** Micrometer exports `http.server.requests` as a histogram in milliseconds (`http_server_requests_milliseconds_bucket`). p50/p95/p99 are `histogram_quantile` over all replicas, then divided by 1000 so the panel is in seconds. Do not average per-replica percentiles.\n\n**Queue:** `messenger_queue_oldest_age_seconds` is the age of the oldest queued or processing attachment. **SLO:** under 30s. This is backlog age, not worker duration.\n\n**Time to ready:** `messenger_job_time_to_ready` is exported in milliseconds. The panel divides the quantile by 1000 and shows seconds, from the committed upload to `ready`."
}
},
{
"id": 2,
"type": "timeseries",
"title": "Business HTTP RPS",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 5},
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (method, uri) (rate(http_server_requests_milliseconds_count{uri!~\"/health.*\"}[1m]))",
"legendFormat": "{{method}} {{uri}}"
}
]
},
{
"id": 3,
"type": "timeseries",
"title": "Business HTTP error ratio (5xx)",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 5},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(rate(http_server_requests_milliseconds_count{status=~\"5..\",uri!~\"/health.*\"}[5m])) / clamp_min(sum(rate(http_server_requests_milliseconds_count{uri!~\"/health.*\"}[5m])), 1e-9)",
"legendFormat": "5xx ratio"
}
]
},
{
"id": 4,
"type": "timeseries",
"title": "HTTP duration p50 / p95 / p99",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 13},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_requests_milliseconds_bucket{uri!~\"/health.*\"}[5m]))) / 1000",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_requests_milliseconds_bucket{uri!~\"/health.*\"}[5m]))) / 1000",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_requests_milliseconds_bucket{uri!~\"/health.*\"}[5m]))) / 1000",
"legendFormat": "p99"
}
]
},
{
"id": 5,
"type": "timeseries",
"title": "Jobs per second",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 13},
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 6,
"type": "timeseries",
"title": "Job duration p95",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 21},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_job_duration_milliseconds_bucket[5m]))) / 1000",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 7,
"type": "timeseries",
"title": "Time to ready p95",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 21},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_milliseconds_bucket[5m]))) / 1000",
"legendFormat": "p95"
}
]
},
{
"id": 8,
"type": "timeseries",
"title": "Queue depth and oldest job age",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 21},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": [{"matcher": {"id": "byName", "options": "oldest age"}, "properties": [{"id": "unit", "value": "s"}]}]},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max(messenger_queue_depth{queue=\"attachments.process\"})",
"legendFormat": "depth"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max(messenger_queue_oldest_age_seconds{queue=\"attachments.process\"})",
"legendFormat": "oldest age"
}
]
},
{
"id": 9,
"type": "timeseries",
"title": "DB pool used and waiting",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 29},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(hikaricp_connections_active)",
"legendFormat": "active"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(hikaricp_connections_pending)",
"legendFormat": "pending"
}
]
},
{
"id": 10,
"type": "timeseries",
"title": "Worker busy / capacity",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 29},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max(messenger_worker_busy)",
"legendFormat": "busy"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max(messenger_worker_capacity)",
"legendFormat": "capacity"
}
]
},
{
"id": 11,
"type": "timeseries",
"title": "Process CPU",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 29},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max by (service_name) (process_cpu_usage)",
"legendFormat": "{{service_name}}"
}
]
},
{
"id": 12,
"type": "timeseries",
"title": "Process heap",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 37},
"fieldConfig": {"defaults": {"unit": "bytes"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (service_name) (jvm_memory_used_bytes{area=\"heap\"})",
"legendFormat": "{{service_name}}"
}
]
}
]
}
@@ -0,0 +1,8 @@
apiVersion: 1
policies:
- orgId: 1
receiver: grafana-default-email
group_by:
- grafana_folder
- alertname
@@ -0,0 +1,140 @@
apiVersion: 1
groups:
- orgId: 1
name: messenger-slo
folder: Messenger
interval: 30s
rules:
- uid: messenger-error-rate
title: High business HTTP error rate
condition: C
for: 1m
noDataState: OK
execErrState: Error
isPaused: false
labels:
severity: warning
slo: api-availability
annotations:
summary: Business HTTP 5xx ratio is above 5%.
description: "SLI = 5xx / all non-health requests. 4xx is not an error. SLO is 99% success over 5 minutes. The alert uses a 2 minute ratio and fires after 1 minute."
runbook: high-error-rate.md
data:
- refId: A
relativeTimeRange:
from: 300
to: 0
datasourceUid: prometheus
model:
datasource:
type: prometheus
uid: prometheus
editorMode: code
expr: sum(rate(http_server_requests_milliseconds_count{status=~"5..",uri!~"/health.*"}[2m])) / clamp_min(sum(rate(http_server_requests_milliseconds_count{uri!~"/health.*"}[2m])), 1e-9)
instant: true
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange:
from: 300
to: 0
datasourceUid: __expr__
model:
datasource:
name: Expression
type: __expr__
uid: __expr__
expression: A
reducer: last
refId: B
type: reduce
intervalMs: 1000
maxDataPoints: 43200
- refId: C
relativeTimeRange:
from: 300
to: 0
datasourceUid: __expr__
model:
datasource:
name: Expression
type: __expr__
uid: __expr__
conditions:
- evaluator:
params:
- 0.05
type: gt
expression: B
refId: C
type: threshold
intervalMs: 1000
maxDataPoints: 43200
- uid: messenger-queue-lag
title: Attachment queue lag
condition: C
for: 30s
noDataState: OK
execErrState: Error
isPaused: false
labels:
severity: warning
slo: time-to-ready
annotations:
summary: Oldest queued attachment is older than 15 seconds.
description: "Queue lag is the age of the oldest queued or processing attachment, in seconds. It is not worker duration. SLO is oldest age under 30s. The alert threshold is 15s for 30s."
runbook: queue-lag.md
data:
- refId: A
relativeTimeRange:
from: 300
to: 0
datasourceUid: prometheus
model:
datasource:
type: prometheus
uid: prometheus
editorMode: code
expr: max(messenger_queue_oldest_age_seconds{queue="attachments.process"})
instant: true
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange:
from: 300
to: 0
datasourceUid: __expr__
model:
datasource:
name: Expression
type: __expr__
uid: __expr__
expression: A
reducer: last
refId: B
type: reduce
intervalMs: 1000
maxDataPoints: 43200
- refId: C
relativeTimeRange:
from: 300
to: 0
datasourceUid: __expr__
model:
datasource:
name: Expression
type: __expr__
uid: __expr__
conditions:
- evaluator:
params:
- 15
type: gt
expression: B
refId: C
type: threshold
intervalMs: 1000
maxDataPoints: 43200
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,40 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: trace_id
matcherRegex: "trace_id=([0-9a-f]+)"
url: "$${__value.raw}"
datasourceUid: tempo
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
spanStartTimeShift: "-1m"
spanEndTimeShift: "1m"
lokiSearch:
datasourceUid: loki
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
@@ -0,0 +1,8 @@
# High business HTTP error rate
SLI: `5xx / all requests` on routes other than `/health/*`. A wrong password is 401 and is not in the numerator.
1. Open the Messenger dashboard panel "Business HTTP error ratio". Confirm the ratio, not a single replica average.
2. In Loki, filter `{service_name="messenger-api"} | event="http.completed" |= "status=5"` and read `trace_id`. `status` is part of the log line, not a label. Do not copy tokens or message text out of the log.
3. Open that trace in Tempo. A database failure has a long or error `jdbc.query` child. A slow handler has a long server span and no database child.
4. After the database is back, `/health/ready` returns 200 and the 2 minute ratio falls. The alert resolves without an external notification.
+7
View File
@@ -0,0 +1,7 @@
# Attachment queue lag
The signal is `messenger_queue_oldest_age_seconds` for queue `attachments.process`. It is the age of the oldest attachment in `queued` or `processing`, measured by the API from PostgreSQL. It is not the duration of a worker span.
1. If the age grows and `messenger_worker_busy` disappears, the worker process is down. Upload still returns 202.
2. Start the worker. The same attachment becomes `ready`. The age returns to 0 on the next sample (about 5s) and the remote-write step (10s).
3. The alert resolves on the following evaluation. No message is sent outside the stand.
+8
View File
@@ -0,0 +1,8 @@
# Slow database versus a slow HTTP handler
`POST /internal/demo/slow-db?seconds=2` runs `SELECT pg_sleep` and is a database delay. `POST /internal/demo/slow-handler?seconds=2` sleeps in the handler and does not touch PostgreSQL. Both require `X-Demo-Token`.
1. Take `trace_id` from the `http.completed` log of each call.
2. The slow-db trace contains a `jdbc.query` span of about 2 seconds inside the server span.
3. The slow-handler trace has a server span of about 2 seconds and no `jdbc.query` child.
4. Hikari `hikaricp_connections_pending` rises when the pool is waiting on PostgreSQL, and stays near zero for the handler sleep.
+31
View File
@@ -0,0 +1,31 @@
# Стоит в сетевом пространстве API.
# Снаружи принимает только сертификат CN=lb.
# Изнутри приложение ходит на 127.0.0.1 без TLS, а этот процесс шифрует выход.
global
maxconn 200
defaults
mode tcp
timeout connect 2s
timeout client 60s
timeout server 60s
frontend api_in
bind *:8443 ssl crt /certs/server.pem ca-file /certs/ca.crt verify required crl-file /certs/ca.crl
tcp-request content reject unless { ssl_c_s_dn(cn) -m str lb }
default_backend api_local
backend api_local
server app 127.0.0.1:8080
listen redis
bind 127.0.0.1:6379
server redis redis:6379 ssl verify required ca-file /certs/ca.crt verifyhost redis
listen s3
bind 127.0.0.1:8333
server s3 s3:8333 ssl verify required ca-file /certs/ca.crt verifyhost s3
listen otel
bind 127.0.0.1:4318
server otel otel-collector:4318 ssl verify required ca-file /certs/ca.crt crt /certs/client.pem verifyhost otel-collector
+32
View File
@@ -0,0 +1,32 @@
# Внешний вход. Клиент проверяет сертификат localhost.
# Дальше этот процесс сам предъявляет сертификат CN=lb репликам API.
global
maxconn 200
defaults
mode http
timeout connect 2s
timeout client 60s
timeout server 60s
timeout http-request 60s
timeout check 2s
retries 0
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
frontend https
bind *:8443 ssl crt /certs/server.pem
default_backend api
backend api
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr host api
default-server inter 2s fall 3 rise 1 init-addr none resolvers docker resolve-prefer ipv4 check ssl verify required ca-file /certs/ca.crt crt /certs/client.pem
server api-a api-a:8443 verifyhost api-a
server api-b api-b:8443 verifyhost api-b
+18
View File
@@ -0,0 +1,18 @@
global
maxconn 50
defaults
mode tcp
timeout connect 2s
timeout client 60s
timeout server 60s
frontend loki
bind *:3100 ssl crt /certs/server.pem ca-file /certs/ca.crt verify required
acl allowed ssl_c_s_dn(cn) -m str otel-collector
acl allowed ssl_c_s_dn(cn) -m str grafana
tcp-request content reject unless allowed
default_backend local
backend local
server loki 127.0.0.1:13100
+20
View File
@@ -0,0 +1,20 @@
# Принять телеметрию могут только сертификаты api и worker.
# Сертификат от того же CA, но с другим CN, здесь закрывается.
global
maxconn 100
defaults
mode tcp
timeout connect 2s
timeout client 120s
timeout server 120s
frontend otel
bind *:4318 ssl crt /certs/server.pem ca-file /certs/ca.crt verify required
acl allowed ssl_c_s_dn(cn) -m str api
acl allowed ssl_c_s_dn(cn) -m str worker
tcp-request content reject unless allowed
default_backend local
backend local
server collector 127.0.0.1:14318
+18
View File
@@ -0,0 +1,18 @@
global
maxconn 50
defaults
mode tcp
timeout connect 2s
timeout client 60s
timeout server 60s
frontend prom
bind *:9090 ssl crt /certs/server.pem ca-file /certs/ca.crt verify required
acl allowed ssl_c_s_dn(cn) -m str otel-collector
acl allowed ssl_c_s_dn(cn) -m str grafana
tcp-request content reject unless allowed
default_backend local
backend local
server prom 127.0.0.1:19090
+16
View File
@@ -0,0 +1,16 @@
# SeaweedFS слушает plaintext только на 127.0.0.1. Снаружи остаётся TLS.
global
maxconn 100
defaults
mode tcp
timeout connect 2s
timeout client 60s
timeout server 60s
frontend s3
bind *:8333 ssl crt /certs/server.pem
default_backend local
backend local
server seaweed 127.0.0.1:18333
+25
View File
@@ -0,0 +1,25 @@
# Запись трасс и чтение трасс разведены по портам и по CN.
global
maxconn 50
defaults
mode tcp
timeout connect 2s
timeout client 60s
timeout server 60s
frontend push
bind *:4318 ssl crt /certs/server.pem ca-file /certs/ca.crt verify required
tcp-request content reject unless { ssl_c_s_dn(cn) -m str otel-collector }
default_backend push_local
backend push_local
server tempo 127.0.0.1:14318
frontend query
bind *:3200 ssl crt /certs/server.pem ca-file /certs/ca.crt verify required
tcp-request content reject unless { ssl_c_s_dn(cn) -m str grafana }
default_backend query_local
backend query_local
server tempo 127.0.0.1:13200
+17
View File
@@ -0,0 +1,17 @@
# Тот же выход, что у API, но клиентский сертификат worker и без входящего HTTP.
global
maxconn 100
defaults
mode tcp
timeout connect 2s
timeout client 60s
timeout server 60s
listen s3
bind 127.0.0.1:8333
server s3 s3:8333 ssl verify required ca-file /certs/ca.crt verifyhost s3
listen otel
bind 127.0.0.1:4318
server otel otel-collector:4318 ssl verify required ca-file /certs/ca.crt crt /certs/client.pem verifyhost otel-collector
+37
View File
@@ -0,0 +1,37 @@
#!/bin/bash
# Локальный операторский клиент CN=kafka-admin. Обычные api и worker этих прав не имеют.
set -eu
CFG=/etc/kafka/secrets/admin.properties
BOOT=kafka:9092
ready=0
for _ in $(seq 1 40); do
if /opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server "$BOOT" --command-config "$CFG" >/dev/null 2>&1; then
ready=1
break
fi
sleep 2
done
if [ "$ready" -ne 1 ]; then
echo "kafka did not accept the admin certificate" >&2
exit 1
fi
topics() {
/opt/kafka/bin/kafka-topics.sh --bootstrap-server "$BOOT" --command-config "$CFG" "$@"
}
acls() {
/opt/kafka/bin/kafka-acls.sh --bootstrap-server "$BOOT" --command-config "$CFG" "$@"
}
topics --create --if-not-exists --topic attachments.process --partitions 2 --replication-factor 1
topics --create --if-not-exists --topic attachments.failed --partitions 1 --replication-factor 1
topics --create --if-not-exists --topic probe.api --partitions 1 --replication-factor 1
acls --add --allow-principal User:api --operation Write --operation Describe --topic attachments.process
acls --add --allow-principal User:api --operation Write --operation Describe --topic probe.api
acls --add --allow-principal User:api --operation IdempotentWrite --cluster
acls --add --allow-principal User:worker --operation Read --operation Describe --topic attachments.process
acls --add --allow-principal User:worker --operation Write --operation Describe --topic attachments.failed
acls --add --allow-principal User:worker --operation Read --group attachment-worker
acls --add --allow-principal User:worker --operation IdempotentWrite --cluster
echo "kafka acls ready"
+37
View File
@@ -0,0 +1,37 @@
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
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
volume_enabled: true
compactor:
working_directory: /loki/compactor
compaction_interval: 10m
+14
View File
@@ -0,0 +1,14 @@
ui = false
disable_mlock = true
api_addr = "https://openbao:8200"
storage "file" {
path = "/openbao/data"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/certs/openbao.crt"
tls_key_file = "/certs/openbao.key"
tls_min_version = "tls12"
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/data/messenger/api" {
capabilities = ["read"]
}
@@ -0,0 +1,3 @@
path "secret/data/messenger/migrate" {
capabilities = ["read"]
}
@@ -0,0 +1,3 @@
path "secret/data/messenger/worker" {
capabilities = ["read"]
}
+10 -4
View File
@@ -1,7 +1,13 @@
# Конфигурация наблюдаемости — реализовать
# Collector
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
`collector.yaml` принимает OTLP/HTTP `:4318` и OTLP/gRPC `:4317` только внутри сети стенда.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
| Pipeline | Exporter | Хранилище |
| --- | --- | --- |
| traces | `otlphttp/tempo` | Tempo `2.7.2`, локальные блоки на volume `tempo-data` |
| metrics | `prometheusremotewrite` | Prometheus `v3.2.1`, remote write, volume `prometheus-data` |
| logs | `otlphttp/loki` | Loki `3.4.2`, filesystem, volume `loki-data` |
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
`memory_limiter` (192 MiB) стоит первым процессором. У Tempo и Loki очередь `queue_size: 256` с `block_on_overflow: false`. У Prometheus remote write очередь `remote_write_queue.queue_size: 256`. При недоступном backend данные отбрасываются после `max_elapsed_time: 30s`, а не копятся без предела.
Grafana `11.6.1` только читает эти хранилища. Datasource, dashboard и alert rules лежат в `infra/grafana` и подключаются provisioning-ом.
+101
View File
@@ -0,0 +1,101 @@
# OTel Collector 0.139.0. Receives OTLP from API and worker, then forwards
# metrics to Prometheus, logs to Loki and traces to Tempo.
# memory_limiter and a bounded sending queue drop data when a backend is down
# instead of growing RAM without a limit.
receivers:
otlp:
protocols:
grpc:
endpoint: 127.0.0.1:14317
http:
endpoint: 127.0.0.1:14318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 48
batch:
timeout: 5s
send_batch_size: 512
send_batch_max_size: 1024
exporters:
otlphttp/tempo:
endpoint: https://tempo:4318
tls:
ca_file: /certs/ca.crt
cert_file: /certs/client.crt
key_file: /certs/client.key
insecure: false
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 30s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
block_on_overflow: false
otlphttp/loki:
endpoint: https://loki:3100/otlp
tls:
ca_file: /certs/ca.crt
cert_file: /certs/client.crt
key_file: /certs/client.key
insecure: false
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 30s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
block_on_overflow: false
prometheusremotewrite:
endpoint: https://prometheus:9090/api/v1/write
tls:
ca_file: /certs/ca.crt
cert_file: /certs/client.crt
key_file: /certs/client.key
insecure: false
timeout: 5s
resource_to_telemetry_conversion:
enabled: true
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 30s
remote_write_queue:
enabled: true
queue_size: 256
num_consumers: 2
extensions:
health_check:
endpoint: 127.0.0.1:13133
service:
extensions: [health_check]
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheusremotewrite]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
telemetry:
logs:
level: info
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
set -eu
cp /certs/server.crt /var/lib/postgresql/server.crt
cp /certs/server.key /var/lib/postgresql/server.key
chown postgres:postgres /var/lib/postgresql/server.crt /var/lib/postgresql/server.key
chmod 600 /var/lib/postgresql/server.key
chmod 644 /var/lib/postgresql/server.crt
exec docker-entrypoint.sh postgres \
-c ssl=on \
-c ssl_cert_file=/var/lib/postgresql/server.crt \
-c ssl_key_file=/var/lib/postgresql/server.key \
-c ssl_min_protocol_version=TLSv1.2 \
-c hba_file=/etc/postgres/pg_hba.conf
+5
View File
@@ -0,0 +1,5 @@
# Локальный сокет — только внутри контейнера, им пользуется оператор и healthcheck.
# По сети пароль принимается только поверх TLS.
local all all trust
hostssl all all 0.0.0.0/0 scram-sha-256
hostnossl all all 0.0.0.0/0 reject
+6
View File
@@ -0,0 +1,6 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
# Series arrive by remote write from the Collector. There is no scrape of the API.
scrape_configs: []
+24
View File
@@ -0,0 +1,24 @@
{
"identities": [
{
"name": "messenger-api",
"credentials": [
{
"accessKey": "${S3_ACCESS_KEY}",
"secretKey": "${S3_SECRET_KEY}"
}
],
"actions": ["Read", "Write", "List"]
},
{
"name": "messenger-bootstrap",
"credentials": [
{
"accessKey": "${S3_BOOTSTRAP_ACCESS_KEY}",
"secretKey": "${S3_BOOTSTRAP_SECRET_KEY}"
}
],
"actions": ["Admin"]
}
]
}
+29
View File
@@ -0,0 +1,29 @@
stream_over_http_enabled: true
server:
http_listen_address: 127.0.0.1
http_listen_port: 13200
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 127.0.0.1:14317
http:
endpoint: 127.0.0.1:14318
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks