ЛР 7 — БВТ2301 — Курлова — на 4

Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия:
- внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial;
- TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL),
  Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA;
- OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь;
- роли БД, S3-политики и права брокера по принципу минимальных прав;
- Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS;
- hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия;
- отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
This commit is contained in:
alenchha
2026-11-16 10:49:13 +03:00
parent 20afc2c790
commit 861e7722b5
116 changed files with 14522 additions and 63 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,9 @@
apiVersion: 1
providers:
- name: messenger
folder: Messenger
type: file
disableDeletion: true
allowUiUpdates: false
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,63 @@
# Grafana 11.5.2 datasources (fixed uids are referenced by the dashboard JSON). Grafana stores no signals itself.
# "$$" escapes "$" from Grafana's env-variable interpolation; $__file{...} reads the client TLS material.
# lab7: every datasource uses HTTPS, verifies the server against the lab root CA and authenticates with grafana-out.
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
timeInterval: 15s
prometheusType: Prometheus
secureJsonData:
tlsCACert: "$__file{/run/secrets/ca.crt}"
tlsClientCert: "$__file{/run/secrets/client.crt}"
tlsClientKey: "$__file{/run/secrets/client.key}"
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
maxLines: 1000
derivedFields:
# trace_id is OTLP structured metadata -> link "Open trace" to Tempo.
- name: TraceID
matcherType: label
matcherRegex: trace_id
datasourceUid: tempo
url: "$${__value.raw}"
urlDisplayLabel: Open trace
secureJsonData:
tlsCACert: "$__file{/run/secrets/ca.crt}"
tlsClientCert: "$__file{/run/secrets/client.crt}"
tlsClientKey: "$__file{/run/secrets/client.key}"
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: "-5m"
spanEndTimeShift: "5m"
filterByTraceID: true
filterBySpanID: false
customQuery: true
query: '{service_name=~"messenger-.*"} | trace_id="$${__trace.traceId}"'
nodeGraph:
enabled: true
secureJsonData:
tlsCACert: "$__file{/run/secrets/ca.crt}"
tlsClientCert: "$__file{/run/secrets/client.crt}"
tlsClientKey: "$__file{/run/secrets/client.key}"
+48
View File
@@ -0,0 +1,48 @@
# Loki 3.4.2 single binary: log store. Logs arrive by OTLP (https://loki:3100/otlp, mTLS) from the Collector.
# service.name -> stream label service_name; log attributes (event, code.*) and trace_id/span_id -> structured metadata.
auth_enabled: false
server:
http_listen_port: 3100
# Internal gRPC of the single binary: loopback only (closed local hop, not reachable from the network).
grpc_listen_address: 127.0.0.1
grpc_listen_port: 9096
log_level: warn
# lab7: HTTPS with mandatory client certificates from the "Telemetry Clients CA" (collector-out pushes,
# grafana-out queries, operator evidence). No certificate / another CA -> TLS handshake refused.
http_tls_config:
cert_file: /run/secrets/server.crt
key_file: /run/secrets/server.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/secrets/telemetry-ca.crt
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
retention_period: 168h
ingestion_rate_mb: 8
ingestion_burst_size_mb: 16
volume_enabled: true
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Idempotent MinIO bootstrap over HTTPS (CA verified by mc). Root credentials are used only here.
# Two service users with prefix-scoped policies: messenger-api and messenger-worker (see policy-*.json).
set -eu
BUCKET="${S3_BUCKET:-messenger-attachments}"
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
cp /run/secrets/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
until mc alias set local https://minio:9000 "$(cat /run/secrets/minio_root_user)" "$(cat /run/secrets/minio_root_password)" >/dev/null 2>&1; do
echo "waiting for minio"; sleep 2
done
mc mb --ignore-existing "local/$BUCKET" >/dev/null
mc anonymous set none "local/$BUCKET" >/dev/null
for role in api worker; do
user="$(cat /run/secrets/s3_${role}_access_key)"
mc admin policy create local "messenger-$role" "/etc/minio-policy/policy-$role.json" >/dev/null
mc admin user add local "$user" "$(cat /run/secrets/s3_${role}_secret_key)" >/dev/null
mc admin policy attach local "messenger-$role" --user "$user" >/dev/null 2>&1 || true
done
echo "minio bootstrap complete: bucket=$BUCKET private, users messenger-api / messenger-worker with prefix policies"
+23
View File
@@ -0,0 +1,23 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "UploadToStagingAndCompensate",
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]
},
{
"Sid": "DownloadAndReconcileFinalObjects",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::messenger-attachments/attachments/*"]
},
{
"Sid": "ProbeAndListForReconciler",
"Effect": "Allow",
"Action": ["s3:ListBucket", "s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::messenger-attachments"]
}
]
}
+17
View File
@@ -0,0 +1,17 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadAndCleanStaging",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]
},
{
"Sid": "WriteFinalObjectsOnly",
"Effect": "Allow",
"Action": ["s3:PutObject"],
"Resource": ["arn:aws:s3:::messenger-attachments/attachments/*"]
}
]
}
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
set -u
SERVERS="${API_UPSTREAMS:-api-1 api-2}"
INTERVAL="${HEALTH_INTERVAL:-1}"
FALL="${HEALTH_FALL:-2}"
RISE="${HEALTH_RISE:-2}"
OUT=/etc/nginx/upstream/servers.conf
mkdir -p "$(dirname "$OUT")"
var() { echo "$1" | tr -c 'a-zA-Z0-9\n' '_'; }
render() {
any_up=0
for s in $SERVERS; do
eval "[ \"\$up_$(var "$s")\" = 1 ]" && any_up=1
done
for s in $SERVERS; do
mark=""
if [ "$any_up" = 1 ] && eval "[ \"\$up_$(var "$s")\" = 0 ]"; then
mark=" down"
fi
echo "server $s:8080 resolve max_fails=1 fail_timeout=10s$mark;"
done
}
for s in $SERVERS; do
v=$(var "$s")
eval "up_$v=1 ok_$v=0 bad_$v=0"
done
render > "$OUT"
watch() {
pending=0
while sleep "$INTERVAL"; do
changed=0
for s in $SERVERS; do
v=$(var "$s")
# Readiness over the same mTLS as real traffic (LB identity, server verified against the lab CA).
if curl -sf -m 1 -o /dev/null --cacert /run/secrets/ca.crt --cert /run/secrets/client.crt \
--key /run/secrets/client.key "https://$s:8080/health/ready" 2>/dev/null; then
eval "ok_$v=\$((ok_$v + 1)) bad_$v=0"
if eval "[ \"\$up_$v\" = 0 ] && [ \"\$ok_$v\" -ge $RISE ]"; then
eval "up_$v=1"; changed=1; echo "health: $s ready, back in upstream"
fi
else
eval "bad_$v=\$((bad_$v + 1)) ok_$v=0"
if eval "[ \"\$up_$v\" = 1 ] && [ \"\$bad_$v\" -ge $FALL ]"; then
eval "up_$v=0"; changed=1; echo "health: $s not ready, marked down"
fi
fi
done
if [ "$changed" = 1 ]; then
render > "$OUT"
pending=1
fi
if [ "$pending" = 1 ] && nginx -s reload 2>/dev/null; then
pending=0
fi
done
}
watch &
exec nginx -g 'daemon off;'
+95
View File
@@ -0,0 +1,95 @@
# nginx 1.27 (lab7): the only business ingress. Client -> nginx: TLS (server cert SAN localhost/nginx).
# nginx -> every API replica: mTLS. nginx presents lb-client (identity lb.client.messenger) and verifies the replica
# certificate against the lab root CA with the shared SAN api.internal. The API itself checks the LB identity.
worker_processes 2;
pid /var/run/nginx.pid;
events {
worker_connections 256;
}
http {
resolver 127.0.0.11 valid=5s ipv6=off;
upstream api {
zone api 64k;
include /etc/nginx/upstream/servers.conf;
keepalive 32;
keepalive_timeout 4s;
}
log_format main '$remote_addr - $upstream_addr [$time_local] '
'"$request" $status $body_bytes_sent '
'"$upstream_response_time" "$request_time"';
access_log /var/log/nginx/access.log main;
server {
listen 8443 ssl;
ssl_certificate /run/secrets/server.crt;
ssl_certificate_key /run/secrets/server.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:tls:5m;
add_header Strict-Transport-Security "max-age=31536000" always;
server_tokens off;
client_max_body_size 64k;
error_page 413 @payload_too_large;
# Upstream mTLS (no fallback to plaintext, verification always on).
proxy_ssl_certificate /run/secrets/client.crt;
proxy_ssl_certificate_key /run/secrets/client.key;
proxy_ssl_trusted_certificate /run/secrets/ca.crt;
proxy_ssl_verify on;
proxy_ssl_verify_depth 2;
proxy_ssl_name api.internal;
proxy_ssl_server_name on;
proxy_ssl_protocols TLSv1.2 TLSv1.3;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 1s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 5s;
location ~ ^/api/v1/chats/[^/]+/messages$ {
proxy_pass https://api;
proxy_next_upstream error timeout http_502 http_503 non_idempotent;
}
location ~ ^/api/v1/chats/[^/]+/attachments$ {
client_max_body_size 10m;
proxy_request_buffering off;
proxy_pass https://api;
proxy_next_upstream off;
}
location @payload_too_large {
default_type application/json;
add_header X-Request-Id $request_id always;
add_header X-Instance-Id lb always;
add_header Connection close always;
return 413 '{"error":{"code":"payload_too_large","message":"Тело запроса слишком большое","request_id":"$request_id"}}';
}
location /health/ {
proxy_pass https://api;
proxy_next_upstream error timeout;
}
location ~ ^/api/v1/attachments/ {
proxy_max_temp_file_size 0;
proxy_pass https://api;
proxy_next_upstream error timeout;
}
location / {
proxy_pass https://api;
proxy_next_upstream error timeout http_502 http_503;
}
}
}
+39 -4
View File
@@ -1,7 +1,42 @@
# OpenBao — реализовать конфигурацию и политики
# OpenBao — конфигурация и действия оператора
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
OpenBao 2.6.5 в **server mode** (не dev): хранилище `file` на volume `baodata`, TLS-listener `openbao:8200` с сертификатом от lab Root CA. Наружу порт не опубликован; оператор работает через `docker compose exec` и CLI по TLS на `127.0.0.1` внутри контейнера.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
| Файл | Назначение |
| --- | --- |
| `config.hcl` | listener (TLS ≥ 1.2, `tls_client_ca_file` — запрос клиентского сертификата для cert auth), storage `file`, `disable_mlock` |
| `policies/messenger-api.hcl` | `read` только `messenger/data/api` и `messenger/metadata/api` |
| `policies/messenger-worker.hcl` | `read` только `messenger/data/worker` и `messenger/metadata/worker` |
| `../../scripts/bao.sh` | init, unseal, bootstrap, seal, rotate-worker-db, status (ничего секретного не печатает) |
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
## Аутентификация сервисов
Метод **cert**:
- роль `api`: сертификат цепочкой до lab Root CA и CN ровно `api.client.messenger`, политика `messenger-api`;
- роль `worker`: то же для `worker.client.messenger`, политика `messenger-worker`;
- у обеих ролей `token_ttl=15m`, `token_max_ttl=1h`.
Сервис получает только свой TLS-ключ (Docker secret) и логинится им (`app/openbao.py`). Root token, SecretID, `BAO_TOKEN` в окружении приложения не используются. Каждые 15 с токен продлевается или запрашивается заново, а новая версия KV-секрета передаётся в callback (ротация без рестарта).
## Действия оператора
```sh
sh scripts/bao.sh init # один раз: 3 доли unseal, порог 2, root token -> secrets/operator/ (0600); затем unseal
sh scripts/bao.sh bootstrap # идемпотентно: KV v2 `messenger/`, политики, роли cert auth, секреты сервисов
sh scripts/bao.sh status
sh scripts/bao.sh unseal # ПОСЛЕ КАЖДОГО рестарта OpenBao (он стартует запечатанным)
sh scripts/bao.sh seal # учебный инцидент
sh scripts/bao.sh rotate-worker-db # новый пароль роли app_worker: ALTER ROLE + новая версия messenger/worker
```
**После рестарта OpenBao:**
- уже работающие API и worker продолжают работать на полученных секретах;
- `scripts/bao.sh unseal` возвращает возможность входа;
- сервис, перезапущенный при запечатанном OpenBao, ждёт до `BAO_STARTUP_TIMEOUT_SECONDS` (120 с) и завершается с кодом 78, Docker перезапускает его до unseal;
- restart hook `scripts/restart.sh` делает unseal сам, потому что его запускает оператор.
**Восстановление и компрометация:**
- утрата root token — `bao operator generate-root` с порогом долей;
- компрометация роли сервиса — `bao delete auth/cert/certs/<role>` (новые логины невозможны), отзыв токенов по accessor, ротация секретов в KV, новый сертификат.
**Учебный компромисс.** Все 3 доли и root token лежат у одного оператора на хосте стенда (`secrets/operator/`, вне Git и образов, 0600). В production доли раздаются разным людям, root token отзывается после bootstrap, а для autounseal используется KMS или HSM.
+21
View File
@@ -0,0 +1,21 @@
# OpenBao 2.1.0 server mode (NOT dev mode): persistent file storage on the volume `baodata`, TLS listener.
# The listener asks for a client certificate (tls_client_ca_file) because services authenticate with the cert
# auth method; requests without a certificate are still possible for the operator CLI with a token.
ui = false
disable_mlock = true # container without IPC_LOCK; swap is not configured in the lab VM (documented trade-off)
api_addr = "https://openbao:8200"
# Single node: no cluster listener at all (2.6 opens 8201 by default; nothing should listen without a purpose).
disable_clustering = true
log_level = "info"
storage "file" {
path = "/openbao/file"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/run/secrets/openbao.crt"
tls_key_file = "/run/secrets/openbao.key"
tls_client_ca_file = "/run/secrets/ca.crt"
tls_min_version = "tls12"
}
+7
View File
@@ -0,0 +1,7 @@
# API replicas: read ONLY their own KV v2 secret (data + metadata for version checks). Nothing else.
path "messenger/data/api" {
capabilities = ["read"]
}
path "messenger/metadata/api" {
capabilities = ["read"]
}
@@ -0,0 +1,7 @@
# Worker: read ONLY its own KV v2 secret. It cannot read the API secret (other DB role, S3 user, Valkey ACL).
path "messenger/data/worker" {
capabilities = ["read"]
}
path "messenger/metadata/worker" {
capabilities = ["read"]
}
+111
View File
@@ -0,0 +1,111 @@
# OpenTelemetry Collector (contrib 0.120.0): receiver/processor/exporter only, it stores nothing long-term.
# API, worker --OTLP/HTTPS:4318 (mTLS)--> collector --mTLS--> Prometheus (OTLP), Loki (OTLP), Tempo (OTLP/gRPC)
# lab7: the receiver trusts ONLY the "Telemetry Ingest CA" (client_ca_file): api-otel / worker-otel certificates.
# A certificate from the root CA (LB, api, worker identities) or no certificate cannot push telemetry.
# Outbound: the collector presents collector-out (Telemetry Clients CA) and verifies each backend's server cert.
extensions:
health_check:
endpoint: 127.0.0.1:13133 # loopback only (no Docker healthcheck: distroless image)
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
max_request_body_size: 4194304 # 4 MiB per OTLP request
tls:
cert_file: /run/secrets/server.crt
key_file: /run/secrets/server.key
client_ca_file: /run/secrets/ingest-ca.crt
min_version: "1.2"
prometheus/self:
config:
scrape_configs:
- job_name: otel-collector
scrape_interval: 15s
static_configs: [{targets: ["127.0.0.1:8888"]}]
processors:
# First in every pipeline: refuse new data (receivers answer 503 -> SDK retries/drops) before the container OOMs.
# Container limit is 256 MiB; soft limit = limit_mib - spike_limit_mib = 140 MiB.
memory_limiter:
check_interval: 1s
limit_mib: 180
spike_limit_mib: 40
batch:
send_batch_size: 1024
send_batch_max_size: 2048
timeout: 2s
# Defense in depth: even if an instrumentation adds them, these attributes never leave the collector.
# url.query would contain ?filename=...; headers could contain Authorization.
attributes/scrub:
actions:
- {key: url.query, action: delete}
- {key: url.full, action: delete}
- {key: http.target, action: delete}
- {key: http.url, action: delete}
- {key: http.request.header.authorization, action: delete}
- {key: http.request.header.cookie, action: delete}
- {key: db.query.parameters, action: delete}
exporters:
# Every exporter verifies the backend against the lab root CA and authenticates as collector-out (mTLS).
otlphttp/prometheus:
endpoint: https://prometheus:9090/api/v1/otlp
tls: &client_tls
ca_file: /run/secrets/ca.crt
cert_file: /run/secrets/client.crt
key_file: /run/secrets/client.key
min_version: "1.2"
compression: gzip
timeout: 5s
sending_queue: {enabled: true, num_consumers: 2, queue_size: 100}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 120s}
otlphttp/loki:
endpoint: https://loki:3100/otlp
tls: *client_tls
compression: gzip
timeout: 5s
sending_queue: {enabled: true, num_consumers: 2, queue_size: 100}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 120s}
otlp/tempo:
endpoint: tempo:4317
tls: *client_tls
compression: gzip
timeout: 5s
sending_queue: {enabled: true, num_consumers: 2, queue_size: 100}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 120s}
service:
extensions: [health_check]
telemetry:
# Stable identity of the collector's own metrics (default is a random UUID per restart -> label churn).
resource:
service.instance.id: otel-collector
logs:
level: info
metrics:
level: detailed
# lab7: self-metrics are served on LOOPBACK only and scraped by the collector itself (receiver
# prometheus/self), then exported through the normal metrics pipeline over mTLS. Nothing is reachable from the
# network in plaintext. (Direct OTLP push of internal telemetry ignored client certificates in 0.120.0.)
readers:
- pull:
exporter:
prometheus:
host: 127.0.0.1
port: 8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp, prometheus/self]
processors: [memory_limiter, batch]
exporters: [otlphttp/prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, batch]
exporters: [otlphttp/loki]
+5
View File
@@ -0,0 +1,5 @@
# Default profile: no extra processing. All spans that the SDK head-sampled are exported.
# Selected with COLLECTOR_PROFILE=default (see compose.yaml); merged over collector.yaml.
processors:
batch:
timeout: 2s
+31
View File
@@ -0,0 +1,31 @@
# Track 1 "balanced" profile (COLLECTOR_PROFILE=tail): SDK keeps 100% head sampling, the collector decides per
# whole trace after decision_wait. Keeps: every trace with an error, every trace slower than 500 ms, every trace of
# the attachment pipeline (rare, async, valuable), and 10% of the remaining ordinary traffic.
# Metrics are computed in the SDK BEFORE any sampling, so RPS/error rate/percentiles are unaffected.
processors:
tail_sampling:
decision_wait: 10s
num_traces: 20000
expected_new_traces_per_sec: 200
decision_cache:
sampled_cache_size: 50000
policies:
- name: keep-errors
type: status_code
status_code: {status_codes: [ERROR]}
- name: keep-slow
type: latency
latency: {threshold_ms: 500}
- name: keep-async-pipeline
type: string_attribute
string_attribute: {key: messaging.system, values: [rabbitmq]}
- name: baseline-10pct
type: probabilistic
probabilistic: {sampling_percentage: 10}
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, tail_sampling, batch]
exporters: [otlp/tempo]
+8
View File
@@ -0,0 +1,8 @@
# PostgreSQL client authentication (lab7). Network clients: TLS only (hostssl) + SCRAM-SHA-256; plaintext refused.
# "local" = Unix socket inside the container only (healthcheck, operator `docker compose exec psql`): whoever can
# exec into the container already controls it, so trust adds no new access path.
local all all trust
hostssl all all 0.0.0.0/0 scram-sha-256
hostssl all all ::/0 scram-sha-256
host all all 0.0.0.0/0 reject
host all all ::/0 reject
+5
View File
@@ -0,0 +1,5 @@
# Client side of the container healthcheck (promtool check healthy): verify the server, present the operator cert.
tls_config:
ca_file: /run/secrets/ca.crt
cert_file: /run/secrets/health.crt
key_file: /run/secrets/health.key
+25
View File
@@ -0,0 +1,25 @@
# Prometheus v3.2.1: metrics store. Metrics arrive by OTLP push (--web.enable-otlp-receiver, /api/v1/otlp).
# The web listener is HTTPS with mandatory client certificates (web.yml).
global:
scrape_interval: 15s
evaluation_interval: 15s
otlp:
# job=service.name, instance=service.instance.id are set by Prometheus; these become extra labels.
promote_resource_attributes:
- service.name
- service.instance.id
- service.version
- deployment.environment.name
storage:
tsdb:
# OTLP pushes from several SDKs/batches may arrive slightly out of order.
out_of_order_time_window: 10m
rule_files:
- /etc/prometheus/rules/*.yml
# lab7: no scrape jobs. Every signal arrives by OTLP push over mTLS (application metrics through the Collector,
# Collector self-metrics directly). A scrape of a plaintext metrics port would be an unauthenticated side channel.
scrape_configs: []
+111
View File
@@ -0,0 +1,111 @@
# Recording rules (SLI/SLO) and alert rules. Evaluated by Prometheus every 15 s; state (pending/firing/inactive)
# is visible in Prometheus /alerts, the API /api/v1/alerts and in Grafana (alert list panel). No external delivery.
# Runbooks: docs/runbooks.md (anchors in runbook_url).
#
# Label mapping (OTLP -> Prometheus 3): service.name -> service_name, service.instance.id -> instance,
# http.route -> http_route, http.response.status_code -> http_response_status_code, job.type -> job_type.
# HTTP SLI denominator: every business request of messenger-api (health probes are not instrumented).
# Numerator of errors: 5xx only. 4xx (wrong password, 404 of a foreign chat, 409) are client outcomes, not failures.
groups:
- name: messenger-sli
interval: 15s
rules:
- record: messenger:http_requests:rate2m
expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m]))
- record: messenger:http_errors_5xx:rate2m
expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[2m])) or vector(0)
- record: messenger:http_error_ratio:rate2m
expr: messenger:http_errors_5xx:rate2m / messenger:http_requests:rate2m
- record: messenger:http_latency_p95:rate5m
expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api"}[5m])))
# SLO window: rolling 30 min (lab-sized; production would use 28-30 days with the same formulas).
# Availability SLO: 99% of business requests without 5xx.
- record: messenger:slo_availability:ratio30m
expr: |
1 - (
(sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[30m])) or vector(0))
/ sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api"}[30m]))
)
# Latency SLO: 95% of business requests complete in <= 500 ms (bucket le="0.5").
- record: messenger:slo_latency:ratio30m
expr: |
sum(increase(http_server_request_duration_seconds_bucket{service_name="messenger-api",le="0.5"}[30m]))
/ sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api"}[30m]))
- record: messenger:worker_saturation:ratio
# OTLP-pushed series have no staleness markers: a recreated worker would stay in the denominator for the
# 5 min lookback. Only samples fresher than 30 s (3 export intervals) are counted.
expr: |
sum(messenger_worker_busy and (time() - timestamp(messenger_worker_busy) < 30))
/ sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 30))
- name: messenger-alerts
rules:
- alert: MessengerApiHighErrorRate
expr: messenger:http_error_ratio:rate2m > 0.05 and messenger:http_requests:rate2m > 0.2
for: 1m
labels:
severity: page
annotations:
summary: "API: доля 5xx {{ $value | humanizePercentage }} за 2 мин (порог 5%)"
description: "Больше 5% бизнес-запросов messenger-api завершаются 5xx (окно 2m, держится 1m). Расходуется бюджет SLO доступности 99%."
runbook_url: "docs/runbooks.md#messengerapihigherrorrate"
- alert: MessengerQueueLagGrowing
expr: max(messenger_queue_oldest_age_seconds{queue="attachments.process"}) > 60
for: 1m
labels:
severity: page
annotations:
summary: "Очередь вложений: старейшее задание ждёт {{ $value | humanizeDuration }}"
description: "Принятое задание не завершено дольше 60 с (порог), условие держится 1m: worker остановлен, перегружен или не может писать в S3/DB."
runbook_url: "docs/runbooks.md#messengerqueuelaggrowing"
- alert: MessengerApiLatencyHigh
expr: messenger:http_latency_p95:rate5m > 1
for: 2m
labels:
severity: ticket
annotations:
summary: "API p95 = {{ $value | humanizeDuration }} (порог 1 s, окно 5m)"
description: "p95 из histogram buckets всех реплик выше 1 s."
runbook_url: "docs/runbooks.md#messengerapilatencyhigh"
- alert: MessengerDbPoolWaiting
expr: max(db_client_connection_pending_requests) > 0
for: 1m
labels:
severity: ticket
annotations:
summary: "Запросы ждут соединение из пула БД ({{ $value }} в очереди)"
description: "Пул psycopg исчерпан дольше минуты: БД медленная/блокирована или пул мал."
runbook_url: "docs/runbooks.md#messengerdbpoolwaiting"
- alert: MessengerWorkerSaturated
expr: messenger:worker_saturation:ratio > 0.9
for: 5m
labels:
severity: ticket
annotations:
summary: "Worker занят на {{ $value | humanizePercentage }} ёмкости 5 минут"
runbook_url: "docs/runbooks.md#messengerworkersaturated"
- alert: TelemetryExportFailing
# Each term has "or vector(0)": the *_failed_* series do not exist until the first failure, and a sum with an
# empty operand is empty (the alert would never fire). Early signal: exporter queue filling up (backend
# down, retries in progress); late signal: data dropped (queue full) or retries exhausted.
expr: |
(
(sum(rate(otelcol_exporter_send_failed_spans_total[2m])) or vector(0))
+ (sum(rate(otelcol_exporter_send_failed_log_records_total[2m])) or vector(0))
+ (sum(rate(otelcol_exporter_enqueue_failed_spans_total[2m])) or vector(0))
+ (sum(rate(otelcol_exporter_enqueue_failed_log_records_total[2m])) or vector(0))
) > 0
or
max(max by (exporter) (otelcol_exporter_queue_size) / max by (exporter) (otelcol_exporter_queue_capacity)) > 0.2
for: 1m
labels:
severity: ticket
annotations:
summary: "Collector не может доставить telemetry в backend"
description: "Очередь exporter заполнена >20% или данные отбрасываются: Tempo/Loki/Prometheus недоступен. Бизнес-API не затронут, RAM collector ограничена очередью и memory_limiter."
runbook_url: "docs/runbooks.md#telemetryexportfailing"
+9
View File
@@ -0,0 +1,9 @@
# Prometheus web listener (lab7): TLS + mandatory client certificate from the "Telemetry Clients CA" only
# (collector-out for OTLP ingest, grafana-out for queries, operator for evidence scripts and the healthcheck).
# Root-signed service identities (api, worker, lb) are not in this CA and are refused at the handshake.
tls_server_config:
cert_file: /run/secrets/server.crt
key_file: /run/secrets/server.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/secrets/telemetry-ca.crt
min_version: TLS12
+25
View File
@@ -0,0 +1,25 @@
{
"vhosts": [{"name": "messenger"}],
"users": [
{"name": "api.client.messenger", "password_hash": "", "hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []},
{"name": "worker.client.messenger", "password_hash": "", "hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []}
],
"permissions": [
{"user": "api.client.messenger", "vhost": "messenger", "configure": "^$", "write": "^attachments$", "read": "^$"},
{"user": "worker.client.messenger", "vhost": "messenger", "configure": "^$", "write": "^$", "read": "^attachments\\.process$"}
],
"exchanges": [
{"name": "attachments", "vhost": "messenger", "type": "direct", "durable": true, "auto_delete": false, "internal": false, "arguments": {}},
{"name": "attachments.dlx", "vhost": "messenger", "type": "fanout", "durable": true, "auto_delete": false, "internal": false, "arguments": {}}
],
"queues": [
{"name": "attachments.process", "vhost": "messenger", "durable": true, "auto_delete": false,
"arguments": {"x-queue-type": "quorum", "x-dead-letter-exchange": "attachments.dlx", "x-delivery-limit": 20}},
{"name": "attachments.dlq", "vhost": "messenger", "durable": true, "auto_delete": false,
"arguments": {"x-queue-type": "quorum"}}
],
"bindings": [
{"source": "attachments", "vhost": "messenger", "destination": "attachments.process", "destination_type": "queue", "routing_key": "attachment.process.v1", "arguments": {}},
{"source": "attachments.dlx", "vhost": "messenger", "destination": "attachments.dlq", "destination_type": "queue", "routing_key": "", "arguments": {}}
]
}
+1
View File
@@ -0,0 +1 @@
[rabbitmq_auth_mechanism_ssl].
+25
View File
@@ -0,0 +1,25 @@
# RabbitMQ 4.0 (lab7): TLS-only AMQP with mandatory client certificates. Identity = certificate CN, mapped to a
# passwordless user from definitions.json (auth mechanism EXTERNAL). No password users, no guest, no management UI.
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.cacertfile = /run/secrets/ca.crt
ssl_options.certfile = /run/secrets/server.crt
ssl_options.keyfile = /run/secrets/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
# Users, permissions, vhost and topology come from the definitions file on every boot.
definitions.import_backend = local_filesystem
definitions.local.path = /etc/rabbitmq/definitions.json
definitions.skip_if_unchanged = true
loopback_users = none
consumer_timeout = 600000
disk_free_limit.absolute = 200MB
vm_memory_high_watermark.relative = 0.6
log.console.level = warning
# Erlang distribution (CLI tools, clustering) is loopback-only: no cluster here, and rabbitmqctl runs inside the
# container. Otherwise ports 25672/4369 would be a cookie-protected plaintext channel reachable from the network.
distribution.listener.interface = 127.0.0.1
+40
View File
@@ -0,0 +1,40 @@
# Tempo 2.7.1 single binary: trace store (local blocks on a volume). Receives OTLP/gRPC (mTLS) from the Collector.
stream_over_http_enabled: true
server:
http_listen_port: 3200
grpc_listen_address: 127.0.0.1 # internal gRPC of the single binary: loopback only
log_level: warn
# lab7: query API over HTTPS with mandatory client certificates from the "Telemetry Clients CA".
http_tls_config:
cert_file: /run/secrets/server.crt
key_file: /run/secrets/server.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/secrets/telemetry-ca.crt
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
# OTLP ingest from the Collector only: mTLS with the same client CA (collector-out).
tls:
cert_file: /run/secrets/server.crt
key_file: /run/secrets/server.key
client_ca_file: /run/secrets/telemetry-ca.crt
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
query_frontend:
search:
max_result_limit: 10000
usage_report:
reporting_enabled: false
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
# Valkey (lab7): TLS-only (plaintext port 0), ACL users rendered at start into the tmpfs from a Docker secret.
# default disabled
# api session cache + login rate limit keys only, a minimal command set (no FLUSH*, CONFIG, KEYS, SCAN, EVAL)
# health PING only (container healthcheck)
# Cache only: no persistence; PostgreSQL stays the source of truth for sessions.
set -eu
umask 077
{
echo "user default off"
echo "user api on >$(cat /run/secrets/valkey_api_password) resetkeys ~session:* ~ratelimit:* resetchannels -@all +get +set +del +incr +incrby +expire +ttl +ping +hello +client|setinfo +client|setname +select"
echo "user health on >health resetkeys -@all +ping"
} > /tmp/users.acl
exec valkey-server \
--port 0 \
--tls-port 6379 \
--tls-cert-file /run/secrets/server.crt \
--tls-key-file /run/secrets/server.key \
--tls-ca-cert-file /run/secrets/ca.crt \
--tls-auth-clients no \
--aclfile /tmp/users.acl \
--save "" --appendonly no \
--maxmemory 64mb --maxmemory-policy allkeys-lru \
--dir /data