forked from mtusi2026/mtusi2026lab7
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8bf76612c | ||
|
|
9cc80d2529 |
+28
-31
@@ -1,41 +1,38 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
# Lab7: копируется в .env (scripts/init-secrets.sh) для ЛОКАЛЬНОГО синтетического стенда; .env не коммитится.
|
||||
# Здесь НЕТ секретов: пароли/ключи — в secrets/ (вне Git) и в OpenBao; CA keys и unseal shares —
|
||||
# в каталоге оператора ($OPERATOR_DIR, по умолчанию ~/.mtusi2026lab7-operator).
|
||||
# Соответствие логическим именам задания — REPORT.md «Архитектура и решения».
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
APP_VERSION=1
|
||||
API_REPLICAS=2
|
||||
WORKER_REPLICAS=2
|
||||
# Публичный HTTPS ingress (HAProxy, сертификат public-ca) и Grafana (HTTPS): только 127.0.0.1.
|
||||
LB_PORT=8443
|
||||
GRAFANA_PORT=3000
|
||||
SESSION_TTL_SECONDS=3600
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
S3_ENDPOINT=https://s3:9000
|
||||
S3_REGION=us-east-1
|
||||
# Ограничение входа на LB: попыток POST /auth/sessions за 10 с с одного IP (сверх — 429 + Retry-After).
|
||||
LOGIN_RATE_LIMIT=20
|
||||
# Argon2id (не ниже базового профиля m=19 MiB, t=2, p=1 — процесс иначе не стартует).
|
||||
ARGON2_MEMORY_KIB=19456
|
||||
ARGON2_ITERATIONS=2
|
||||
ARGON2_PARALLELISM=1
|
||||
PASSWORD_HASH_CONCURRENCY=2
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
S3_REGION=us-east-1
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
BROKER_URL_FILE=/run/secrets/broker_url
|
||||
WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
STAGING_RETENTION_SECONDS=86400
|
||||
OTEL_SERVICE_NAME=messenger-api
|
||||
# Worker must set a distinct service.name.
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
|
||||
PUBLIC_BASE_URL=https://localhost:8443
|
||||
TLS_CA_FILE=/run/secrets/ca.crt
|
||||
TLS_CERT_FILE=/run/secrets/service.crt
|
||||
TLS_KEY_FILE=/run/secrets/service.key
|
||||
BAO_ADDR=https://openbao:8200
|
||||
BAO_CACERT=/run/secrets/bao-ca.crt
|
||||
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
|
||||
ARGON2_MEMORY_KIB=19456
|
||||
ARGON2_ITERATIONS=2
|
||||
ARGON2_PARALLELISM=1
|
||||
OTEL_SDK_DISABLED=false
|
||||
# Сколько процесс ждёт unsealed OpenBao на старте, прежде чем завершиться (не берёт значений по умолчанию).
|
||||
BAO_STARTUP_WAIT_SECONDS=300
|
||||
# Фиксированные в compose.yaml (не переопределяются .env), для справки:
|
||||
# OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 (+ CA и client cert сервиса)
|
||||
# S3_ENDPOINT=https://s3:8333, POSTGRES_HOST=db (sslmode=verify-full), BAO_ADDR=https://openbao:8200
|
||||
# TLS_CA_FILE=/run/secrets/internal-ca.crt, TLS_CERT_FILE=/run/secrets/service.crt, TLS_KEY_FILE=/run/secrets/service.key
|
||||
# Учебные инъекции отказов (по умолчанию выключены):
|
||||
FAULT_INJECTION=0
|
||||
WORKER_FAULT_INJECTION=0
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
## Лабораторная 7
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
Трек 5, если заявлен: TODO
|
||||
Автор / группа: Лазарев Юрий Сергеевич, БПИ2303
|
||||
Целевая оценка (3/4/5): 3
|
||||
Трек 5, если заявлен: не заявлен
|
||||
|
||||
Что реализовано и что перенесено: TODO
|
||||
Команды запуска из чистого clone: TODO
|
||||
Результаты проверок и ссылка на REPORT.md: TODO
|
||||
Ограничения / известные ошибки: TODO
|
||||
Источники и использование ИИ: TODO
|
||||
Что реализовано и что перенесено: перенесена реализация lab6 (API ×2 за HAProxy, PostgreSQL, SeaweedFS S3, RabbitMQ, relay outbox, worker ×2, janitor, OTel Collector, Prometheus, Loki, Tempo, Grafana) без изменения бизнес-API. Добавлено: внешний HTTPS (public-ca) на 127.0.0.1:8443; обязательное mTLS LB→каждая API-реплика с allowlist identity `lb` (проверка SAN в приложении); TLS с проверкой сервера ко всем зависимостям (PostgreSQL verify-full + pg_hba только hostssl, HTTPS S3, AMQPS, OTLP/HTTPS с client cert, mTLS Collector→backends, Grafana→datasources, Prometheus scrape); OpenBao 2.7.2 не в dev-mode (Raft на volume, ручной init/unseal оператором, auth/cert с ролью и policy на сервис, TTL 15 мин + renew); раздельные роли PostgreSQL с грантами по таблицам; Argon2id (m=19 MiB, t=2, p=1, замер на стенде) с rehash; случайный X-Instance-Id; hardening (non-root, cap_drop ALL, no-new-privileges, read-only rootfs, tmpfs, лимиты, только 2 порта на 127.0.0.1); модель угроз и trust matrix; отрицательные тесты.
|
||||
Команды запуска из чистого clone: `./scripts/init-secrets.sh && ./scripts/bao-init.sh && docker compose --env-file .env up -d --build --wait && make check test test-security CA_FILE=$PWD/secrets/pki/public-ca.crt` — подробно в REPORT.md «Запуск из чистого clone».
|
||||
Результаты проверок и ссылка на REPORT.md: REPORT.md «Доказательства критериев»; stdout — evidence/*.txt, агрегаты — evidence/*.json (полный прогон `./student-tests/run_all.sh`).
|
||||
Ограничения / известные ошибки: REPORT.md «Ограничения и следующие шаги» (Collector/backends/RabbitMQ проверяют только CA, не роль клиента; нет ротации/CRL; unseal shares у оператора на том же хосте; часть нагрузочных тестов lab4–5 не перенесена на TLS — student-tests/legacy).
|
||||
Источники и использование ИИ: REPORT.md, шапка; код подготовлен с помощью ИИ-ассистента (Claude), запуск и проверки — автор.
|
||||
|
||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [ ] Контракт и публичные тесты не ослаблены.
|
||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [x] Контракт и публичные тесты не ослаблены.
|
||||
- [x] make check и make test выполнены; приложен реальный вывод.
|
||||
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Проверка РЕАЛИЗАЦИИ lab7 (contracts.yml проверяет только skeleton). Изолированный стенд Compose
|
||||
# с одноразовыми секретами и PKI, созданными на раннере; OPERATOR_DIR — временный каталог раннера
|
||||
# (роль «оператора» в CI играет сам job). Секреты CI не нужны. pull_request_target не используется.
|
||||
# Ограничение: локально workflow не исполнялся (нет раннера); проверен синтаксис YAML.
|
||||
name: Application
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
app:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
COMPOSE_PROJECT_NAME: mtusi-lab7-ci
|
||||
OPERATOR_DIR: ${{ runner.temp }}/operator
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Secrets, PKI, config
|
||||
run: ./scripts/init-secrets.sh && docker compose --env-file .env config --quiet
|
||||
- name: Telemetry configs and alert rule unit tests
|
||||
run: ./scripts/check_rules.sh
|
||||
- name: Build
|
||||
run: docker compose build migrate
|
||||
- name: OpenBao init/unseal/bootstrap (operator step)
|
||||
run: ./scripts/bao-init.sh
|
||||
- name: Start
|
||||
run: docker compose --env-file .env up -d --wait --wait-timeout 300
|
||||
- name: Public HTTPS smoke and external TLS trust
|
||||
run: make check test test-security CA_FILE=$PWD/secrets/pki/public-ca.crt
|
||||
- name: Internal TLS/mTLS matrix
|
||||
run: docker compose --profile tools run --rm -T checks /app/student-tests/lab7_tls_matrix.py
|
||||
- name: API negative tests
|
||||
run: python3 student-tests/lab7_api_security.py --ca-file secrets/pki/public-ca.crt
|
||||
- name: OpenBao policies and sealed behaviour
|
||||
run: python3 student-tests/lab7_openbao.py --ca-file secrets/pki/public-ca.crt
|
||||
- name: Hardening and secret leaks
|
||||
run: CA_FILE=$PWD/secrets/pki/public-ca.crt python3 student-tests/lab7_hardening.py
|
||||
- name: Persistence (HTTPS)
|
||||
run: make test-persistence ACTION_SCRIPT=scripts/restart.sh CA_FILE=$PWD/secrets/pki/public-ca.crt
|
||||
- name: Logs on failure (application services only; secrets are never logged)
|
||||
if: failure()
|
||||
run: docker compose logs --no-color --tail=200 api worker relay migrate s3-init lb openbao
|
||||
- name: Cleanup
|
||||
if: always()
|
||||
run: docker compose down -v
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
# Lab7: мессенджер на Python + PostgreSQL + S3 + RabbitMQ + OpenTelemetry SDK + OpenBao (секреты) + mTLS. Один образ для API-реплик, relay,
|
||||
# worker, janitor, ops-CLI и job-ов migrate (схема), s3-init (bucket).
|
||||
FROM python:3.12.7-slim@sha256:60d9996b6a8a3689d36db740b49f4327be3be09a21122bd02fb8895abb38b50d
|
||||
|
||||
# MALLOC_ARENA_MAX=2: glibc не заводит арену на каждый поток ThreadingHTTPServer —
|
||||
# освобождённые буферы upload возвращаются в общий пул, RSS не растёт с числом потоков.
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
MALLOC_ARENA_MAX=2 \
|
||||
APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8443
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Сначала зависимости (закреплённые версии) — слой кэшируется, пока не изменится requirements.txt.
|
||||
COPY requirements.txt /app/
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY src/ /app/src/
|
||||
COPY migrations/ /app/migrations/
|
||||
# Временные файлы upload (O_TMPFILE) и рабочие файлы worker — в /tmp. Lab7: rootfs контейнеров
|
||||
# read-only, /tmp — tmpfs (compose.yaml); каталоги создаёт сам процесс при старте.
|
||||
ENV UPLOAD_TMP_DIR=/tmp/uploads
|
||||
|
||||
# Метка версии сборки (rolling update: scripts/rolling-update.sh собирает с новым значением).
|
||||
ARG APP_VERSION=1
|
||||
ENV APP_VERSION=${APP_VERSION}
|
||||
|
||||
# Lab7: в образе нет секретов, ключей и сертификатов (.dockerignore исключает secrets/, *.key, *.pem);
|
||||
# всё это приходит в runtime: сертификат/ключ — Docker secret, пароли/ключи — из OpenBao.
|
||||
RUN useradd --no-create-home --uid 10001 app
|
||||
USER 10001:10001
|
||||
|
||||
# 8443 — mTLS (только identity lb); 8081 — health только на 127.0.0.1 контейнера.
|
||||
EXPOSE 8443
|
||||
# Python-процесс — PID 1 (exec-форма), сам обрабатывает SIGTERM (graceful shutdown).
|
||||
STOPSIGNAL SIGTERM
|
||||
HEALTHCHECK --interval=5s --timeout=2s --start-period=10s --retries=2 \
|
||||
CMD ["python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8081/health/ready', timeout=2).status == 200 else 1)"]
|
||||
CMD ["python", "/app/src/server.py"]
|
||||
@@ -1,37 +1,195 @@
|
||||
# Отчёт — лабораторная 7
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Лазарев Юрий Сергеевич, БПИ2303
|
||||
- Целевая оценка; выбранный трек 5, если нужен: **3**, трек 5 не заявлен (отдельные пункты уровня 4 сделаны попутно и отмечены, уровень 4 целиком не заявляется)
|
||||
- Commit/PR: [PR #23 — ЛР 7 — БПИ2303 — Лазарев — на 3](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab7/pulls/23); реализация `9cc80d2`, ветка `solution/bpi2303-lazarev`, fork [zemiles/mtusi2026lab7](https://gitea.privcloud.tech/zemiles/mtusi2026lab7).
|
||||
- Использованные источники, библиотеки и помощь ИИ: всё из lab6 (Python 3.12, psycopg 3.2.3, psycopg-pool 3.2.4, minio 7.2.20, urllib3 2.8.0, Pillow 13.0.0, pika 1.3.2, OpenTelemetry SDK 1.45.1) и **argon2-cffi 25.1.0** (+ argon2-cffi-bindings 25.1.0). Новый образ: `openbao/openbao:2.7.2@sha256:50469110…0561f`; остальные образы и digest — как в lab6 (см. `compose.yaml`). Документация: OWASP Password Storage / File Upload Cheat Sheets, OpenBao (auth/cert, policies, KV v2, integrated storage, production hardening, declarative audit), PostgreSQL (SSL, pg_hba, привилегии, `SELECT … FOR UPDATE`), RabbitMQ TLS и rabbitmq_prometheus TLS, HAProxy SSL (`verify`, `verifyhost`, `crt`), OTel Collector `configtls`, Prometheus web-config, Loki/Tempo `http_tls_config`, Grafana provisioning `$__file{}`, Docker security (capabilities, no-new-privileges, read-only). Код lab6 перенесён и доработан с помощью ИИ-ассистента (Claude); решения, запуск и проверки — автор.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Проверено: MacBook Air M3, 16 GB RAM, macOS 26.4.1; Docker Desktop 28.0.4 (VM 8 vCPU, 7.7 GiB), Compose v2.34.0; Python 3.12 на хосте (только стандартная библиотека, для тестов). Порты `127.0.0.1:8443` (HTTPS API) и `127.0.0.1:3000` (HTTPS Grafana) должны быть свободны — стенд lab6 остановить.
|
||||
|
||||
```sh
|
||||
# 0. Локальные секреты, PKI и .env (не коммитятся; значения не печатаются; повтор ничего не перезаписывает).
|
||||
# CA private keys -> $OPERATOR_DIR (по умолчанию ~/.mtusi2026lab7-operator, ВНЕ проекта).
|
||||
# Сертификаты выпускает OpenSSL закреплённого образа python:3.12.7-slim (docker run --network none).
|
||||
./scripts/init-secrets.sh
|
||||
|
||||
# 1. Офлайн-проверка конфигов (promtool config/web-config/rules, otelcol validate, loki -verify-config).
|
||||
./scripts/check_rules.sh
|
||||
|
||||
# 2. ОПЕРАТОР, один раз на пустом volume: OpenBao init (3 shares, порог 2) -> $OPERATOR_DIR/openbao/init.json,
|
||||
# unseal, KV v2, policies, роли auth/cert, запись сервисных секретов. Повтор безопасен.
|
||||
docker compose build migrate # образ приложения (собирает его только migrate)
|
||||
./scripts/bao-init.sh
|
||||
|
||||
# 3. Запуск (~40 с до готовности 18 контейнеров)
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait
|
||||
# порядок: openbao (unsealed) + db, s3, broker (healthy) -> migrate (роли+гранты), s3-init -> api x2,
|
||||
# relay, worker x2, janitor -> lb; телеметрия независимо: otel-collector, prometheus, loki, tempo -> grafana
|
||||
docker compose ps # migrate и s3-init Exited (0); порты только у lb и grafana
|
||||
|
||||
# 4. Обязательные проверки (публичный CA — secrets/pki/public-ca.crt)
|
||||
CA=$PWD/secrets/pki/public-ca.crt
|
||||
make check && make test CA_FILE=$CA && make test-security CA_FILE=$CA
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh CA_FILE=$CA # рестарт ВСЕХ хранилищ, вкл. OpenBao (+unseal)
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh CA_FILE=$CA && ./scripts/start-all.sh
|
||||
|
||||
# 5. Проверки lab7
|
||||
docker compose --profile tools run --rm -T checks /app/student-tests/lab7_tls_matrix.py --output /app/evidence/lab7-tls-matrix.json
|
||||
python3 student-tests/lab7_api_security.py --ca-file $CA --output evidence/lab7-api-security.json
|
||||
python3 student-tests/lab7_openbao.py --ca-file $CA --output evidence/lab7-openbao.json
|
||||
CA_FILE=$CA python3 student-tests/lab7_hardening.py --output evidence/lab7-hardening.json
|
||||
docker compose exec -T api python - < student-tests/argon2_bench.py > evidence/argon2-bench.json
|
||||
|
||||
# Всё сразу с записью stdout в evidence/*.txt:
|
||||
./student-tests/run_all.sh # обязательное + lab7 (≈ 8 мин)
|
||||
WITH_LAB6=1 ./student-tests/run_all.sh # + перенесённые проверки lab6/lab5 поверх TLS
|
||||
|
||||
# 6. Grafana: https://localhost:3000 (доверить secrets/pki/public-ca.crt), admin / secrets/grafana_admin_password.
|
||||
|
||||
# 7. После рестарта Docker/хоста: OpenBao sealed -> ОПЕРАТОР
|
||||
./scripts/bao-unseal.sh
|
||||
|
||||
# 8. Безопасная остановка (данные и секреты OpenBao остаются в volumes)
|
||||
docker compose stop # или docker compose down (volumes остаются)
|
||||
|
||||
# 9. Намеренное удаление учебных данных (НЕОБРАТИМО): volumes, затем материал оператора
|
||||
docker compose down -v # после этого init.json в $OPERATOR_DIR/openbao не соответствует стенду —
|
||||
# удалить его вручную перед новым bao-init.sh
|
||||
```
|
||||
|
||||
**Действия оператора.** Только оператор имеет `$OPERATOR_DIR` (ключи CA, root token, unseal shares). Нужны: `bao-init.sh` один раз на новый volume, `bao-unseal.sh` после каждого рестарта контейнера OpenBao (Docker/хост). Обычный рестарт API/worker ничего не требует. `restart.sh` — операторский хук, поэтому сам делает unseal.
|
||||
|
||||
**Замечание (Docker Desktop на macOS)**: как в lab6, при запуске из неинтерактивной среды `docker pull` зависал на keychain-хелпере; обход — отдельный `DOCKER_CONFIG` с `config.json = {}` и ссылкой `cli-plugins`. Публичные образы скачиваются анонимно.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```
|
||||
хост 127.0.0.1:8443 ─HTTPS(public-ca)─► lb ═mTLS: lb предъявляет id "lb", проверяет SAN "api"═► api ×2
|
||||
│ сеть apinet (internal: только lb и api) │
|
||||
хост 127.0.0.1:3000 ─HTTPS(public-ca)─► grafana ═mTLS═► prometheus / loki / tempo │
|
||||
│
|
||||
api/relay/worker/janitor ──TLS verify-full + роль *_svc──► db (PostgreSQL, hostssl only) ◄──────┤
|
||||
api/worker/janitor ──HTTPS + свой ключ──► s3 (SeaweedFS) │
|
||||
relay/worker ──AMQPS 5671 + свой пользователь/ACL──► broker (RabbitMQ) │
|
||||
все процессы приложения ═OTLP/HTTPS + client cert═► otel-collector ═mTLS═► tempo/loki/prometheus │
|
||||
api/relay/worker/janitor/migrate/s3-init/ops ──TLS + auth/cert──► openbao (сеть vault) ◄─────────┘
|
||||
```
|
||||
|
||||
Источник истины, транзакционные границы, outbox, at-least-once и наблюдаемость — без изменений с lab5/lab6. Изменения lab7:
|
||||
|
||||
| Область | Решение | Где |
|
||||
| --- | --- | --- |
|
||||
| PKI | Два CA: **public-ca** (ingress, Grafana; его сертификат раздаётся клиентам) и **internal-ca** (сервисы). ECDSA P-256, leaf 30 дней, CA 365 дней, SAN DNS = имя сервиса = identity. Ключи CA — только у оператора. Тестовые identities: `intruder` (internal-ca, чужая роль), `rogue-lb` (чужой CA, SAN `lb`) | `scripts/init-secrets.sh`, `scripts/pki-issue.sh` |
|
||||
| Внешний TLS | HAProxy `:8443 ssl`, TLS ≥ 1.2, без tickets, HSTS, без `Server` | `infra/haproxy/haproxy.cfg` |
|
||||
| LB → API | mTLS обязательный: LB проверяет CA + `verifyhost api`, предъявляет `lb.pem`; API — `CERT_REQUIRED` и **SAN ∈ MTLS_ALLOWED_CLIENTS (= lb)**, иначе закрытие до HTTP. Handshake в потоке соединения, таймаут 5 с. Health — отдельный plaintext listener **только 127.0.0.1:8081** | `src/server.py` (`Server.finish_request`, `HealthHandler`), `src/tlsutil.py` |
|
||||
| Секреты | OpenBao 2.7.2: Raft на volume, TLS, audit → stdout; **auth/cert** (identity = leaf сервиса), policy на сервис = read только своего `kv/data/messenger/<svc>`; токен 15 мин/max 1 ч, renew, re-login. В env/образе/Docker secrets приложений паролей нет | `infra/openbao/`, `scripts/bao-init.sh`, `src/vault.py` |
|
||||
| PostgreSQL | `ssl=on`, pg_hba: `hostssl … scram-sha-256`, `hostnossl reject`, локально `peer` только для `postgres`. Роли `api_svc/worker_svc/relay_svc/janitor_svc/ops_svc` + гранты по таблицам; для `SELECT … FOR UPDATE` — только `UPDATE(id)`. DDL — job `migrate` (роль `postgres`) | `infra/postgres/`, `migrations/security/grants.sql`, `src/migrate.py` |
|
||||
| S3 | SeaweedFS S3 только HTTPS; minio-py с CA; разные ключи api/worker/janitor/admin (как в lab6), выдаются из OpenBao | `compose.yaml` (s3), `src/objstore.py` |
|
||||
| Брокер | RabbitMQ: только AMQPS 5671, `verify_peer`; метрики только HTTPS 15691 c обязательным cert; epmd/dist — 127.0.0.1 | `infra/rabbitmq/rabbitmq.conf`, `src/common.py` |
|
||||
| Телеметрия | OTLP/HTTPS + обязательный client cert на Collector; mTLS Collector → Tempo/Loki/Prometheus; scrape только HTTPS + cert; Grafana → datasources HTTPS + cert; Grafana сама — HTTPS | `infra/otel`, `infra/prometheus`, `infra/loki`, `infra/tempo`, `infra/grafana` |
|
||||
| Пароли | **Argon2id** m=19456 KiB, t=2, p=1, соль 16 B, PHC-строка; процесс не стартует с параметрами ниже базовых; rehash scrypt/старых параметров при входе; dummy-hash для неизвестного логина | `src/security.py` |
|
||||
| Alias реплики | `X-Instance-Id` = случайный `r-<10 hex>` на жизнь процесса (не hostname); `stop-one.sh` находит контейнер по `/tmp/instance-id` | `src/instance.py`, `scripts/stop-one.sh` |
|
||||
| Hardening | Приложение: uid 10001, `cap_drop: ALL`, `no-new-privileges`, `read_only` + tmpfs `/tmp`, лимиты CPU/RAM/PIDs. Остальные: `no-new-privileges`, `cap_drop: ALL` (+ минимальный `cap_add` для entrypoint-ов db/broker/s3), read-only где совместимо. Наружу — только 127.0.0.1:8443 и 127.0.0.1:3000 | `compose.yaml` |
|
||||
|
||||
**Сети.** `frontend` (lb, публикация), `apinet` internal (lb ↔ api), `backend` internal (данные), `telemetry` internal, `vault` internal (OpenBao + процессы приложения), `grafana-ui` (публикация Grafana). LB не видит БД/S3/брокер/OpenBao; Grafana — только telemetry.
|
||||
|
||||
**Роли, сервисы и credentials**
|
||||
|
||||
| Роль | Service | Образ | Health/readiness | Volume | Сеть / порт | Credentials |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| LB | `lb` | `haproxy:3.0.5-alpine` | `haproxy -c`; сам проверяет `/health/ready` API по mTLS | — | frontend+apinet+telemetry; `127.0.0.1:8443`; `:8404` (stats/metrics, mTLS, только telemetry) | Docker secrets: `lb-public.pem` (public-ca), `lb.pem` (identity lb) |
|
||||
| API ×2 | `api` | `mtusi-messenger:lab7` | `127.0.0.1:8081/health/ready` (БД) | — | apinet+backend+telemetry+vault; `8443` mTLS, не опубликован | cert `api` (Docker secret) → OpenBao `kv/messenger/api`: пароль `api_svc`, ключ S3 api |
|
||||
| Worker ×2 | `worker` | тот же | heartbeat-файл | tmpfs | backend+telemetry+vault | cert `worker` → `kv/messenger/worker`: `worker_svc`, ключ S3 worker, AMQPS user worker |
|
||||
| Relay | `relay` | тот же | heartbeat | — | backend+telemetry+vault | cert `relay` → `relay_svc`, AMQPS user relay |
|
||||
| Janitor | `janitor` | тот же | heartbeat | — | backend+telemetry+vault | cert `janitor` → `janitor_svc`, ключ S3 janitor |
|
||||
| Миграции/роли | `migrate` (job) | тот же | Exited 0 | — | backend+vault | cert `migrate` → `kv/messenger/migrate` (суперпользователь + пароли ролей), токен 5 мин |
|
||||
| Bucket | `s3-init` (job) | тот же | Exited 0 | — | backend+vault | cert `s3-init` → ключ S3 admin |
|
||||
| PostgreSQL | `db` | `postgres:16.4-alpine` | `su-exec postgres pg_isready` | `pgdata` | backend; `5432` TLS | `postgres_password` (Docker secret), cert `db` |
|
||||
| S3 | `s3` | `chrislusf/seaweedfs:4.50` | `curl --cacert … https://127.0.0.1:8333/healthz` + запись в filer | `s3data` | backend; `8333` HTTPS | `s3_identities.json` (Docker secret), cert `s3` |
|
||||
| Брокер | `broker` | `rabbitmq:4.1.4-alpine` | running, alarms, listener 5671, очередь объявлена | `brokerdata` | backend+telemetry; `5671` AMQPS, `15691` HTTPS-метрики | `rabbitmq_definitions.json` (только хеши паролей), cert `broker` |
|
||||
| Секреты | `openbao` | `openbao/openbao:2.7.2` | `bao status` (0 = unsealed) | `baodata` (Raft) | vault; `8200` TLS | cert `openbao`; root/shares — у оператора |
|
||||
| Collector | `otel-collector` | `otel/opentelemetry-collector-contrib:0.163.2` | `up{job="otelcol-contrib"}` | — | telemetry; `4318` OTLP/HTTPS mTLS | cert `otel-collector` |
|
||||
| Метрики | `prometheus` | `prom/prometheus:v3.13.5` | `promtool check ready` по mTLS | `promdata` | telemetry; `9090` mTLS | cert `prometheus` |
|
||||
| Логи | `loki` | `grafana/loki:3.6.19` | `up{job="loki"}` | `lokidata` | telemetry; `3100` mTLS | cert `loki` |
|
||||
| Трассы | `tempo` | `grafana/tempo:2.10.10` | `up{job="tempo"}` | `tempodata` | telemetry; `3200`, `4317` mTLS | cert `tempo` |
|
||||
| UI | `grafana` | `grafana/grafana:12.4.14` | `curl --cacert public-ca https://localhost:3000/api/health` | `grafanadata` | telemetry+grafana-ui; `127.0.0.1:3000` HTTPS | admin — Docker secret; cert `grafana` (к datasources), `grafana-public` (сервер) |
|
||||
|
||||
**Переменные `.env.example` → конфигурация.** `DATABASE_URL_FILE` skeleton → `POSTGRES_HOST/DB/USER` + пароль роли из OpenBao (`POSTGRES_PASSWORD`), `sslmode=verify-full`; `S3_ACCESS_KEY_ID_FILE/S3_SECRET_ACCESS_KEY_FILE` → поля KV `S3_ACCESS_KEY_ID/S3_SECRET_ACCESS_KEY`; `BROKER_URL_FILE` → поле KV `BROKER_URL` (amqps); `TLS_CA_FILE/TLS_CERT_FILE/TLS_KEY_FILE` → `/run/secrets/internal-ca.crt|service.crt|service.key` (те же имена, дефолты `src/tlsutil.py`); `BAO_ADDR/BAO_CACERT` → как в skeleton + `BAO_AUTH_ROLE`, `BAO_KV_PATH`; `ARGON2_*` — как в skeleton; `PUBLIC_BASE_URL` → `https://localhost:8443` (тесты); `APP_PORT=8443` (mTLS), `HEALTH_PORT=8081`. `SESSION_STORE=postgres`, `CACHE_URL_FILE` — не используются (Redis/Valkey нет).
|
||||
|
||||
**Критичные зависимости readiness.** `/health/ready` API = PostgreSQL (как в lab6). OpenBao в readiness не входит: секреты читаются при старте процесса — без OpenBao процесс не стартует (и не становится ready), а работающий продолжает с секретами в памяти. Недоступность Grafana/телеметрии на API не влияет.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
Все прогоны — на стенде выше, 2026-11-18, проект `mtusi-lab7`. Сводный прогон: `WITH_LAB6=1 ./student-tests/run_all.sh` → [evidence/run-all.txt](evidence/run-all.txt).
|
||||
|
||||
**Воспроизводимость из чистого clone.** Копия репозитория без `secrets/`, `.env` и материала оператора (отдельный `COMPOSE_PROJECT_NAME=mtusi-lab7-clean` и `OPERATOR_DIR`): `init-secrets.sh` → `check_rules.sh` → `docker compose build --no-cache migrate` → `bao-init.sh` → `up --wait` → `WITH_LAB6=1 run_all.sh` — **ALL PASS** без ручных правок ([evidence/clean-clone-run.txt](evidence/clean-clone-run.txt)); затем этот стенд удалён (`down -v`).
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Публичный smoke по HTTPS | `make check`; `make test CA_FILE=…/public-ca.crt` | `PASS: lab7 public API scenario` (health → пользователи → вход → чат → сообщения → пагинация → ACL → идемпотентность → файл → thumbnail → logout) | evidence/make-test.txt |
|
||||
| HTTPS с проверяемым CA и hostname/SAN; недоверенный TLS | `make test-security`; `lab7_api_security.py` (`tls.*`) | пустой trust store → `SSLCertVerificationError`; SNI `evil.example` → Hostname mismatch; internal-ca не валидирует ingress; TLS 1.1 → `PROTOCOL_VERSION` | evidence/make-test-security.txt, evidence/lab7-api-security.json |
|
||||
| Argon2id: salt и параметры, не ниже 19 MiB/t=2/p=1, обоснование замером | `lab7_api_security.py` (`argon2.*`); `argon2_bench.py` в контейнере API | В БД `$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>`, соли разные; rehash scrypt → Argon2id при входе; замер — раздел «Эксперименты» | evidence/lab7-api-security.json, evidence/argon2-bench.json |
|
||||
| LB → каждая API-реплика: обязательное mTLS, проверка identity, нет обхода | `lab7_tls_matrix.py` (в сети стенда) | для обеих реплик: без cert → `CERTIFICATE_REQUIRED`; rogue CA (SAN lb) → `UNKNOWN_CA`; internal-ca, identity `intruder` → закрыто после handshake без HTTP-ответа; plaintext → reset; `:8081` из сети → refused; identity `lb` → 200, бизнес-API без Bearer → 401; порт API не опубликован | evidence/lab7-tls-matrix.json, evidence/lab7-hardening.json |
|
||||
| TLS с проверкой сервера к DB, S3, broker, Collector, backends, OpenBao; раздельные credentials | `lab7_tls_matrix.py`; `selfcheck.py` внутри сервисов | 67/67: plaintext отвергается у всех (pg_hba reject, 400 HTTPS, refused), чужой CA/hostname → ошибка проверки, без client cert → отказ у Collector/Prometheus/Loki/Tempo/lb:8404/broker:15691; `pg_stat_ssl` TLSv1.3 у всех ролей; разные роли БД/ключи S3/пользователи брокера | evidence/lab7-tls-matrix.json, evidence/lab7-openbao.json |
|
||||
| OpenBao не dev, persistent; сервисная аутентификация, scoped policy; нет root/unseal/широкого токена в приложении | `lab7_openbao.py` | `storage_type=raft`, `t=2 n=3`, entrypoint `bao server -config=…`; для api/worker/relay/janitor: policies `default,messenger-<svc>`, TTL 900, свой путь 200, чужой/`migrate`/list/запись/policy/token create/seal → 403, после revoke 403; в env нет токенов; смонтированы только CA+свой cert/key; KV пережил рестарт | evidence/lab7-openbao.json |
|
||||
| Worker не получает admin credentials | `lab7_openbao.py` (`worker.*`) | ключ S3 worker = свой (не admin/api); `worker_svc` — denied на users/sessions/messages; путь `migrate` → 403 | evidence/lab7-openbao.json |
|
||||
| Контейнеры: без privileged/host network/docker.sock; app/worker non-root, без capabilities, лимиты; наружу только TLS ingress и локальные admin | `lab7_hardening.py` | 182/182: no-new-privileges везде, `CapDrop ALL` везде (cap_add только db/broker/s3 — документировано), app uid 10001 + read-only rootfs, лимиты у всех; опубликованы только `127.0.0.1:8443` и `127.0.0.1:3000`; loopback health-listener изнутри контейнера отдаёт только `/health/*` (бизнес-API → 404) | evidence/lab7-hardening.json |
|
||||
| Secret values/ключи не в Git, образах, telemetry | `scripts/scan_secrets.py`; `lab7_hardening.py` (`image.*`, `telemetry.*`); `obs_correlation.py` | 125 значений (пароли, ключи S3, тела PEM leaf и CA keys, root token, unseal shares) — 0 файлов; в образе нет `*.key/*.pem`/secrets, история слоёв чистая; в Loki/Tempo нет свежего токена/пароля (с положительным контролем поиска) | evidence/lab7-hardening.json, evidence/scan-secrets.txt, evidence/obs-correlation.json |
|
||||
| Rate limit входа 429/Retry-After | `lab7_api_security.py` (`ratelimit.*`) | первый 429 на 21-й попытке за 10 с, `Retry-After: 10`, JSON `rate_limited` с `request_id`; после окна вход снова 201 | evidence/lab7-api-security.json |
|
||||
| Ограничение размера запросов | `lab7_api_security.py` (`limits.*`) | JSON > 1 MiB → 413; upload > 10 MiB → 413 до чтения тела | evidence/lab7-api-security.json |
|
||||
| Доступ постороннего; поддельный X-User-Id | `lab7_api_security.py` (`outsider.*`, `spoof.*`) | chat/history/metadata/content/thumbnail → 404; прикрепление чужого файла → 404; запись в чужой чат → 404; `X-User-Id` чужого пользователя не меняет `/users/me` | evidence/lab7-api-security.json |
|
||||
| Logout / expiry | `lab7_api_security.py` (`logout.*`, `expiry.*`) | logout 204 → тот же токен 401, повтор 401; сессия с `expires_at` в прошлом (оператор, своя тестовая строка) → 401 | evidence/lab7-api-security.json |
|
||||
| Сертификаты локально, документированный bootstrap | `./scripts/init-secrets.sh` | выпуск 2 CA + 19 leaf сервисов (+ тестовые: rogue CA, `intruder`, `rogue-lb`); CA keys в `$OPERATOR_DIR/ca` (600); README infra/openbao, trust-matrix | — |
|
||||
| Перезапуск с сохранением данных (HTTPS) | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS; хук перезапустил openbao (+unseal), db, s3, broker, prometheus, loki, tempo и все процессы — состояния до/после | evidence/test-persistence.txt, evidence/persistence-ps-before.txt, evidence/persistence-ps-after.txt |
|
||||
| Последовательный отказ API-реплик (HTTPS) | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` ×N | PASS для api-1 и api-2 (для api-2 очередь round-robin сдвинута одним лишним запросом), 96–98 подтверждённых записей, 0 ошибок, восстановление записи 3.7–4.7 с | evidence/test-failover.txt |
|
||||
| Нагрузка по HTTPS | `tests/load.py --duration 30 --concurrency 4` | 9588 успешных, 0 ошибок, 319.5 rps, p50 8.3 мс (после исправления Nagle; до — 80.9 rps, p50 48.8 мс) | evidence/load-after-nodelay.json, evidence/load-before-nodelay.json |
|
||||
| Сохранение lab6 (наблюдаемость) поверх mTLS | `obs_correlation.py`, `dashboard_check.py`, `check_rules.sh` | трасса upload→relay→worker (26 spans), логи по trace_id в Loki; 3 datasource OK, 56 панелей без ошибок; все scrape-цели `up=1` | evidence/obs-correlation.json, evidence/dashboard-check.json, evidence/prometheus-up.txt |
|
||||
| Сохранение lab5 (фоновая обработка) | `worker_outage.py` | остановка worker → upload 202 → рестарт API+брокера → ready, повторная доставка — no-op | evidence/worker-outage.txt |
|
||||
| Модель угроз, trust matrix | — | 10 угроз с контролями и тестами; матрица заполнена, N/A с причинами | security/THREAT_MODEL.md, contracts/trust-matrix.md |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Пункты уровня 4, сделанные попутно (уровень 4 не заявляется): rehash старого хеша при входе; общий для реплик rate limit; read-only/no-new-privileges/drop capabilities и tmpfs; ограничение upload-worker по CPU/RAM/времени (cgroup + RLIMIT подпроцесса, с lab5); проверка отсутствия утечек в telemetry; поведение при sealed OpenBao.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
**Argon2id — выбор параметров** (`argon2_bench.py` внутри API-контейнера: cgroup 0.5 CPU, 640 MiB, aarch64; 15 хешей + 15 проверок на профиль, затем 2×15 параллельно — как `PASSWORD_HASH_CONCURRENCY=2`):
|
||||
|
||||
| Профиль | hash p50 / p95, мс | verify p50, мс | рост RSS, MiB | хешей/с на реплику (2 потока) |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **m=19 MiB, t=2, p=1 (выбран)** | 13.0 / 64.8 | 13.2 | 18.2 | 27.2 |
|
||||
| m=46 MiB, t=1, p=1 (OWASP alt) | 21.6 / 71.3 | 21.6 | 46.0 | 14.4 |
|
||||
| m=19 MiB, t=3, p=1 | 23.4 / 108.6 | 69.7 | — | 16.6 |
|
||||
| m=64 MiB, t=3, p=1 | 186.4 / 207.8 | 183.9 | — | 3.7 |
|
||||
| m=19 MiB, t=2, p=2 | 8.0 / 80.8 | — | — | 15.0 |
|
||||
|
||||
p95 завышен троттлингом CFS (квота 50 мс на 100 мс), это реальная задержка входа на стенде. Обоснование: базовый профиль OWASP (минимум задания) даёт ~13 мс на вход и ~27 входов/с на реплику (≈ 54/с на стенд); 2 одновременных хеша занимают ~37 MiB из 640 MiB. Профиль m=64 MiB/t=3 удорожает офлайн-перебор в ~14 раз, но снижает пропускную способность входа до 3.7/с на реплику — на 0.5 CPU 20 попыток (лимит LB за 10 с с одного IP) заняли бы ~5 с CPU всей реплики. Для учебного стенда с лимитом 0.5 CPU выбран базовый профиль; параметры меняются переменными `ARGON2_*` без миграции (хеши самоописаны, rehash при входе).
|
||||
|
||||
**Нагрузка по HTTPS и найденная регрессия задержки.** `tests/load.py --duration 30 --concurrency 4` (closed-loop, только POST сообщений, клиент открывает новое TLS-соединение на каждый запрос; путь клиент →TLS→ LB →mTLS→ API → PostgreSQL TLS; телеметрия включена, 100 % трасс). Гипотеза: стабильные ~+40 мс к каждому ответу после перехода на TLS — эффект Nagle на сокете Python-сервера (заголовки и тело ответа — отдельные TLS-записи; вторая ждёт ACK первой, а HAProxy подтверждает с delayed ACK ~40 мс). Проверка — включить `TCP_NODELAY` на сокете API (`disable_nagle_algorithm = True`), остальное без изменений:
|
||||
|
||||
| Конфигурация | успешных / ошибок | успешных rps | p50 / p95 / p99, мс | Файл |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| lab6 (plaintext HTTP, тот же стенд) | 14173 / 0 | 471 | 4.8 / 37.6 / 56.3 | REPORT.md lab6 |
|
||||
| lab7, Nagle включён | 2429 / 0 | 80.9 | 48.8 / 52.9 / 75.1 | evidence/load-before-nodelay.json |
|
||||
| **lab7, TCP_NODELAY (итог)** | 9588 / 0 | **319.5** | **8.3** / 37.7 / 77.5 | evidence/load-after-nodelay.json |
|
||||
|
||||
Гипотеза подтверждена (p50 −40 мс, rps ×4). Оставшаяся разница с lab6 (~32 %) — TLS-handshake на каждый запрос нагрузочного клиента (urllib без keep-alive) и шифрование на двух hop-ах; повторное использование соединений LB→API (`http-reuse safe`) сохраняется, TLS-сессии намеренно не переиспользуются (`no-ssl-reuse`, без tickets — каждое новое соединение заново проверяет identity). Ограничения: один прогон по 30 с на конфигурацию, closed-loop (coordinated omission), клиент на том же хосте; это сравнение конфигураций, а не предельная пропускная способность.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Рестарт всех хранилищ и процессов (`restart.sh`, вкл. OpenBao + unseal) | данные и прежняя сессия доступны | PASS `test-persistence` | ~60 с хук; потерь нет |
|
||||
| Остановка api-1, затем api-2 (`stop-one.sh`) | запись продолжается через вторую реплику, без дублей | PASS ×2, 0 failed attempts | 3.7–4.7 с; потерь и дублей нет |
|
||||
| OpenBao sealed (рестарт контейнера) при работающем API | работающие реплики обслуживают; новая не стартует; после unseal — стартует | вход и `/users/me` = 200; перезапущенная api-1 `unhealthy`, в логе `openbao not ready (… sealed)`; LB отдаёт ответы с другой реплики; после `bao-unseal.sh` — healthy | ~12 с после unseal (42 с от рестарта реплики); KV на месте |
|
||||
| Чужой клиент в сети стенда (no cert / rogue CA / intruder) → API | отказ до HTTP | отказ во всех трёх случаях, событие `mtls.identity_rejected` | — |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- **Identity только на LB→API.** Collector, Prometheus, Loki, Tempo, `lb:8404` и RabbitMQ проверяют цепочку internal-ca, но не роль клиента: любой сервис с сертификатом internal-ca может слать телеметрию/читать метрики (тест фиксирует, что `intruder` принят Collector-ом). Брокер аутентифицирует по паролю + ACL, client cert не обязателен. Разграничение identity (OTel `auth` extension / sidecar, `rabbitmq_auth_mechanism_ssl`) — уровень 4.
|
||||
- **Нет ротации и отзыва сертификатов** (CRL/OCSP, короткоживущие leaf из OpenBao PKI) и не продемонстрирована ротация секрета; механизм для паролей ролей БД есть (`bao-init.sh` + `migrate`). Leaf 30 дней — продление вручную.
|
||||
- **Unseal shares** хранятся у оператора на том же хосте (отдельно от OpenBao, 600, вне проекта) — учебный компромисс; root token не отозван после bootstrap (нет отдельной операторской policy).
|
||||
- **S3-права — по bucket**, не по prefix: worker и api читают все объекты bucket.
|
||||
- **Rate limit — по IP на одном LB**: распределённый перебор не ограничен; один LB — единая точка отказа (как в lab3–6).
|
||||
- Dependency/image scan с разбором применимости не выполнялся (уровень 4).
|
||||
- Часть нагрузочных/отказных тестов lab4–5 (медленный клиент, прогрессивный upload, память upload, нагрузочный failover) написана под plaintext `:8080` и не перенесена на TLS — `student-tests/legacy/README.md`; обязательные возможности покрыты HTTPS smoke и перенесёнными проверками.
|
||||
- Один Docker-host: отказ хоста, Docker daemon или root на хосте модель не покрывает.
|
||||
|
||||
+842
@@ -0,0 +1,842 @@
|
||||
# Lab7 = lab6 + защита: HTTPS снаружи, mTLS LB->API, TLS ко всем зависимостям, OpenBao, hardening.
|
||||
#
|
||||
# клиент --HTTPS :8443 (public-ca)--> lb --mTLS (identity lb, internal-ca)--> api x2
|
||||
# api/relay/worker/janitor --TLS verify-full--> db (PostgreSQL, отдельные роли *_svc)
|
||||
# --HTTPS--> s3 (SeaweedFS, отдельные ключи)
|
||||
# relay/worker --AMQPS 5671--> broker (RabbitMQ, отдельные пользователи и ACL)
|
||||
# все процессы приложения --OTLP/HTTPS + client cert--> otel-collector --mTLS--> prometheus/loki/tempo
|
||||
# grafana --HTTPS + client cert--> prometheus/loki/tempo; оператор --HTTPS :3000--> grafana
|
||||
# api/relay/worker/janitor/migrate/s3-init/ops --TLS + cert auth--> openbao (KV v2, scoped policy)
|
||||
#
|
||||
# Сети (все internal, кроме frontend и grafana-ui): apinet (lb <-> api), backend (данные),
|
||||
# telemetry, vault (OpenBao только для процессов приложения). LB не видит БД/S3/брокер/OpenBao.
|
||||
# На хост опубликованы ТОЛЬКО 127.0.0.1:8443 (HTTPS API) и 127.0.0.1:3000 (HTTPS Grafana).
|
||||
#
|
||||
# Запуск (подробно — REPORT.md):
|
||||
# ./scripts/init-secrets.sh # пароли, PKI; CA keys -> каталог оператора
|
||||
# ./scripts/bao-init.sh # ОПЕРАТОР: init/unseal OpenBao, policies, cert roles, KV
|
||||
# docker compose --env-file .env up -d --build --wait
|
||||
name: mtusi-lab7
|
||||
|
||||
x-app-image: &app-image
|
||||
image: mtusi-messenger:lab7
|
||||
pull_policy: never
|
||||
|
||||
# Hardening общий для всех сервисов: без повышения привилегий (setuid-бинарники бесполезны).
|
||||
x-sec: &sec
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
|
||||
# Процессы приложения: non-root (uid 10001 из образа), без capabilities, read-only rootfs,
|
||||
# запись только в tmpfs /tmp (upload O_TMPFILE, рабочие файлы worker, heartbeat, instance-id).
|
||||
x-app-sec: &app-sec
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
user: "10001:10001"
|
||||
|
||||
x-otel-env: &otel-env
|
||||
OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
# Lab7: CA для проверки Collector и client cert сервиса (mTLS ingest).
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/internal-ca.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/service.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/service.key
|
||||
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=${APP_ENV:-lab}
|
||||
OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_always_on}
|
||||
OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-1.0}
|
||||
OTEL_METRIC_EXPORT_INTERVAL: ${OTEL_METRIC_EXPORT_INTERVAL:-10000}
|
||||
OTEL_EXPORTER_OTLP_TIMEOUT_SECONDS: ${OTEL_EXPORTER_OTLP_TIMEOUT_SECONDS:-5}
|
||||
OTEL_BSP_MAX_QUEUE_SIZE: ${OTEL_BSP_MAX_QUEUE_SIZE:-2048}
|
||||
OTEL_BLRP_MAX_QUEUE_SIZE: ${OTEL_BLRP_MAX_QUEUE_SIZE:-2048}
|
||||
OTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED: ${OTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED:-true}
|
||||
|
||||
# Секреты сервисов — из OpenBao: cert auth (свой leaf) -> token со scoped policy -> KV v2.
|
||||
x-bao-env: &bao-env
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/secrets/internal-ca.crt
|
||||
BAO_KV_MOUNT: kv
|
||||
BAO_STARTUP_WAIT_SECONDS: ${BAO_STARTUP_WAIT_SECONDS:-300}
|
||||
|
||||
x-db-env: &db-env
|
||||
POSTGRES_HOST: db
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
DB_SSLMODE: verify-full
|
||||
|
||||
x-s3-env: &s3-env
|
||||
S3_ENDPOINT: https://s3:8333
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_CONNECT_TIMEOUT_SECONDS: ${S3_CONNECT_TIMEOUT_SECONDS:-2}
|
||||
S3_READ_TIMEOUT_SECONDS: ${S3_READ_TIMEOUT_SECONDS:-5}
|
||||
|
||||
x-job-env: &job-env
|
||||
PIPELINE_VERSION: ${PIPELINE_VERSION:-1}
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-30}
|
||||
JOB_RETRY_BASE_SECONDS: ${JOB_RETRY_BASE_SECONDS:-2}
|
||||
JOB_RETRY_MAX_SECONDS: ${JOB_RETRY_MAX_SECONDS:-60}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
|
||||
services:
|
||||
# ===================================================================== secrets
|
||||
# OpenBao НЕ в dev-mode: file storage на volume baodata, TLS-listener, после старта sealed.
|
||||
# Init/unseal — оператор (scripts/bao-init.sh, scripts/bao-unseal.sh); unseal shares и root token
|
||||
# лежат в каталоге оператора вне проекта и в контейнер не монтируются.
|
||||
# healthcheck `bao status`: exit 0 только когда initialized + unsealed (sealed -> 2 -> unhealthy).
|
||||
openbao:
|
||||
image: openbao/openbao:2.7.2@sha256:5046911075e137e154ce49ab051502f4ec7cf367d484ae4a4dce665d9b90561f
|
||||
entrypoint: ["bao", "server", "-config=/openbao/config/openbao.hcl"]
|
||||
init: true
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
environment:
|
||||
BAO_ADDR: https://127.0.0.1:8200
|
||||
BAO_CACERT: /run/secrets/internal-ca.crt
|
||||
SKIP_SETCAP: "true"
|
||||
volumes:
|
||||
- baodata:/openbao/file
|
||||
- ./infra/openbao/openbao.hcl:/openbao/config/openbao.hcl:ro
|
||||
tmpfs: ["/tmp:size=16m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: openbao_crt, target: service.crt}
|
||||
- {source: openbao_key, target: service.key}
|
||||
networks: [vault]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "bao", "status"]
|
||||
interval: 5s
|
||||
start_interval: 1s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
|
||||
# ===================================================================== данные
|
||||
# PostgreSQL: ssl=on, pg_hba только hostssl + scram-sha-256 (plaintext reject). Стартовый root
|
||||
# нужен entrypoint-у образа (chown данных, копия ключа TLS с правами 0600), затем uid postgres.
|
||||
db:
|
||||
image: postgres:16.4-alpine@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c
|
||||
entrypoint: ["/bin/sh", "/etc/postgresql/start.sh"]
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID]
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
POSTGRES_INITDB_ARGS: "--auth-local=peer --auth-host=scram-sha-256"
|
||||
secrets:
|
||||
- postgres_password
|
||||
- {source: db_crt, target: service.crt}
|
||||
- {source: db_key, target: service.key}
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
|
||||
- ./infra/postgres/start.sh:/etc/postgresql/start.sh:ro
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
# от имени ОС-пользователя postgres (локальный сокет, peer): под root был бы «Peer authentication failed»
|
||||
test: ["CMD-SHELL", "su-exec postgres pg_isready -q -U postgres -d \"$${POSTGRES_DB}\""]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
stop_grace_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 512M}
|
||||
|
||||
# S3: SeaweedFS, S3 API только HTTPS :8333 (сертификат s3). master/volume/filer — 127.0.0.1
|
||||
# контейнера (закрытый локальный hop, снаружи недостижим).
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:4.50@sha256:c2658820e763294a9e9de7b36c81e59b879e3459148351aee4e31a126ca64860
|
||||
command:
|
||||
- server
|
||||
- -dir=/data
|
||||
- -ip=127.0.0.1
|
||||
- -ip.bind=127.0.0.1
|
||||
- -master.volumeSizeLimitMB=1024
|
||||
- -master.electionTimeout=2s
|
||||
- -volume.preStopSeconds=2
|
||||
- -volume.max=0
|
||||
- -s3
|
||||
- -s3.ip.bind=0.0.0.0
|
||||
- -s3.port=8333
|
||||
- -s3.cert.file=/run/secrets/service.crt
|
||||
- -s3.key.file=/run/secrets/service.key
|
||||
- -s3.config=/run/secrets/s3_identities.json
|
||||
- -s3.iam=false
|
||||
- -s3.port.iceberg=0
|
||||
- -s3.port.lance=0
|
||||
- -s3.concurrentUploadLimitMB=64
|
||||
- -filer.concurrentUploadLimitMB=64
|
||||
- -volume.concurrentUploadLimitMB=64
|
||||
- -s3.cacheCapacityMB=16
|
||||
- -s3.readerCacheSizeMB=32
|
||||
# entrypoint образа: chown /data и su-exec на пользователя seaweed (дальше процесс не root).
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
cap_add: [CHOWN, SETGID, SETUID]
|
||||
secrets:
|
||||
- s3_identities.json
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: s3_crt, target: service.crt}
|
||||
- {source: s3_key, target: service.key}
|
||||
environment:
|
||||
GOMEMLIMIT: 512MiB
|
||||
volumes:
|
||||
- s3data:/data
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -sf -m 2 --cacert /run/secrets/internal-ca.crt https://127.0.0.1:8333/healthz -o /dev/null && curl -sf -m 2 -X PUT --data-binary ok http://127.0.0.1:8888/.healthcheck/probe -o /dev/null"]
|
||||
interval: 5s
|
||||
start_interval: 1s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 60s
|
||||
stop_grace_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 768M}
|
||||
|
||||
# RabbitMQ: только AMQPS 5671 и HTTPS-метрики 15691 (client cert обязателен). Узел rabbit@localhost:
|
||||
# epmd и Erlang distribution слушают только 127.0.0.1 контейнера (кластерного канала нет).
|
||||
broker:
|
||||
image: rabbitmq:4.1.4-alpine@sha256:b736d649308e1b3e1a116c3f36986b605ee3d03e88f10166be2900083d2e63f2
|
||||
hostname: broker
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID]
|
||||
environment:
|
||||
RABBITMQ_NODENAME: rabbit@localhost
|
||||
ERL_EPMD_ADDRESS: 127.0.0.1
|
||||
RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: "-kernel inet_dist_use_interface {127,0,0,1}"
|
||||
volumes:
|
||||
- brokerdata:/var/lib/rabbitmq
|
||||
- ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/conf.d/90-lab7.conf:ro
|
||||
secrets:
|
||||
- {source: rabbitmq_definitions.json, target: rabbitmq_definitions.json}
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: broker_crt, target: service.crt}
|
||||
- {source: broker_key, target: service.key}
|
||||
networks: [backend, telemetry]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "rabbitmq-diagnostics -q check_running && rabbitmq-diagnostics -q check_local_alarms && rabbitmq-diagnostics -q check_port_listener 5671 && rabbitmqctl -q -p messenger list_queues name | grep -q attachments.process.v1"]
|
||||
interval: 10s
|
||||
start_interval: 2s
|
||||
timeout: 15s
|
||||
retries: 5
|
||||
start_period: 60s
|
||||
stop_grace_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 512M}
|
||||
|
||||
# ===================================================================== bootstrap jobs
|
||||
migrate:
|
||||
<<: [*app-image, *app-sec]
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
APP_VERSION: ${APP_VERSION:-1}
|
||||
pull_policy: missing
|
||||
command: ["python", "/app/src/migrate.py"]
|
||||
environment:
|
||||
<<: [*db-env, *bao-env]
|
||||
POSTGRES_USER: postgres
|
||||
# migrate импортирует server.py (STORE/MIGRATIONS_DIR); S3-клиент создаётся, но не используется.
|
||||
S3_ENDPOINT: https://s3:8333
|
||||
S3_CLIENT_REQUIRED: "0"
|
||||
BAO_AUTH_ROLE: migrate
|
||||
BAO_KV_PATH: messenger/migrate
|
||||
tmpfs: ["/tmp:size=8m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: migrate_crt, target: service.crt}
|
||||
- {source: migrate_key, target: service.key}
|
||||
networks: [backend, vault]
|
||||
healthcheck: {disable: true}
|
||||
restart: "no"
|
||||
depends_on:
|
||||
db: {condition: service_healthy}
|
||||
openbao: {condition: service_healthy}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128M}
|
||||
|
||||
s3-init:
|
||||
<<: [*app-image, *app-sec]
|
||||
command: ["python", "/app/src/s3_bootstrap.py"]
|
||||
environment:
|
||||
<<: [*s3-env, *bao-env]
|
||||
BAO_AUTH_ROLE: s3-init
|
||||
BAO_KV_PATH: messenger/s3-init
|
||||
tmpfs: ["/tmp:size=8m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: s3_init_crt, target: service.crt}
|
||||
- {source: s3_init_key, target: service.key}
|
||||
networks: [backend, vault]
|
||||
healthcheck: {disable: true}
|
||||
restart: "no"
|
||||
depends_on:
|
||||
s3: {condition: service_healthy}
|
||||
openbao: {condition: service_healthy}
|
||||
migrate: {condition: service_completed_successfully}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128M}
|
||||
|
||||
# ===================================================================== приложение
|
||||
api:
|
||||
<<: [*app-image, *app-sec]
|
||||
expose: ["8443"]
|
||||
environment:
|
||||
<<: [*db-env, *s3-env, *job-env, *otel-env, *bao-env]
|
||||
POSTGRES_USER: api_svc
|
||||
BAO_AUTH_ROLE: api
|
||||
BAO_KV_PATH: messenger/api
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8443"
|
||||
MTLS_ALLOWED_CLIENTS: lb
|
||||
HEALTH_HOST: 127.0.0.1
|
||||
HEALTH_PORT: "8081"
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456}
|
||||
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2}
|
||||
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1}
|
||||
DB_POOL_SIZE: ${DB_POOL_SIZE:-10}
|
||||
DRAIN_SECONDS: ${DRAIN_SECONDS:-3}
|
||||
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-10}
|
||||
PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-2}
|
||||
PASSWORD_HASH_WAIT_SECONDS: ${PASSWORD_HASH_WAIT_SECONDS:-0.5}
|
||||
DB_HEALTH_INTERVAL_SECONDS: ${DB_HEALTH_INTERVAL_SECONDS:-1}
|
||||
READY_STALE_SECONDS: ${READY_STALE_SECONDS:-3}
|
||||
UPLOAD_TIMEOUT_SECONDS: ${UPLOAD_TIMEOUT_SECONDS:-60}
|
||||
JSON_BODY_TIMEOUT_SECONDS: ${JSON_BODY_TIMEOUT_SECONDS:-10}
|
||||
UPLOAD_CONCURRENCY: ${UPLOAD_CONCURRENCY:-8}
|
||||
DECODE_CONCURRENCY: ${DECODE_CONCURRENCY:-1}
|
||||
JPEG_PROBE_MEMORY_MB: ${JPEG_PROBE_MEMORY_MB:-384}
|
||||
JPEG_PROBE_CPU_SECONDS: ${JPEG_PROBE_CPU_SECONDS:-10}
|
||||
JPEG_PROBE_TIMEOUT_SECONDS: ${JPEG_PROBE_TIMEOUT_SECONDS:-15}
|
||||
S3_PUT_CONCURRENCY: ${S3_PUT_CONCURRENCY:-3}
|
||||
FAULT_INJECTION: ${FAULT_INJECTION:-0}
|
||||
FAULT_SLOW_HANDLER_SECONDS: ${FAULT_SLOW_HANDLER_SECONDS:-1.5}
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
tmpfs: ["/tmp:size=160m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: api_crt, target: service.crt}
|
||||
- {source: api_key, target: service.key}
|
||||
# У API нет доступа к брокеру (задание пишется в outbox PostgreSQL).
|
||||
networks: [apinet, backend, telemetry, vault]
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 20s
|
||||
depends_on:
|
||||
db: {condition: service_healthy}
|
||||
openbao: {condition: service_healthy}
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-init: {condition: service_completed_successfully}
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 640M, pids: 256}
|
||||
|
||||
relay:
|
||||
<<: [*app-image, *app-sec]
|
||||
command: ["python", "/app/src/relay.py"]
|
||||
environment:
|
||||
<<: [*db-env, *job-env, *otel-env, *bao-env]
|
||||
POSTGRES_USER: relay_svc
|
||||
BAO_AUTH_ROLE: relay
|
||||
BAO_KV_PATH: messenger/relay
|
||||
SERVICE_NAME: relay
|
||||
RELAY_POLL_SECONDS: ${RELAY_POLL_SECONDS:-1}
|
||||
REAPER_INTERVAL_SECONDS: ${REAPER_INTERVAL_SECONDS:-5}
|
||||
JOB_REDRIVE_AFTER_SECONDS: ${JOB_REDRIVE_AFTER_SECONDS:-900}
|
||||
OUTBOX_RETENTION_SECONDS: ${OUTBOX_RETENTION_SECONDS:-86400}
|
||||
RELAY_FAULT: ${RELAY_FAULT:-}
|
||||
OTEL_SERVICE_NAME: messenger-relay
|
||||
tmpfs: ["/tmp:size=8m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: relay_crt, target: service.crt}
|
||||
- {source: relay_key, target: service.key}
|
||||
networks: [backend, telemetry, vault]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import os,sys,time; sys.exit(0 if time.time() - os.path.getmtime('/tmp/relay.heartbeat') < 30 else 1)"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 15s
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
broker: {condition: service_healthy}
|
||||
openbao: {condition: service_healthy}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 128M, pids: 64}
|
||||
|
||||
# Upload-worker: ограничен по CPU/RAM (cgroup) и по времени/памяти задания (подпроцесс transform:
|
||||
# RLIMIT_AS/RLIMIT_CPU + JOB_TIMEOUT_SECONDS).
|
||||
worker:
|
||||
<<: [*app-image, *app-sec]
|
||||
command: ["python", "/app/src/worker.py"]
|
||||
environment:
|
||||
<<: [*db-env, *s3-env, *job-env, *otel-env, *bao-env]
|
||||
POSTGRES_USER: worker_svc
|
||||
BAO_AUTH_ROLE: worker
|
||||
BAO_KV_PATH: messenger/worker
|
||||
SERVICE_NAME: worker
|
||||
S3_READ_TIMEOUT_SECONDS: ${WORKER_S3_READ_TIMEOUT_SECONDS:-10}
|
||||
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
|
||||
WORKER_PREFETCH: ${WORKER_PREFETCH:-1}
|
||||
TRANSFORM_MEMORY_LIMIT_MB: ${TRANSFORM_MEMORY_LIMIT_MB:-768}
|
||||
TRANSFORM_CPU_SECONDS: ${TRANSFORM_CPU_SECONDS:-30}
|
||||
WORKER_TMP_DIR: /tmp/work
|
||||
WORKER_FAULT_INJECTION: ${WORKER_FAULT_INJECTION:-0}
|
||||
FAULT_SLOW_SECONDS: ${FAULT_SLOW_SECONDS:-20}
|
||||
OTEL_SERVICE_NAME: messenger-worker
|
||||
tmpfs: ["/tmp:size=96m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: worker_crt, target: service.crt}
|
||||
- {source: worker_key, target: service.key}
|
||||
networks: [backend, telemetry, vault]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import os,sys,time; sys.exit(0 if time.time() - os.path.getmtime('/tmp/worker.heartbeat') < 30 else 1)"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 75s
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-init: {condition: service_completed_successfully}
|
||||
broker: {condition: service_healthy}
|
||||
openbao: {condition: service_healthy}
|
||||
deploy:
|
||||
replicas: ${WORKER_REPLICAS:-2}
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 1G, pids: 128}
|
||||
|
||||
janitor:
|
||||
<<: [*app-image, *app-sec]
|
||||
command: ["python", "/app/src/janitor.py"]
|
||||
environment:
|
||||
<<: [*db-env, *s3-env, *otel-env, *bao-env]
|
||||
POSTGRES_USER: janitor_svc
|
||||
BAO_AUTH_ROLE: janitor
|
||||
BAO_KV_PATH: messenger/janitor
|
||||
ATTACHMENT_GRACE_SECONDS: ${ATTACHMENT_GRACE_SECONDS:-3600}
|
||||
JANITOR_INTERVAL_SECONDS: ${JANITOR_INTERVAL_SECONDS:-300}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
OTEL_SERVICE_NAME: messenger-janitor
|
||||
tmpfs: ["/tmp:size=8m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: janitor_crt, target: service.crt}
|
||||
- {source: janitor_key, target: service.key}
|
||||
networks: [backend, telemetry, vault]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import os,sys,time; sys.exit(0 if time.time() - os.path.getmtime('/tmp/janitor.heartbeat') < 90 else 1)"]
|
||||
interval: 15s
|
||||
timeout: 3s
|
||||
retries: 2
|
||||
start_period: 20s
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-init: {condition: service_completed_successfully}
|
||||
openbao: {condition: service_healthy}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 160M, pids: 64}
|
||||
|
||||
# Ingress: HTTPS :8443 наружу (только 127.0.0.1 хоста), mTLS к API. Не видит БД/S3/OpenBao.
|
||||
lb:
|
||||
image: haproxy:3.0.5-alpine@sha256:43a2591a6a62a41dd22edb4452880e9c70de489fbd7c54ffb52d035cccbfe949
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
environment:
|
||||
LOGIN_RATE_LIMIT: ${LOGIN_RATE_LIMIT:-20}
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: lb_public_pem, target: lb-public.pem}
|
||||
- {source: lb_pem, target: lb.pem}
|
||||
ports:
|
||||
- "127.0.0.1:${LB_PORT:-8443}:8443"
|
||||
networks: [frontend, apinet, telemetry]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "haproxy", "-c", "-q", "-f", "/usr/local/etc/haproxy/haproxy.cfg"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
depends_on:
|
||||
api: {condition: service_started}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128M}
|
||||
|
||||
# Операторский CLI: docker compose --profile tools run --rm ops <команда>
|
||||
ops:
|
||||
<<: [*app-image, *app-sec]
|
||||
profiles: [tools]
|
||||
entrypoint: ["python", "/app/src/ops.py"]
|
||||
environment:
|
||||
<<: [*db-env, *s3-env, *job-env, *bao-env]
|
||||
POSTGRES_USER: ops_svc
|
||||
BAO_AUTH_ROLE: ops
|
||||
BAO_KV_PATH: messenger/ops
|
||||
SERVICE_NAME: ops
|
||||
tmpfs: ["/tmp:size=8m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: ops_crt, target: service.crt}
|
||||
- {source: ops_key, target: service.key}
|
||||
networks: [backend, vault]
|
||||
healthcheck: {disable: true}
|
||||
restart: "no"
|
||||
|
||||
# Проверки ВНУТРИ стенда (отрицательные mTLS/TLS-тесты, права S3, варианты). Только для тестов:
|
||||
# получает тестовые identities (intruder, rogue-lb) и — для положительной проверки mTLS — lb.
|
||||
checks:
|
||||
<<: [*app-image, *app-sec]
|
||||
profiles: [tools]
|
||||
entrypoint: ["python"]
|
||||
environment:
|
||||
<<: *s3-env
|
||||
PYTHONDONTWRITEBYTECODE: "1"
|
||||
tmpfs: ["/tmp:size=64m,mode=1777"]
|
||||
volumes:
|
||||
- ./student-tests:/app/student-tests:ro
|
||||
- ./tests:/app/tests:ro
|
||||
- ./contracts:/app/contracts:ro
|
||||
- ./lab.json:/app/lab.json:ro
|
||||
- ./evidence:/app/evidence
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: public_ca, target: public-ca.crt}
|
||||
- {source: lb_crt, target: lb.crt}
|
||||
- {source: lb_key, target: lb.key}
|
||||
- {source: intruder_crt, target: intruder.crt}
|
||||
- {source: intruder_key, target: intruder.key}
|
||||
- {source: rogue_ca, target: rogue-ca.crt}
|
||||
- {source: rogue_lb_crt, target: rogue-lb.crt}
|
||||
- {source: rogue_lb_key, target: rogue-lb.key}
|
||||
- s3_api_access_key
|
||||
- s3_api_secret_key
|
||||
- s3_worker_access_key
|
||||
- s3_worker_secret_key
|
||||
- s3_janitor_access_key
|
||||
- s3_janitor_secret_key
|
||||
networks: [apinet, backend, telemetry, vault]
|
||||
healthcheck: {disable: true}
|
||||
restart: "no"
|
||||
|
||||
# ===================================================================== телеметрия (lab6 + TLS)
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.163.2@sha256:7f22d2a6748110ffb6a59bc0df448bccbf501cdb667d610ede4c61d3863d5849
|
||||
command: ["--config=/etc/otelcol/collector.yaml"]
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
volumes:
|
||||
- ./infra/otel/collector.yaml:/etc/otelcol/collector.yaml:ro
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: otel_collector_crt, target: service.crt}
|
||||
- {source: otel_collector_key, target: service.key}
|
||||
environment:
|
||||
GOMEMLIMIT: 200MiB
|
||||
networks: [telemetry]
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.13.5@sha256:aafa9d694e6a883c02db516d9f6e5b84e14195f49a2a6456a4cca815edda72b9
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --web.config.file=/etc/prometheus/web.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=15d
|
||||
- --storage.tsdb.retention.size=2GB
|
||||
- --web.enable-otlp-receiver
|
||||
- --enable-feature=exemplar-storage
|
||||
- --web.listen-address=:9090
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
volumes:
|
||||
- ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||
- ./infra/prometheus/web.yml:/etc/prometheus/web.yml:ro
|
||||
- ./infra/prometheus/client.yml:/etc/prometheus/client.yml:ro
|
||||
- ./infra/prometheus/rules:/etc/prometheus/rules:ro
|
||||
- promdata:/prometheus
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: prometheus_crt, target: service.crt}
|
||||
- {source: prometheus_key, target: service.key}
|
||||
networks: [telemetry]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "promtool", "check", "ready", "--url=https://prometheus:9090", "--http.config.file=/etc/prometheus/client.yml"]
|
||||
interval: 10s
|
||||
start_interval: 2s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
loki:
|
||||
image: grafana/loki:3.6.19@sha256:0f9cbc340cbe33ee498e654075034336962057db072f57b37f253e14d476443a
|
||||
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
volumes:
|
||||
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
|
||||
- lokidata:/loki
|
||||
tmpfs: ["/tmp:size=32m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: loki_crt, target: service.crt}
|
||||
- {source: loki_key, target: service.key}
|
||||
networks: [telemetry]
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
tempo:
|
||||
image: grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38
|
||||
command: ["-config.file=/etc/tempo/tempo.yaml"]
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
volumes:
|
||||
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||
- tempodata:/var/tempo
|
||||
tmpfs: ["/tmp:size=32m,mode=1777"]
|
||||
secrets:
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: tempo_crt, target: service.crt}
|
||||
- {source: tempo_key, target: service.key}
|
||||
networks: [telemetry]
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
# Grafana: HTTPS (public-ca) на 127.0.0.1:3000; к datasources — HTTPS + client cert grafana.
|
||||
grafana:
|
||||
image: grafana/grafana:12.4.14@sha256:ae509d9ae8c1021ca32ec370a9ca975d40165eda9fccd1e1102d317ff8787cd7
|
||||
<<: *sec
|
||||
cap_drop: [ALL]
|
||||
environment:
|
||||
GF_SERVER_PROTOCOL: https
|
||||
GF_SERVER_CERT_FILE: /run/secrets/public.crt
|
||||
GF_SERVER_CERT_KEY: /run/secrets/public.key
|
||||
GF_SERVER_MIN_TLS_VERSION: TLS1.2
|
||||
GF_SECURITY_ADMIN_USER: admin
|
||||
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password
|
||||
GF_SECURITY_COOKIE_SECURE: "true"
|
||||
GF_SECURITY_COOKIE_SAMESITE: strict
|
||||
GF_SECURITY_DISABLE_GRAVATAR: "true"
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
GF_AUTH_ANONYMOUS_ENABLED: "false"
|
||||
GF_ANALYTICS_REPORTING_ENABLED: "false"
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
|
||||
GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: "false"
|
||||
GF_NEWS_NEWS_FEED_ENABLED: "false"
|
||||
GF_PLUGINS_PREINSTALL_DISABLED: "true"
|
||||
GF_DASHBOARDS_DEFAULT_HOME_DASHBOARD_PATH: /var/lib/grafana/dashboards/messenger.json
|
||||
secrets:
|
||||
- grafana_admin_password
|
||||
- {source: internal_ca, target: internal-ca.crt}
|
||||
- {source: public_ca, target: public-ca.crt}
|
||||
- {source: grafana_crt, target: service.crt}
|
||||
- {source: grafana_key, target: service.key}
|
||||
- {source: grafana_public_crt, target: public.crt}
|
||||
- {source: grafana_public_key, target: public.key}
|
||||
volumes:
|
||||
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
- grafanadata:/var/lib/grafana
|
||||
ports:
|
||||
- "127.0.0.1:${GRAFANA_PORT:-3000}:3000"
|
||||
networks: [telemetry, grafana-ui]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-sf", "-m", "2", "--cacert", "/run/secrets/public-ca.crt", "https://localhost:3000/api/health", "-o", "/dev/null"]
|
||||
interval: 10s
|
||||
start_interval: 2s
|
||||
timeout: 3s
|
||||
retries: 6
|
||||
start_period: 60s
|
||||
depends_on:
|
||||
prometheus: {condition: service_started}
|
||||
loki: {condition: service_started}
|
||||
tempo: {condition: service_started}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 384M}
|
||||
|
||||
secrets:
|
||||
internal_ca:
|
||||
file: ./secrets/pki/internal-ca.crt
|
||||
public_ca:
|
||||
file: ./secrets/pki/public-ca.crt
|
||||
lb_public_pem:
|
||||
file: ./secrets/pki/lb-public.pem
|
||||
lb_pem:
|
||||
file: ./secrets/pki/lb.pem
|
||||
grafana_public_crt:
|
||||
file: ./secrets/pki/grafana-public.crt
|
||||
grafana_public_key:
|
||||
file: ./secrets/pki/grafana-public.key
|
||||
lb_crt:
|
||||
file: ./secrets/pki/lb.crt
|
||||
lb_key:
|
||||
file: ./secrets/pki/lb.key
|
||||
api_crt:
|
||||
file: ./secrets/pki/api.crt
|
||||
api_key:
|
||||
file: ./secrets/pki/api.key
|
||||
worker_crt:
|
||||
file: ./secrets/pki/worker.crt
|
||||
worker_key:
|
||||
file: ./secrets/pki/worker.key
|
||||
relay_crt:
|
||||
file: ./secrets/pki/relay.crt
|
||||
relay_key:
|
||||
file: ./secrets/pki/relay.key
|
||||
janitor_crt:
|
||||
file: ./secrets/pki/janitor.crt
|
||||
janitor_key:
|
||||
file: ./secrets/pki/janitor.key
|
||||
migrate_crt:
|
||||
file: ./secrets/pki/migrate.crt
|
||||
migrate_key:
|
||||
file: ./secrets/pki/migrate.key
|
||||
s3_init_crt:
|
||||
file: ./secrets/pki/s3-init.crt
|
||||
s3_init_key:
|
||||
file: ./secrets/pki/s3-init.key
|
||||
ops_crt:
|
||||
file: ./secrets/pki/ops.crt
|
||||
ops_key:
|
||||
file: ./secrets/pki/ops.key
|
||||
grafana_crt:
|
||||
file: ./secrets/pki/grafana.crt
|
||||
grafana_key:
|
||||
file: ./secrets/pki/grafana.key
|
||||
db_crt:
|
||||
file: ./secrets/pki/db.crt
|
||||
db_key:
|
||||
file: ./secrets/pki/db.key
|
||||
s3_crt:
|
||||
file: ./secrets/pki/s3.crt
|
||||
s3_key:
|
||||
file: ./secrets/pki/s3.key
|
||||
broker_crt:
|
||||
file: ./secrets/pki/broker.crt
|
||||
broker_key:
|
||||
file: ./secrets/pki/broker.key
|
||||
otel_collector_crt:
|
||||
file: ./secrets/pki/otel-collector.crt
|
||||
otel_collector_key:
|
||||
file: ./secrets/pki/otel-collector.key
|
||||
prometheus_crt:
|
||||
file: ./secrets/pki/prometheus.crt
|
||||
prometheus_key:
|
||||
file: ./secrets/pki/prometheus.key
|
||||
loki_crt:
|
||||
file: ./secrets/pki/loki.crt
|
||||
loki_key:
|
||||
file: ./secrets/pki/loki.key
|
||||
tempo_crt:
|
||||
file: ./secrets/pki/tempo.crt
|
||||
tempo_key:
|
||||
file: ./secrets/pki/tempo.key
|
||||
openbao_crt:
|
||||
file: ./secrets/pki/openbao.crt
|
||||
openbao_key:
|
||||
file: ./secrets/pki/openbao.key
|
||||
# тестовые identities (только сервис checks)
|
||||
intruder_crt:
|
||||
file: ./secrets/pki/test/intruder.crt
|
||||
intruder_key:
|
||||
file: ./secrets/pki/test/intruder.key
|
||||
rogue_ca:
|
||||
file: ./secrets/pki/test/rogue-ca.crt
|
||||
rogue_lb_crt:
|
||||
file: ./secrets/pki/test/rogue-lb.crt
|
||||
rogue_lb_key:
|
||||
file: ./secrets/pki/test/rogue-lb.key
|
||||
# серверная сторона хранилищ и тестовые ключи S3
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
grafana_admin_password:
|
||||
file: ./secrets/grafana_admin_password
|
||||
s3_identities.json:
|
||||
file: ./secrets/s3_identities.json
|
||||
rabbitmq_definitions.json:
|
||||
file: ./secrets/rabbitmq_definitions.json
|
||||
s3_api_access_key:
|
||||
file: ./secrets/s3_api_access_key
|
||||
s3_api_secret_key:
|
||||
file: ./secrets/s3_api_secret_key
|
||||
s3_worker_access_key:
|
||||
file: ./secrets/s3_worker_access_key
|
||||
s3_worker_secret_key:
|
||||
file: ./secrets/s3_worker_secret_key
|
||||
s3_janitor_access_key:
|
||||
file: ./secrets/s3_janitor_access_key
|
||||
s3_janitor_secret_key:
|
||||
file: ./secrets/s3_janitor_secret_key
|
||||
|
||||
networks:
|
||||
frontend: {}
|
||||
apinet:
|
||||
internal: true
|
||||
backend:
|
||||
internal: true
|
||||
telemetry:
|
||||
internal: true
|
||||
vault:
|
||||
internal: true
|
||||
grafana-ui: {}
|
||||
|
||||
volumes:
|
||||
baodata: {}
|
||||
pgdata: {}
|
||||
s3data: {}
|
||||
brokerdata: {}
|
||||
promdata: {}
|
||||
lokidata: {}
|
||||
tempodata: {}
|
||||
grafanadata: {}
|
||||
+40
-20
@@ -1,37 +1,57 @@
|
||||
# Матрица доверия — заполнить в решении lab7
|
||||
# Матрица доверия — решение lab7 (Лазарев Ю. С., БПИ2303)
|
||||
|
||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
||||
Это обязательная матрица покрытия. Для каждой строки указаны реальный порт, endpoint, CA, service identity, проверка SAN/ACL, срок жизни credentials и команда положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
||||
|
||||
**Обозначения.** `public-ca` — CA внешнего ingress (его сертификат раздаётся клиентам: `secrets/pki/public-ca.crt`). `internal-ca` — CA сервисов (mTLS/TLS внутри стенда). Закрытые ключи обоих CA — только в каталоге оператора `$OPERATOR_DIR/ca/` (вне проекта, не монтируются в контейнеры). Leaf-сертификаты: ECDSA P-256, **30 дней**, SAN DNS = имя сервиса Compose (это и есть identity); выпуск — `scripts/init-secrets.sh` → `scripts/pki-issue.sh`. Каждый контейнер получает Docker secret-ами **только свой** `service.crt/service.key` + `internal-ca.crt`.
|
||||
|
||||
Тесты: **M** = `docker compose --profile tools run --rm -T checks /app/student-tests/lab7_tls_matrix.py` (67 проверок, [evidence/lab7-tls-matrix.json](../evidence/lab7-tls-matrix.json)); **A** = `python3 student-tests/lab7_api_security.py` ([evidence/lab7-api-security.json](../evidence/lab7-api-security.json)); **B** = `python3 student-tests/lab7_openbao.py` ([evidence/lab7-openbao.json](../evidence/lab7-openbao.json)); **H** = `python3 student-tests/lab7_hardening.py`; **S** = `make test-security`.
|
||||
|
||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
||||
| --- | --- | --- | --- |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
||||
| Клиент → ingress/LB | **Сделано.** `127.0.0.1:8443` → HAProxy `bind :8443 ssl crt lb-public.pem` (public-ca, SAN `localhost`, `127.0.0.1`), TLS ≥ 1.2, без session tickets, HSTS. Клиент проверяет CA + hostname; пользователь — Bearer (сессия в PostgreSQL, TTL 3600 с, отзыв `DELETE /auth/sessions/current`). Rate limit входа на LB (stick-table, 20/10 с с IP → 429 + `Retry-After: 10`), общий для всех реплик. | Expiry/revocation сессии — проверены (A: `expiry.*`, `logout.*`); общий login rate limit — есть (LB). Ротация leaf ingress — не выполнялась (уровень 4 не заявлен). | Конфиг: [infra/haproxy/haproxy.cfg](../infra/haproxy/haproxy.cfg) `frontend fe_api`. **+** `make test CA_FILE=…/public-ca.crt` (smoke PASS). **−** S: пустой trust store → `SSLCertVerificationError`; A: `tls.wrong_hostname_rejected` (SNI `evil.example` → Hostname mismatch), `tls.internal_ca_does_not_validate_ingress`, `tls.tls11_refused` (alert protocol_version); `ratelimit.login_429_with_retry_after`. |
|
||||
| LB → API (все реплики) | **Сделано: обязательное mTLS + allowlist identity.** HAProxy `server-template api 8 api:8443 ssl verify required ca-file internal-ca.crt verifyhost api crt lb.pem no-ssl-reuse` (LB проверяет SAN `api`, предъявляет identity `lb`). API (`src/server.py`, `src/tlsutil.py`): `CERT_REQUIRED` + internal-ca, затем **SAN DNS клиента ∈ `MTLS_ALLOWED_CLIENTS=lb`**, иначе соединение закрывается до разбора HTTP (событие `mtls.identity_rejected`, метрика `messenger.mtls.rejected`). Без session tickets на API → каждое новое соединение проходит проверку. Health-проверки LB идут тем же mTLS. Порт API наружу не опубликован; сеть `apinet` internal (только lb и api). Health для Docker — plaintext **только 127.0.0.1:8081** внутри контейнера, отдаёт лишь `/health/*`. | Ротация leaf без обхода — не выполнялась. | **+** M: `identity lb -> /health/ready` = 200 для каждой реплики, `identity lb, no Bearer -> business API` = 401 (mTLS не заменяет сессию). **−** M: без client cert → `TLSV13_ALERT_CERTIFICATE_REQUIRED`; cert rogue CA с SAN `lb` → `UNKNOWN_CA`; доверенный CA, identity `intruder` → `closed_after_handshake_no_http_response`; plaintext → reset; `:8081` из сети → refused; ожидание чужого hostname → Hostname mismatch. H: порт API не опубликован. |
|
||||
| API/worker → PostgreSQL | **Сделано.** `db:5432`, `ssl=on`, сертификат `db` (internal-ca); клиенты `sslmode=verify-full sslrootcert=internal-ca.crt`. [pg_hba.conf](../infra/postgres/pg_hba.conf): только `hostssl … scram-sha-256`, `hostnossl … reject`. Раздельные роли: `api_svc`, `worker_svc`, `relay_svc`, `janitor_svc`, `ops_svc` (NOSUPERUSER, NOCREATEROLE, NOCREATEDB, NOBYPASSRLS, CONNECTION LIMIT) с грантами по таблицам ([grants.sql](../migrations/security/grants.sql)); DDL и владение — только `postgres` (job `migrate`). Пароли ролей — из OpenBao (KV), синхронизируются job `migrate`. | Ротация пароля роли — механизм есть (повторный `migrate` выставляет пароль из KV), сценарий не демонстрировался; mTLS к БД — нет. | **+** B/selfcheck: `pg_stat_ssl` = TLSv1.3 у каждой роли; M: `verify-full, internal CA, wrong pwd` → TLS ok, SCRAM отверг пароль. **−** M: `sslmode=disable` → `pg_hba.conf rejects … no encryption`; rogue CA → cert verify failed; подключение по IP → SAN mismatch. B: worker `SELECT users/sessions/messages` → denied; api `CREATE TABLE`/`DROP`/`TRUNCATE`/`UPDATE chats.title` → denied. |
|
||||
| API/worker → S3 | **Сделано.** `https://s3:8333` (SeaweedFS `-s3.cert.file/-s3.key.file`, сертификат `s3`); клиенты minio-py с `cert_reqs=CERT_REQUIRED, ca_certs=internal-ca` (http:// endpoint процесс отвергает). Ключи разные: `api` (Read+Write bucket), `worker` (Read+Write), `janitor` (List+Write, без чтения содержимого), `admin` (только job `s3-init`); приложения получают свои ключи из OpenBao. master/volume/filer SeaweedFS слушают только 127.0.0.1 контейнера (закрытый локальный hop). Bucket приватный. | Права по prefix и ротация ключей — не делались (ограничение по bucket). | **+** smoke (upload/download по HTTPS), M: анонимный list по проверенному TLS → 403. **−** M: plaintext → `400 … HTTPS`; rogue CA → verify failed. B: у worker ключ S3 = ключ `worker` (SHA-префикс), не `admin`/`api`. Конфиг: compose `s3`, `secrets/s3_identities.json` (генерируется init-secrets). |
|
||||
| API/worker → broker | **Сделано (на 3).** RabbitMQ: `listeners.tcp = none`, только AMQPS `broker:5671` (сертификат `broker`, TLS 1.2/1.3), `verify_peer` (предъявленный client cert проверяется), клиенты pika с CA + `server_hostname=broker` и своим client cert. Отдельные пользователи и ACL vhost `messenger`: `relay` — только write в exchange `attachments`; `worker` — только read из `attachments.process.v1`; `ops` — DLQ; ни у кого нет configure. **API к брокеру доступа не имеет** (outbox в PostgreSQL). Erlang distribution/epmd — только 127.0.0.1 (`rabbit@localhost`). | mTLS с обязательным cert и проверкой SAN/роли — не реализовано (уровень 4). | [infra/rabbitmq/rabbitmq.conf](../infra/rabbitmq/rabbitmq.conf). **+** M: AMQPS с проверкой CA → Connection.Start; smoke (worker обработал файл). **−** M: plaintext 5672 → refused; rogue CA trust → verify failed; client cert rogue CA → `UNKNOWN_CA`; `worker` с неверным паролем → auth refused. |
|
||||
| API/worker → Collector | **Сделано: TLS + обязательный client cert (mTLS по CA).** `https://otel-collector:4318` (OTLP/HTTP), `client_ca_file: internal-ca` — без сертификата стенда ingest невозможен; Python SDK: `OTEL_EXPORTER_OTLP_CERTIFICATE/CLIENT_CERTIFICATE/CLIENT_KEY`. OTLP gRPC 4317, метрики 8888 и health 13133 Collector-а — только 127.0.0.1. Сеть `telemetry` internal. | Раздельные identities: сертификаты уже раздельные (SAN = сервис), но **Collector не ограничивает роль** — `intruder` (internal-ca) принят (M фиксирует это как известное ограничение уровня 3). | [infra/otel/collector.yaml](../infra/otel/collector.yaml). **+** `obs_correlation.py` (трасса API→relay→worker, логи в Loki). **−** M: plaintext → 400; без client cert → `CERTIFICATE_REQUIRED`; rogue CA → `UNKNOWN_CA`; `:4317/:8888/:13133` из сети → refused. |
|
||||
| Collector → telemetry backends | **Сделано: mTLS.** Tempo OTLP gRPC `tempo:4317` (`tls.client_ca_file`), Loki `https://loki:3100/otlp`, Prometheus `https://prometheus:9090/api/v1/otlp` (`web.yml`: `RequireAndVerifyClientCert`); Collector проверяет CA + `server_name_override` и предъявляет `otel-collector`. Внутренний gRPC Loki (9095) и Tempo (9096) — 127.0.0.1. Scrape Prometheus → HAProxy `lb:8404`, RabbitMQ `broker:15691`, Loki, Tempo, сам Prometheus — только HTTPS + client cert `prometheus`; собственные метрики Collector идут через его же pipeline (receiver `prometheus/self` с loopback), plaintext scrape убран. | Ротация, least privilege по identity — нет (CA-only). | [infra/prometheus/web.yml](../infra/prometheus/web.yml), [prometheus.yml](../infra/prometheus/prometheus.yml), [loki.yaml](../infra/loki/loki.yaml), [tempo.yaml](../infra/tempo/tempo.yaml). **+** `up` = 1 у всех целей ([evidence/prometheus-up.txt](../evidence/prometheus-up.txt)). **−** M: для prometheus/loki/tempo/tempo-gRPC/lb:8404 — plaintext, без cert, rogue CA, чужой hostname → отказ; broker 15692 из сети → refused, 15691 без cert → отказ. |
|
||||
| Grafana → data sources | **Сделано.** Datasources `https://prometheus:9090`, `https://loki:3100`, `https://tempo:3200`, `tlsAuthWithCACert` (internal-ca), `serverName`, `tlsSkipVerify: false`, client cert `grafana` через `$__file{}` из Docker secret (в Git ключа нет). | Отрицательные проверки доступа по identity — нет (backends CA-only). | [datasources.yaml](../infra/grafana/provisioning/datasources/datasources.yaml). **+** `dashboard_check.py`: datasource health OK ×3, 56 панелей без ошибок. **−** те же M-проверки backend-ов без/с чужим cert. |
|
||||
| API/worker/agent → OpenBao | **Сделано.** `https://openbao:8200` (TLS 1.2+, сертификат `openbao`), сеть `vault` internal (только процессы приложения). Аутентификация — **auth/cert**: роль на сервис (`allowed_dns_sans=<сервис>`, `certificate=internal-ca`), policy `messenger-<сервис>` = `read` только `kv/data/messenger/<сервис>`; токен service, TTL 15 мин, max 1 ч (`migrate`/`s3-init` — 5/10 мин); фоновое renew-self на ½ TTL, при неудаче — повторный login. Root token, unseal shares, `BAO_TOKEN`, SecretID в приложении отсутствуют. | Renewal есть и проверен (`renew_self`=200), revoke-self → 403; expiry/ротация секрета под нагрузкой — не демонстрировались. | [infra/openbao/](../infra/openbao/), [scripts/bao-init.sh](../scripts/bao-init.sh), [src/vault.py](../src/vault.py). **+** B: свой путь 200, policies `default,messenger-<svc>`, TTL ≤ 900. **−** B: чужой сервис / admin-путь `migrate` / list metadata / запись секрета / запись policy / `auth/token/create` / `sys/seal` / list ролей → 403; токен после revoke → 403. M: plaintext → 400, rogue CA → verify failed, login роли `api` с cert `intruder`/`lb`/без cert → 400. |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | **Сделано.** OpenBao — без публикации порта: `docker compose exec openbao bao …` (TLS к 127.0.0.1:8200, root token только в env операторского процесса из `$OPERATOR_DIR/openbao/init.json`). Grafana — `https://localhost:3000` (public-ca), admin/пароль из Docker secret, sign-up и anonymous выключены, cookie secure. S3 admin-ключ — только job `s3-init` (из OpenBao), порт S3 не опубликован. | Отдельная операторская роль/policy вместо root — нет (root у оператора). | H: опубликованы только `127.0.0.1:8443` и `127.0.0.1:3000`. Healthcheck Grafana `curl --cacert public-ca https://localhost:3000/api/health`. |
|
||||
| API → Redis/Valkey, если используется | **N/A** — Redis/Valkey в lab7 не используется: сессии и ключи идемпотентности хранятся в PostgreSQL, rate limit входа — в stick-table HAProxy. | — | compose.yaml: сервиса нет. |
|
||||
| Replication/кластерные каналы, если добавлены | **N/A по составу** — репликации нет (один узел PostgreSQL, RabbitMQ, SeaweedFS, OpenBao Raft). Кластерные слушатели, которые продукты открывают сами, ограничены loopback: OpenBao `cluster_address 127.0.0.1:8201`; RabbitMQ epmd/Erlang dist на 127.0.0.1; SeaweedFS master/volume/filer `-ip.bind=127.0.0.1`; gRPC Loki/Tempo 127.0.0.1. | Модель отказа узла не заявляется (один Docker-host). | M: `internal-only port … from network` → refused. |
|
||||
|
||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||
|
||||
### Scrape / health / bootstrap каналы
|
||||
|
||||
| Канал | Как защищён | Проверка |
|
||||
| --- | --- | --- |
|
||||
| Docker healthcheck API/worker/relay/janitor | API: plaintext **только 127.0.0.1:8081** внутри контейнера, только `/health/live|ready` (остальное 404); worker/relay/janitor — файл heartbeat в tmpfs, без сети | M: `health listener 8081 from network` → refused |
|
||||
| HAProxy → API readiness | тот же mTLS, что и трафик (`check` наследует `ssl verify required … crt lb.pem`) | M: identity `lb` → 200 |
|
||||
| Healthchecks остальных | локально в контейнере: `bao status` (TLS 127.0.0.1), `su-exec postgres pg_isready` (сокет, peer), `curl --cacert … https://127.0.0.1:8333` (S3), `rabbitmq-diagnostics` (loopback dist), `promtool check ready --http.config.file` (mTLS), `curl --cacert public-ca https://localhost:3000` (Grafana) | compose.yaml |
|
||||
| Prometheus scrape | только HTTPS + client cert `prometheus`, проверка CA и `server_name` цели | `up`=1 у всех целей; M — отказ без cert |
|
||||
| Bootstrap PKI | `init-secrets.sh` локально, OpenSSL закреплённого образа, `--network none`; CA keys → `$OPERATOR_DIR` | H: `repo.scan_secrets_clean`, `image.no_key_or_secret_files` |
|
||||
| Bootstrap OpenBao | `bao-init.sh` оператором: init/unseal/policies/roles/KV через `docker compose exec` (stdin, без вывода значений) | B: `status.*` |
|
||||
| Bootstrap БД/S3 | job `migrate` (роль `postgres`, TLS verify-full, KV `messenger/migrate`, токен 5 мин), job `s3-init` (ключ admin, KV `messenger/s3-init`) — завершаются (Exited 0) | `docker compose ps -a` |
|
||||
|
||||
## Обязательные отрицательные проверки
|
||||
|
||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
|
||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
|
||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». — **S + A (`tls.*`)**.
|
||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. — **M (`LB->API[0..1]`)**, для каждой реплики.
|
||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. — уровень 4 не заявлен; для broker и Collector выполнены проверки «без cert / чужой CA», identity-уровень — нет (M фиксирует `intruder` как принятый Collector-ом).
|
||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. — **A (`outsider.*`, `spoof.*`)**.
|
||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. — **B**.
|
||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. — уровень 4 не заявлен; подготовлено: на API и HAProxy отключены session tickets/кэш TLS-сессий (`OP_NO_TICKET`, `no-tls-tickets`, `tune.ssl.cachesize 0`, `no-ssl-reuse`), revoke-self токена OpenBao проверен (B).
|
||||
|
||||
## Bootstrap и эксплуатация
|
||||
|
||||
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
|
||||
|
||||
**Решение:** CA keys и `openbao/init.json` (root token + 3 unseal shares, порог 2) — в `$OPERATOR_DIR` (700/600) у оператора, ни в один контейнер не монтируются. Leaf keys — в `secrets/pki` (каталог 700, вне Git и образа), каждый контейнер видит только свой ключ. После рестарта контейнера OpenBao он **sealed**: работающие API/worker продолжают обслуживать запросы (секреты уже в памяти), новые/перезапущенные процессы ждут (не становятся ready), оператор выполняет `./scripts/bao-unseal.sh` (2 из 3 shares через stdin). Обычный рестарт API unseal не требует. Подробно — [infra/openbao/README.md](../infra/openbao/README.md).
|
||||
|
||||
OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии.
|
||||
|
||||
**Решение:** non-dev, integrated storage **Raft** (file storage в OpenBao 2.7 удалён) на volume `baodata`; **cert auth** (identity = тот же leaf-сертификат, что и для mTLS, без отдельного SecretID); токены service-типа с policy, TTL 15 мин / max 1 ч, renew-self и re-login; статические KV v2 secrets.
|
||||
|
||||
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
|
||||
|
||||
@@ -3,3 +3,24 @@
|
||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
||||
|
||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
||||
|
||||
## Lab7 — состав (2026-11-18, MacBook Air M3, Docker Desktop 28.0.4, VM 8 vCPU / 7.7 GiB)
|
||||
|
||||
| Файл | Что | Команда |
|
||||
| --- | --- | --- |
|
||||
| run-all.txt | сводный прогон всех проверок | `WITH_LAB6=1 ./student-tests/run_all.sh` |
|
||||
| clean-clone-run.txt | тот же прогон из чистой копии репозитория со свежими секретами/PKI/OpenBao | см. REPORT.md «Доказательства» |
|
||||
| make-*.txt | `make check`, HTTPS smoke, внешний TLS trust | run_all |
|
||||
| lab7-tls-matrix.json/.txt | 67 положительных/отрицательных TLS/mTLS проверок изнутри стенда | `checks lab7_tls_matrix.py` |
|
||||
| lab7-api-security.json/.txt | 33 проверки внешнего API (TLS, ACL, logout/expiry, rate limit, лимиты, Argon2id) | `lab7_api_security.py` |
|
||||
| lab7-openbao.json/.txt | 83 проверки OpenBao (статус, policies allow/deny, sealed-сценарий) | `lab7_openbao.py` |
|
||||
| lab7-hardening.json/.txt | 182 проверки docker inspect / образа / репозитория / телеметрии | `lab7_hardening.py` |
|
||||
| argon2-bench.json | замер профилей Argon2id в контейнере API | `argon2_bench.py` |
|
||||
| test-persistence.txt, persistence-ps-*.txt | рестарт всех хранилищ (вкл. OpenBao + unseal), состояния до/после | `make test-persistence` |
|
||||
| test-failover.txt | последовательная остановка api-1 и api-2 с alias-ами реплик | `make test-failover` |
|
||||
| load*.json | нагрузка POST по HTTPS (до/после TCP_NODELAY) | `tests/load.py` |
|
||||
| prometheus-up.txt | все scrape-цели `up=1` по HTTPS + client cert | obslib |
|
||||
| obs-correlation.json, dashboard-check.json, worker-outage.txt | регрессии lab5/lab6 поверх TLS | run_all `WITH_LAB6=1` |
|
||||
|
||||
Токены, пароли, ключи и unseal material в evidence не сохраняются (тесты печатают только статусы,
|
||||
имена полей и SHA-256-префиксы).
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
{
|
||||
"measured_at": "2026-11-18T20:02:28Z",
|
||||
"python": "3.12.7",
|
||||
"machine": "aarch64",
|
||||
"cgroup_cpu_limit": 0.5,
|
||||
"cgroup_memory_limit_mib": 640,
|
||||
"n_per_profile": 15,
|
||||
"profiles": [
|
||||
{
|
||||
"name": "owasp-min m=19MiB t=2 p=1 (выбран)",
|
||||
"memory_kib": 19456,
|
||||
"iterations": 2,
|
||||
"parallelism": 1,
|
||||
"hash_ms": {
|
||||
"p50": 13.0,
|
||||
"p95": 64.8,
|
||||
"max": 65.7
|
||||
},
|
||||
"verify_ms": {
|
||||
"p50": 13.2,
|
||||
"p95": 63.2
|
||||
},
|
||||
"max_rss_growth_mib": 18.2,
|
||||
"concurrency2_hashes_per_s": 27.2,
|
||||
"sample_prefix": [
|
||||
"argon2id",
|
||||
"v=19",
|
||||
"m=19456,t=2,p=1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "owasp-alt m=46MiB t=1 p=1",
|
||||
"memory_kib": 47104,
|
||||
"iterations": 1,
|
||||
"parallelism": 1,
|
||||
"hash_ms": {
|
||||
"p50": 21.6,
|
||||
"p95": 71.3,
|
||||
"max": 71.5
|
||||
},
|
||||
"verify_ms": {
|
||||
"p50": 21.6,
|
||||
"p95": 78.6
|
||||
},
|
||||
"max_rss_growth_mib": 46.0,
|
||||
"concurrency2_hashes_per_s": 14.4,
|
||||
"sample_prefix": [
|
||||
"argon2id",
|
||||
"v=19",
|
||||
"m=47104,t=1,p=1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "m=19MiB t=3 p=1",
|
||||
"memory_kib": 19456,
|
||||
"iterations": 3,
|
||||
"parallelism": 1,
|
||||
"hash_ms": {
|
||||
"p50": 23.4,
|
||||
"p95": 108.6,
|
||||
"max": 183.1
|
||||
},
|
||||
"verify_ms": {
|
||||
"p50": 69.7,
|
||||
"p95": 105.5
|
||||
},
|
||||
"max_rss_growth_mib": 0.0,
|
||||
"concurrency2_hashes_per_s": 16.6,
|
||||
"sample_prefix": [
|
||||
"argon2id",
|
||||
"v=19",
|
||||
"m=19456,t=3,p=1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "m=64MiB t=3 p=1",
|
||||
"memory_kib": 65536,
|
||||
"iterations": 3,
|
||||
"parallelism": 1,
|
||||
"hash_ms": {
|
||||
"p50": 186.4,
|
||||
"p95": 207.8,
|
||||
"max": 303.9
|
||||
},
|
||||
"verify_ms": {
|
||||
"p50": 183.9,
|
||||
"p95": 212.8
|
||||
},
|
||||
"max_rss_growth_mib": 0.0,
|
||||
"concurrency2_hashes_per_s": 3.7,
|
||||
"sample_prefix": [
|
||||
"argon2id",
|
||||
"v=19",
|
||||
"m=65536,t=3,p=1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "m=19MiB t=2 p=2",
|
||||
"memory_kib": 19456,
|
||||
"iterations": 2,
|
||||
"parallelism": 2,
|
||||
"hash_ms": {
|
||||
"p50": 8.0,
|
||||
"p95": 80.8,
|
||||
"max": 83.2
|
||||
},
|
||||
"verify_ms": {
|
||||
"p50": 15.9,
|
||||
"p95": 92.4
|
||||
},
|
||||
"max_rss_growth_mib": 0.0,
|
||||
"concurrency2_hashes_per_s": 15.0,
|
||||
"sample_prefix": [
|
||||
"argon2id",
|
||||
"v=19",
|
||||
"m=19456,t=2,p=2"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
== promtool check config (prom/prometheus:v3.13.5@sha256:aafa9d694e6a883c02db516d9f6e5b84e14195f49a2a6456a4cca815edda72b9)
|
||||
Checking /etc/prometheus/prometheus.yml
|
||||
SUCCESS: 1 rule files found
|
||||
SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax
|
||||
|
||||
Checking /etc/prometheus/rules/messenger.yml
|
||||
SUCCESS: 26 rules found
|
||||
|
||||
== promtool check web-config (TLS + обязательный client cert)
|
||||
/etc/prometheus/web.yml SUCCESS
|
||||
== promtool test rules
|
||||
SUCCESS
|
||||
|
||||
== otelcol validate (otel/opentelemetry-collector-contrib:0.163.2@sha256:7f22d2a6748110ffb6a59bc0df448bccbf501cdb667d610ede4c61d3863d5849)
|
||||
collector config OK
|
||||
== loki -verify-config (grafana/loki:3.6.19@sha256:0f9cbc340cbe33ee498e654075034336962057db072f57b37f253e14d476443a)
|
||||
loki config OK
|
||||
== dashboard JSON is up to date with scripts/build_dashboard.py
|
||||
dashboard OK
|
||||
@@ -0,0 +1,88 @@
|
||||
# Прогон из чистой копии репозитория (без secrets/, .env, материала оператора), 2026-11-18
|
||||
# COMPOSE_PROJECT_NAME=mtusi-lab7-clean, отдельный OPERATOR_DIR; init-secrets -> check_rules -> build --no-cache -> bao-init -> up --wait -> WITH_LAB6=1 run_all.sh
|
||||
created CA public-ca (key in operator dir)
|
||||
created CA internal-ca (key in operator dir)
|
||||
issued lb-public (public-ca, 30 days)
|
||||
issued grafana-public (public-ca, 30 days)
|
||||
issued lb (internal-ca, 30 days)
|
||||
issued api (internal-ca, 30 days)
|
||||
issued worker (internal-ca, 30 days)
|
||||
issued relay (internal-ca, 30 days)
|
||||
issued janitor (internal-ca, 30 days)
|
||||
issued migrate (internal-ca, 30 days)
|
||||
issued s3-init (internal-ca, 30 days)
|
||||
issued ops (internal-ca, 30 days)
|
||||
issued grafana (internal-ca, 30 days)
|
||||
issued db (internal-ca, 30 days)
|
||||
issued s3 (internal-ca, 30 days)
|
||||
issued broker (internal-ca, 30 days)
|
||||
issued otel-collector (internal-ca, 30 days)
|
||||
issued prometheus (internal-ca, 30 days)
|
||||
issued loki (internal-ca, 30 days)
|
||||
issued tempo (internal-ca, 30 days)
|
||||
issued openbao (internal-ca, 30 days)
|
||||
issued intruder (internal-ca, 30 days)
|
||||
issued rogue-lb (rogue-ca, 30 days)
|
||||
== promtool check config (prom/prometheus:v3.13.5@sha256:aafa9d694e6a883c02db516d9f6e5b84e14195f49a2a6456a4cca815edda72b9)
|
||||
== promtool check web-config (TLS + обязательный client cert)
|
||||
== promtool test rules
|
||||
== otelcol validate (otel/opentelemetry-collector-contrib:0.163.2@sha256:7f22d2a6748110ffb6a59bc0df448bccbf501cdb667d610ede4c61d3863d5849)
|
||||
== loki -verify-config (grafana/loki:3.6.19@sha256:0f9cbc340cbe33ee498e654075034336962057db072f57b37f253e14d476443a)
|
||||
== dashboard JSON is up to date with scripts/build_dashboard.py
|
||||
openbao initialized; root token and 3 unseal shares saved to <scratch>/clean/operator/openbao/init.json (operator only)
|
||||
openbao unsealed (2 of 3 shares)
|
||||
openbao configured: kv v2 'kv/', audit file->stdout, auth/cert roles: api worker relay janitor migrate s3-init ops
|
||||
Container mtusi-lab7-clean-migrate-1 Exited
|
||||
Container mtusi-lab7-clean-migrate-1 Exited
|
||||
Container mtusi-lab7-clean-migrate-1 Exited
|
||||
Container mtusi-lab7-clean-migrate-1 Exited
|
||||
Container mtusi-lab7-clean-migrate-1 Exited
|
||||
Container mtusi-lab7-clean-s3-init-1 Exited
|
||||
Container mtusi-lab7-clean-s3-init-1 Exited
|
||||
Container mtusi-lab7-clean-s3-init-1 Exited
|
||||
Container mtusi-lab7-clean-migrate-1 Exited
|
||||
Container mtusi-lab7-clean-s3-init-1 Exited
|
||||
mtusi-lab7-clean-api-1 Up 11 seconds (healthy)
|
||||
mtusi-lab7-clean-api-2 Up 11 seconds (healthy)
|
||||
mtusi-lab7-clean-broker-1 Up 31 seconds (healthy)
|
||||
mtusi-lab7-clean-db-1 Up 31 seconds (healthy)
|
||||
mtusi-lab7-clean-grafana-1 Up 30 seconds (healthy)
|
||||
mtusi-lab7-clean-janitor-1 Up 11 seconds (healthy)
|
||||
mtusi-lab7-clean-lb-1 Up 10 seconds (healthy)
|
||||
mtusi-lab7-clean-migrate-1 Exited (0) 27 seconds ago
|
||||
mtusi-lab7-clean-openbao-1 Up 48 seconds (healthy)
|
||||
mtusi-lab7-clean-prometheus-1 Up 31 seconds (healthy)
|
||||
mtusi-lab7-clean-relay-1 Up 23 seconds (healthy)
|
||||
mtusi-lab7-clean-s3-1 Up 31 seconds (healthy)
|
||||
mtusi-lab7-clean-s3-init-1 Exited (0) 11 seconds ago
|
||||
mtusi-lab7-clean-worker-1 Up 11 seconds (healthy)
|
||||
mtusi-lab7-clean-worker-2 Up 11 seconds (healthy)
|
||||
== make-check (2026-11-18T20:51:58Z)
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
== make-test (2026-11-18T20:51:58Z)
|
||||
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||
== make-test-security (2026-11-18T20:51:59Z)
|
||||
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||
== lab7-tls-matrix (2026-11-18T20:51:59Z)
|
||||
PASS: 67 checks, 0 failed
|
||||
== lab7-api-security (2026-11-18T20:52:00Z)
|
||||
PASS: 33 checks, 0 failed
|
||||
== lab7-openbao (2026-11-18T20:52:36Z)
|
||||
PASS: 83 checks, 0 failed
|
||||
== lab7-hardening (2026-11-18T20:53:23Z)
|
||||
PASS: 182 checks, 0 failed
|
||||
== test-persistence (2026-11-18T20:53:44Z)
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
== test-failover (2026-11-18T20:54:33Z)
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
== load (2026-11-18T20:54:56Z)
|
||||
== scan-secrets (2026-11-18T20:55:26Z)
|
||||
== check-rules (2026-11-18T20:55:26Z)
|
||||
== obs-correlation (2026-11-18T20:55:29Z)
|
||||
PASS: correlation request->trace->log and upload->relay->worker
|
||||
== dashboard-check (2026-11-18T20:55:39Z)
|
||||
== worker-outage (2026-11-18T20:56:20Z)
|
||||
PASS: worker outage, api+broker restart, ready, duplicate delivery no-op
|
||||
== done: ALL PASS
|
||||
+(eval):1> echo 'CLEAN_EXIT=0'
|
||||
CLEAN_EXIT=0
|
||||
@@ -0,0 +1,598 @@
|
||||
{
|
||||
"dashboard": {
|
||||
"uid": "messenger-overview",
|
||||
"title": "Messenger — наблюдаемость (lab6)",
|
||||
"provisioned": true,
|
||||
"folder": "Messenger",
|
||||
"panels": 56
|
||||
},
|
||||
"datasources": [
|
||||
"loki",
|
||||
"prometheus",
|
||||
"tempo"
|
||||
],
|
||||
"datasource_health": {
|
||||
"prometheus": "OK",
|
||||
"loki": "OK",
|
||||
"tempo": "OK"
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"panel": "RPS бизнес-запросов",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "5xx, доля (2m)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "p95 API (5m)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "SLO доступности, 7d",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Остаток error budget, 7d",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Time to ready p95",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Ready lag очереди",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Alerts firing",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "История alerts (pending/firing -> resolved)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "RPS по маршруту",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 10,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Ответы по классу статуса",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Доля 5xx: API и LB",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Доля 5xx: API и LB",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Задержка API p50/p95/p99 (из histogram)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Задержка API p50/p95/p99 (из histogram)",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Задержка API p50/p95/p99 (из histogram)",
|
||||
"ref": "C",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "p95 по маршруту",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 10,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "5xx по причине (error.type)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Запросы в обработке (saturation API)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 6,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "HAProxy: UP-реплики и очередь LB",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "HAProxy: UP-реплики и очередь LB",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Задания по исходу (в минуту)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Длительность обработки job p50/p95/p99",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Длительность обработки job p50/p95/p99",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Длительность обработки job p50/p95/p99",
|
||||
"ref": "C",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Time to ready p50/p95/p99",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Time to ready p50/p95/p99",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Time to ready p50/p95/p99",
|
||||
"ref": "C",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Глубина очереди: PostgreSQL и RabbitMQ",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 2,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Глубина очереди: PostgreSQL и RabbitMQ",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Глубина очереди: PostgreSQL и RabbitMQ",
|
||||
"ref": "C",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Глубина очереди: PostgreSQL и RabbitMQ",
|
||||
"ref": "D",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Глубина очереди: PostgreSQL и RabbitMQ",
|
||||
"ref": "E",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Возраст старейшего задания и lag",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 2,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Возраст старейшего задания и lag",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Возраст старейшего задания и lag",
|
||||
"ref": "C",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Ожидание в очереди p95 (до claim)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Ожидание в очереди p95 (до claim)",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Saturation worker: занятость потребителей",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Saturation worker: занятость потребителей",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Relay: публикации outbox",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Пул соединений API: used / idle / max",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 12,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Пул соединений API: used / idle / max",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Ожидающие соединение и таймауты пула",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 6,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Ожидающие соединение и таймауты пула",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 2,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Ожидание соединения пула p95",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Операции БД p95 по операции (API)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 12,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Операции БД worker/relay p95",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 5,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Ошибки операций БД",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "S3 p95 по операции",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 4,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "S3 ошибки",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "CPU, ядер (cgroup контейнера)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 6,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "CPU saturation: доля лимита",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 6,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Память контейнеров приложений",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 14,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Память: доля лимита",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 14,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Память telemetry-стека (RSS)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 3,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Память telemetry-стека (RSS)",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 2,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Память telemetry-стека (RSS)",
|
||||
"ref": "C",
|
||||
"datasource": "prometheus",
|
||||
"series": 2,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Память telemetry-стека (RSS)",
|
||||
"ref": "D",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "CPU telemetry-стека",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 3,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "CPU telemetry-стека",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: принято / отправлено / потеряно (spans)",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: принято / отправлено / потеряно (spans)",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: принято / отправлено / потеряно (spans)",
|
||||
"ref": "C",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: принято / отправлено / потеряно (spans)",
|
||||
"ref": "D",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: принято / отправлено / потеряно (spans)",
|
||||
"ref": "E",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: логи",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: логи",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: логи",
|
||||
"ref": "C",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: логи",
|
||||
"ref": "D",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: очередь экспортёров",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 3,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Collector: очередь экспортёров",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 3,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "SDK приложений: потери на стороне процесса",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "SDK приложений: потери на стороне процесса",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "SDK приложений: потери на стороне процесса",
|
||||
"ref": "C",
|
||||
"datasource": "prometheus",
|
||||
"series": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "SDK: заполнение очереди BatchSpanProcessor",
|
||||
"ref": "A",
|
||||
"datasource": "prometheus",
|
||||
"series": 14,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "SDK: заполнение очереди BatchSpanProcessor",
|
||||
"ref": "B",
|
||||
"datasource": "prometheus",
|
||||
"series": 1,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Логи WARN/ERROR приложений (Loki)",
|
||||
"ref": "A",
|
||||
"datasource": "loki",
|
||||
"lines": 20,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "HTTP 5xx (event=http.request)",
|
||||
"ref": "A",
|
||||
"datasource": "loki",
|
||||
"lines": 20,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Последние трассы обработки заданий (Tempo)",
|
||||
"ref": "A",
|
||||
"datasource": "tempo",
|
||||
"traces": 5,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Медленные запросы API > 1 s (Tempo)",
|
||||
"ref": "A",
|
||||
"datasource": "tempo",
|
||||
"traces": 0,
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"panel": "Трассы с ошибкой (Tempo)",
|
||||
"ref": "A",
|
||||
"datasource": "tempo",
|
||||
"traces": 5,
|
||||
"ok": true
|
||||
}
|
||||
],
|
||||
"query_errors": [],
|
||||
"empty_required_panels": [],
|
||||
"pass": true
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
warmup: {'requests': 564, 'ok': 564, 'codes': {'200': 242, '201': 242, '202': 80}, 'error_ratio_5xx': 0.0, 'ok_rps': 14.1, 'p50_ms': 11.3, 'p95_ms': 26.6, 'p99_ms': 43.7}
|
||||
ok RPS бизнес-запросов prometheus 1
|
||||
ok 5xx, доля (2m) prometheus 1
|
||||
ok p95 API (5m) prometheus 1
|
||||
ok SLO доступности, 7d prometheus 1
|
||||
ok Остаток error budget, 7d prometheus 1
|
||||
ok Time to ready p95 prometheus 1
|
||||
ok Ready lag очереди prometheus 1
|
||||
ok Alerts firing prometheus 1
|
||||
ok История alerts (pending/firing -> resolved) prometheus 0
|
||||
ok RPS по маршруту prometheus 10
|
||||
ok Ответы по классу статуса prometheus 1
|
||||
ok Доля 5xx: API и LB prometheus 1
|
||||
ok Доля 5xx: API и LB prometheus 1
|
||||
ok Задержка API p50/p95/p99 (из histogram) prometheus 1
|
||||
ok Задержка API p50/p95/p99 (из histogram) prometheus 1
|
||||
ok Задержка API p50/p95/p99 (из histogram) prometheus 1
|
||||
ok p95 по маршруту prometheus 10
|
||||
ok 5xx по причине (error.type) prometheus 0
|
||||
ok Запросы в обработке (saturation API) prometheus 6
|
||||
ok HAProxy: UP-реплики и очередь LB prometheus 1
|
||||
ok HAProxy: UP-реплики и очередь LB prometheus 1
|
||||
ok Задания по исходу (в минуту) prometheus 1
|
||||
ok Длительность обработки job p50/p95/p99 prometheus 1
|
||||
ok Длительность обработки job p50/p95/p99 prometheus 1
|
||||
ok Длительность обработки job p50/p95/p99 prometheus 1
|
||||
ok Time to ready p50/p95/p99 prometheus 1
|
||||
ok Time to ready p50/p95/p99 prometheus 1
|
||||
ok Time to ready p50/p95/p99 prometheus 1
|
||||
ok Глубина очереди: PostgreSQL и RabbitMQ prometheus 2
|
||||
ok Глубина очереди: PostgreSQL и RabbitMQ prometheus 1
|
||||
ok Глубина очереди: PostgreSQL и RabbitMQ prometheus 1
|
||||
ok Глубина очереди: PostgreSQL и RabbitMQ prometheus 1
|
||||
ok Глубина очереди: PostgreSQL и RabbitMQ prometheus 1
|
||||
ok Возраст старейшего задания и lag prometheus 2
|
||||
ok Возраст старейшего задания и lag prometheus 1
|
||||
ok Возраст старейшего задания и lag prometheus 1
|
||||
ok Ожидание в очереди p95 (до claim) prometheus 1
|
||||
ok Ожидание в очереди p95 (до claim) prometheus 1
|
||||
ok Saturation worker: занятость потребителей prometheus 1
|
||||
ok Saturation worker: занятость потребителей prometheus 1
|
||||
ok Relay: публикации outbox prometheus 1
|
||||
ok Пул соединений API: used / idle / max prometheus 12
|
||||
ok Пул соединений API: used / idle / max prometheus 1
|
||||
ok Ожидающие соединение и таймауты пула prometheus 6
|
||||
ok Ожидающие соединение и таймауты пула prometheus 2
|
||||
ok Ожидание соединения пула p95 prometheus 1
|
||||
ok Операции БД p95 по операции (API) prometheus 12
|
||||
ok Операции БД worker/relay p95 prometheus 5
|
||||
ok Ошибки операций БД prometheus 0
|
||||
ok S3 p95 по операции prometheus 4
|
||||
ok S3 ошибки prometheus 0
|
||||
ok CPU, ядер (cgroup контейнера) prometheus 6
|
||||
ok CPU saturation: доля лимита prometheus 6
|
||||
ok Память контейнеров приложений prometheus 14
|
||||
ok Память: доля лимита prometheus 14
|
||||
ok Память telemetry-стека (RSS) prometheus 3
|
||||
ok Память telemetry-стека (RSS) prometheus 2
|
||||
ok Память telemetry-стека (RSS) prometheus 2
|
||||
ok Память telemetry-стека (RSS) prometheus 1
|
||||
ok CPU telemetry-стека prometheus 3
|
||||
ok CPU telemetry-стека prometheus 1
|
||||
ok Collector: принято / отправлено / потеряно (spans) prometheus 1
|
||||
ok Collector: принято / отправлено / потеряно (spans) prometheus 1
|
||||
ok Collector: принято / отправлено / потеряно (spans) prometheus 0
|
||||
ok Collector: принято / отправлено / потеряно (spans) prometheus 0
|
||||
ok Collector: принято / отправлено / потеряно (spans) prometheus 1
|
||||
ok Collector: логи prometheus 1
|
||||
ok Collector: логи prometheus 1
|
||||
ok Collector: логи prometheus 0
|
||||
ok Collector: логи prometheus 0
|
||||
ok Collector: очередь экспортёров prometheus 3
|
||||
ok Collector: очередь экспортёров prometheus 3
|
||||
ok SDK приложений: потери на стороне процесса prometheus 0
|
||||
ok SDK приложений: потери на стороне процесса prometheus 0
|
||||
ok SDK приложений: потери на стороне процесса prometheus 0
|
||||
ok SDK: заполнение очереди BatchSpanProcessor prometheus 14
|
||||
ok SDK: заполнение очереди BatchSpanProcessor prometheus 1
|
||||
ok Логи WARN/ERROR приложений (Loki) loki 20
|
||||
ok HTTP 5xx (event=http.request) loki 20
|
||||
ok Последние трассы обработки заданий (Tempo) tempo 5
|
||||
ok Медленные запросы API > 1 s (Tempo) tempo 0
|
||||
ok Трассы с ошибкой (Tempo) tempo 5
|
||||
{"dashboard": {"uid": "messenger-overview", "title": "Messenger — наблюдаемость (lab6)", "provisioned": true, "folder": "Messenger", "panels": 56}, "datasource_health": {"prometheus": "OK", "loki": "OK", "tempo": "OK"}, "query_errors": [], "empty_required_panels": [], "pass": true}
|
||||
@@ -0,0 +1,173 @@
|
||||
{
|
||||
"checked_at": "2026-11-18T20:27:20Z",
|
||||
"base_url": "https://localhost:8443",
|
||||
"total": 33,
|
||||
"failed": 0,
|
||||
"results": [
|
||||
{
|
||||
"check": "tls.trusted_ca_and_hostname",
|
||||
"pass": true,
|
||||
"detail": "TLSv1.3"
|
||||
},
|
||||
{
|
||||
"check": "tls.wrong_hostname_rejected",
|
||||
"pass": true,
|
||||
"detail": "Hostname mismatch, certificate is not valid for 'evil.example'."
|
||||
},
|
||||
{
|
||||
"check": "tls.internal_ca_does_not_validate_ingress",
|
||||
"pass": true,
|
||||
"detail": "unable to get local issuer certificate"
|
||||
},
|
||||
{
|
||||
"check": "tls.tls11_refused",
|
||||
"pass": true,
|
||||
"detail": "tls_error TLSV1_ALERT_PROTOCOL_VERSION"
|
||||
},
|
||||
{
|
||||
"check": "setup.attachment_ready",
|
||||
"pass": true,
|
||||
"detail": "ready"
|
||||
},
|
||||
{
|
||||
"check": "outsider.chat_404",
|
||||
"pass": true,
|
||||
"detail": "404"
|
||||
},
|
||||
{
|
||||
"check": "outsider.history_404",
|
||||
"pass": true,
|
||||
"detail": "404"
|
||||
},
|
||||
{
|
||||
"check": "outsider.attachment_metadata_404",
|
||||
"pass": true,
|
||||
"detail": "404"
|
||||
},
|
||||
{
|
||||
"check": "outsider.attachment_content_404",
|
||||
"pass": true,
|
||||
"detail": "404"
|
||||
},
|
||||
{
|
||||
"check": "outsider.attachment_thumbnail_404",
|
||||
"pass": true,
|
||||
"detail": "404"
|
||||
},
|
||||
{
|
||||
"check": "outsider.attach_foreign_file_404",
|
||||
"pass": true,
|
||||
"detail": "404"
|
||||
},
|
||||
{
|
||||
"check": "outsider.post_into_foreign_chat_404",
|
||||
"pass": true,
|
||||
"detail": "404"
|
||||
},
|
||||
{
|
||||
"check": "outsider.chat_list_hides_foreign",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "spoof.x_user_id_ignored",
|
||||
"pass": true,
|
||||
"detail": "me=eve"
|
||||
},
|
||||
{
|
||||
"check": "spoof.x_user_id_alone_401",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "auth.basic_on_business_endpoint_401",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "auth.unknown_token_401",
|
||||
"pass": true,
|
||||
"detail": "Bearer realm=\"messenger\""
|
||||
},
|
||||
{
|
||||
"check": "auth.same_401_unknown_user_and_wrong_password",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "auth.error_has_no_credentials_or_internals",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "logout.204",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "logout.token_revoked_401",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "logout.repeat_401",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "expiry.expired_session_401",
|
||||
"pass": true,
|
||||
"detail": "rows=1"
|
||||
},
|
||||
{
|
||||
"check": "argon2.stored_format",
|
||||
"pass": true,
|
||||
"detail": "$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>"
|
||||
},
|
||||
{
|
||||
"check": "argon2.unique_salt",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "argon2.rehash_legacy_scrypt_on_login",
|
||||
"pass": true,
|
||||
"detail": "$argon2id$v=19$m=19456,t=2,p=1"
|
||||
},
|
||||
{
|
||||
"check": "limits.json_body_over_1mib_413",
|
||||
"pass": true,
|
||||
"detail": "payload_too_large"
|
||||
},
|
||||
{
|
||||
"check": "limits.upload_over_10mib_413",
|
||||
"pass": true,
|
||||
"detail": "payload_too_large"
|
||||
},
|
||||
{
|
||||
"check": "headers.instance_alias_random",
|
||||
"pass": true,
|
||||
"detail": "r-4676e5ef75"
|
||||
},
|
||||
{
|
||||
"check": "headers.no_server_banner",
|
||||
"pass": true,
|
||||
"detail": "None"
|
||||
},
|
||||
{
|
||||
"check": "headers.hsts",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "ratelimit.login_429_with_retry_after",
|
||||
"pass": true,
|
||||
"detail": "first 429 at attempt 19, Retry-After=10, code=rate_limited"
|
||||
},
|
||||
{
|
||||
"check": "ratelimit.recovers_after_window",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
PASS tls.trusted_ca_and_hostname TLSv1.3
|
||||
PASS tls.wrong_hostname_rejected Hostname mismatch, certificate is not valid for 'evil.example'.
|
||||
PASS tls.internal_ca_does_not_validate_ingress unable to get local issuer certificate
|
||||
PASS tls.tls11_refused tls_error TLSV1_ALERT_PROTOCOL_VERSION
|
||||
PASS setup.attachment_ready ready
|
||||
PASS outsider.chat_404 404
|
||||
PASS outsider.history_404 404
|
||||
PASS outsider.attachment_metadata_404 404
|
||||
PASS outsider.attachment_content_404 404
|
||||
PASS outsider.attachment_thumbnail_404 404
|
||||
PASS outsider.attach_foreign_file_404 404
|
||||
PASS outsider.post_into_foreign_chat_404 404
|
||||
PASS outsider.chat_list_hides_foreign
|
||||
PASS spoof.x_user_id_ignored me=eve
|
||||
PASS spoof.x_user_id_alone_401
|
||||
PASS auth.basic_on_business_endpoint_401
|
||||
PASS auth.unknown_token_401 Bearer realm="messenger"
|
||||
PASS auth.same_401_unknown_user_and_wrong_password
|
||||
PASS auth.error_has_no_credentials_or_internals
|
||||
PASS logout.204
|
||||
PASS logout.token_revoked_401
|
||||
PASS logout.repeat_401
|
||||
PASS expiry.expired_session_401 rows=1
|
||||
PASS argon2.stored_format $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
|
||||
PASS argon2.unique_salt
|
||||
PASS argon2.rehash_legacy_scrypt_on_login $argon2id$v=19$m=19456,t=2,p=1
|
||||
PASS limits.json_body_over_1mib_413 payload_too_large
|
||||
PASS limits.upload_over_10mib_413 payload_too_large
|
||||
PASS headers.instance_alias_random r-4676e5ef75
|
||||
PASS headers.no_server_banner None
|
||||
PASS headers.hsts
|
||||
PASS ratelimit.login_429_with_retry_after first 429 at attempt 19, Retry-After=10, code=rate_limited
|
||||
PASS ratelimit.recovers_after_window
|
||||
PASS: 33 checks, 0 failed
|
||||
@@ -0,0 +1,917 @@
|
||||
{
|
||||
"checked_at": "2026-11-18T20:59:25Z",
|
||||
"total": 182,
|
||||
"failed": 0,
|
||||
"results": [
|
||||
{
|
||||
"check": "api(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_apinet//private"
|
||||
},
|
||||
{
|
||||
"check": "api(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=640MiB cpu=0.50"
|
||||
},
|
||||
{
|
||||
"check": "api(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(1).non_root_uid",
|
||||
"pass": true,
|
||||
"detail": "10001:10001"
|
||||
},
|
||||
{
|
||||
"check": "api(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(1).only_own_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "/run/secrets/internal-ca.crt,/run/secrets/service.crt,/run/secrets/service.key"
|
||||
},
|
||||
{
|
||||
"check": "api(2).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(2).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_apinet//private"
|
||||
},
|
||||
{
|
||||
"check": "api(2).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(2).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(2).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=640MiB cpu=0.50"
|
||||
},
|
||||
{
|
||||
"check": "api(2).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(2).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(2).non_root_uid",
|
||||
"pass": true,
|
||||
"detail": "10001:10001"
|
||||
},
|
||||
{
|
||||
"check": "api(2).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(2).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(2).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api(2).only_own_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "/run/secrets/internal-ca.crt,/run/secrets/service.crt,/run/secrets/service.key"
|
||||
},
|
||||
{
|
||||
"check": "broker(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "broker(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_backend//private"
|
||||
},
|
||||
{
|
||||
"check": "broker(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "broker(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "broker(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=512MiB cpu=1.00"
|
||||
},
|
||||
{
|
||||
"check": "broker(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": "add=CHOWN,DAC_OVERRIDE,FOWNER,SETGID,SETUID"
|
||||
},
|
||||
{
|
||||
"check": "broker(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": "CHOWN,DAC_OVERRIDE,FOWNER,SETGID,SETUID"
|
||||
},
|
||||
{
|
||||
"check": "broker(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "broker(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "db(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "db(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_backend//private"
|
||||
},
|
||||
{
|
||||
"check": "db(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "db(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "db(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=512MiB cpu=1.00"
|
||||
},
|
||||
{
|
||||
"check": "db(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": "add=CHOWN,DAC_OVERRIDE,FOWNER,SETGID,SETUID"
|
||||
},
|
||||
{
|
||||
"check": "db(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": "CHOWN,DAC_OVERRIDE,FOWNER,SETGID,SETUID"
|
||||
},
|
||||
{
|
||||
"check": "db(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "db(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_grafana-ui//private"
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=384MiB cpu=0.50"
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).published_3000/tcp",
|
||||
"pass": true,
|
||||
"detail": "127.0.0.1:3000"
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "grafana(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_backend//private"
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=160MiB cpu=0.25"
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).non_root_uid",
|
||||
"pass": true,
|
||||
"detail": "10001:10001"
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor(1).only_own_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "/run/secrets/service.key,/run/secrets/internal-ca.crt,/run/secrets/service.crt"
|
||||
},
|
||||
{
|
||||
"check": "lb(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "lb(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_apinet//private"
|
||||
},
|
||||
{
|
||||
"check": "lb(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "lb(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "lb(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=128MiB cpu=0.50"
|
||||
},
|
||||
{
|
||||
"check": "lb(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "lb(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "lb(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "lb(1).published_8443/tcp",
|
||||
"pass": true,
|
||||
"detail": "127.0.0.1:8443"
|
||||
},
|
||||
{
|
||||
"check": "lb(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "lb(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "loki(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "loki(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_telemetry//private"
|
||||
},
|
||||
{
|
||||
"check": "loki(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "loki(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "loki(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=512MiB cpu=0.50"
|
||||
},
|
||||
{
|
||||
"check": "loki(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "loki(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "loki(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "loki(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "loki(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_vault//private"
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=256MiB cpu=0.50"
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "openbao(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_telemetry//private"
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=256MiB cpu=0.50"
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "otel-collector(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_telemetry//private"
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=512MiB cpu=0.50"
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "prometheus(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_backend//private"
|
||||
},
|
||||
{
|
||||
"check": "relay(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=128MiB cpu=0.25"
|
||||
},
|
||||
{
|
||||
"check": "relay(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay(1).non_root_uid",
|
||||
"pass": true,
|
||||
"detail": "10001:10001"
|
||||
},
|
||||
{
|
||||
"check": "relay(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay(1).only_own_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "/run/secrets/service.key,/run/secrets/internal-ca.crt,/run/secrets/service.crt"
|
||||
},
|
||||
{
|
||||
"check": "s3(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "s3(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_backend//private"
|
||||
},
|
||||
{
|
||||
"check": "s3(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "s3(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "s3(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=768MiB cpu=1.00"
|
||||
},
|
||||
{
|
||||
"check": "s3(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": "add=CHOWN,SETGID,SETUID"
|
||||
},
|
||||
{
|
||||
"check": "s3(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": "CHOWN,SETGID,SETUID"
|
||||
},
|
||||
{
|
||||
"check": "s3(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "s3(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_telemetry//private"
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=512MiB cpu=0.50"
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "tempo(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(1).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(1).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_backend//private"
|
||||
},
|
||||
{
|
||||
"check": "worker(1).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(1).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(1).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=1024MiB cpu=1.00"
|
||||
},
|
||||
{
|
||||
"check": "worker(1).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(1).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(1).non_root_uid",
|
||||
"pass": true,
|
||||
"detail": "10001:10001"
|
||||
},
|
||||
{
|
||||
"check": "worker(1).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(1).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(1).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(1).only_own_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "/run/secrets/internal-ca.crt,/run/secrets/service.crt,/run/secrets/service.key"
|
||||
},
|
||||
{
|
||||
"check": "worker(2).not_privileged",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(2).no_host_namespaces",
|
||||
"pass": true,
|
||||
"detail": "mtusi-lab7_backend//private"
|
||||
},
|
||||
{
|
||||
"check": "worker(2).no_docker_socket",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(2).no_new_privileges",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(2).memory_cpu_limits",
|
||||
"pass": true,
|
||||
"detail": "mem=1024MiB cpu=1.00"
|
||||
},
|
||||
{
|
||||
"check": "worker(2).cap_drop_all",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(2).cap_add_only_documented",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(2).non_root_uid",
|
||||
"pass": true,
|
||||
"detail": "10001:10001"
|
||||
},
|
||||
{
|
||||
"check": "worker(2).read_only_rootfs",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(2).no_vault_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(2).no_secret_values_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker(2).only_own_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "/run/secrets/internal-ca.crt,/run/secrets/service.crt,/run/secrets/service.key"
|
||||
},
|
||||
{
|
||||
"check": "api(6506bf).health_listener_only_health",
|
||||
"pass": true,
|
||||
"detail": "{\"GET /health/ready\": \"200\", \"GET /api/v1/chats\": \"404\", \"POST /api/v1/users\": \"404\", \"GET /api/v1/users/me\": \"404\"}"
|
||||
},
|
||||
{
|
||||
"check": "api(c66490).health_listener_only_health",
|
||||
"pass": true,
|
||||
"detail": "{\"GET /health/ready\": \"200\", \"GET /api/v1/chats\": \"404\", \"POST /api/v1/users\": \"404\", \"GET /api/v1/users/me\": \"404\"}"
|
||||
},
|
||||
{
|
||||
"check": "image.no_key_or_secret_files",
|
||||
"pass": true,
|
||||
"detail": " no_secrets_dir "
|
||||
},
|
||||
{
|
||||
"check": "image.no_secrets_dir",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "image.history_without_secret_values",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "image.default_user_non_root",
|
||||
"pass": true,
|
||||
"detail": "10001:10001"
|
||||
},
|
||||
{
|
||||
"check": "repo.scan_secrets_clean",
|
||||
"pass": true,
|
||||
"detail": "checked 125 secret values from 50 files; files with leaks: none"
|
||||
},
|
||||
{
|
||||
"check": "telemetry.loki_search_positive_control",
|
||||
"pass": true,
|
||||
"detail": "matching lines: 2"
|
||||
},
|
||||
{
|
||||
"check": "telemetry.loki_no_bearer_token",
|
||||
"pass": true,
|
||||
"detail": "hits=0"
|
||||
},
|
||||
{
|
||||
"check": "telemetry.loki_no_password",
|
||||
"pass": true,
|
||||
"detail": "hits=0"
|
||||
},
|
||||
{
|
||||
"check": "telemetry.loki_no_token_prefix",
|
||||
"pass": true,
|
||||
"detail": "hits=0"
|
||||
},
|
||||
{
|
||||
"check": "telemetry.tempo_no_token_or_password",
|
||||
"pass": true,
|
||||
"detail": "checked 5 traces"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
PASS api(1).not_privileged
|
||||
PASS api(1).no_host_namespaces mtusi-lab7_apinet//private
|
||||
PASS api(1).no_docker_socket
|
||||
PASS api(1).no_new_privileges
|
||||
PASS api(1).memory_cpu_limits mem=640MiB cpu=0.50
|
||||
PASS api(1).cap_drop_all
|
||||
PASS api(1).cap_add_only_documented
|
||||
PASS api(1).non_root_uid 10001:10001
|
||||
PASS api(1).read_only_rootfs
|
||||
PASS api(1).no_vault_token_in_env
|
||||
PASS api(1).no_secret_values_in_env
|
||||
PASS api(1).only_own_tls_identity_mounted /run/secrets/internal-ca.crt,/run/secrets/service.crt,/run/secrets/service.key
|
||||
PASS api(2).not_privileged
|
||||
PASS api(2).no_host_namespaces mtusi-lab7_apinet//private
|
||||
PASS api(2).no_docker_socket
|
||||
PASS api(2).no_new_privileges
|
||||
PASS api(2).memory_cpu_limits mem=640MiB cpu=0.50
|
||||
PASS api(2).cap_drop_all
|
||||
PASS api(2).cap_add_only_documented
|
||||
PASS api(2).non_root_uid 10001:10001
|
||||
PASS api(2).read_only_rootfs
|
||||
PASS api(2).no_vault_token_in_env
|
||||
PASS api(2).no_secret_values_in_env
|
||||
PASS api(2).only_own_tls_identity_mounted /run/secrets/internal-ca.crt,/run/secrets/service.crt,/run/secrets/service.key
|
||||
PASS broker(1).not_privileged
|
||||
PASS broker(1).no_host_namespaces mtusi-lab7_backend//private
|
||||
PASS broker(1).no_docker_socket
|
||||
PASS broker(1).no_new_privileges
|
||||
PASS broker(1).memory_cpu_limits mem=512MiB cpu=1.00
|
||||
PASS broker(1).cap_drop_all add=CHOWN,DAC_OVERRIDE,FOWNER,SETGID,SETUID
|
||||
PASS broker(1).cap_add_only_documented CHOWN,DAC_OVERRIDE,FOWNER,SETGID,SETUID
|
||||
PASS broker(1).no_vault_token_in_env
|
||||
PASS broker(1).no_secret_values_in_env
|
||||
PASS db(1).not_privileged
|
||||
PASS db(1).no_host_namespaces mtusi-lab7_backend//private
|
||||
PASS db(1).no_docker_socket
|
||||
PASS db(1).no_new_privileges
|
||||
PASS db(1).memory_cpu_limits mem=512MiB cpu=1.00
|
||||
PASS db(1).cap_drop_all add=CHOWN,DAC_OVERRIDE,FOWNER,SETGID,SETUID
|
||||
PASS db(1).cap_add_only_documented CHOWN,DAC_OVERRIDE,FOWNER,SETGID,SETUID
|
||||
PASS db(1).no_vault_token_in_env
|
||||
PASS db(1).no_secret_values_in_env
|
||||
PASS grafana(1).not_privileged
|
||||
PASS grafana(1).no_host_namespaces mtusi-lab7_grafana-ui//private
|
||||
PASS grafana(1).no_docker_socket
|
||||
PASS grafana(1).no_new_privileges
|
||||
PASS grafana(1).memory_cpu_limits mem=384MiB cpu=0.50
|
||||
PASS grafana(1).cap_drop_all
|
||||
PASS grafana(1).cap_add_only_documented
|
||||
PASS grafana(1).published_3000/tcp 127.0.0.1:3000
|
||||
PASS grafana(1).no_vault_token_in_env
|
||||
PASS grafana(1).no_secret_values_in_env
|
||||
PASS janitor(1).not_privileged
|
||||
PASS janitor(1).no_host_namespaces mtusi-lab7_backend//private
|
||||
PASS janitor(1).no_docker_socket
|
||||
PASS janitor(1).no_new_privileges
|
||||
PASS janitor(1).memory_cpu_limits mem=160MiB cpu=0.25
|
||||
PASS janitor(1).cap_drop_all
|
||||
PASS janitor(1).cap_add_only_documented
|
||||
PASS janitor(1).non_root_uid 10001:10001
|
||||
PASS janitor(1).read_only_rootfs
|
||||
PASS janitor(1).no_vault_token_in_env
|
||||
PASS janitor(1).no_secret_values_in_env
|
||||
PASS janitor(1).only_own_tls_identity_mounted /run/secrets/service.key,/run/secrets/internal-ca.crt,/run/secrets/service.crt
|
||||
PASS lb(1).not_privileged
|
||||
PASS lb(1).no_host_namespaces mtusi-lab7_apinet//private
|
||||
PASS lb(1).no_docker_socket
|
||||
PASS lb(1).no_new_privileges
|
||||
PASS lb(1).memory_cpu_limits mem=128MiB cpu=0.50
|
||||
PASS lb(1).cap_drop_all
|
||||
PASS lb(1).cap_add_only_documented
|
||||
PASS lb(1).read_only_rootfs
|
||||
PASS lb(1).published_8443/tcp 127.0.0.1:8443
|
||||
PASS lb(1).no_vault_token_in_env
|
||||
PASS lb(1).no_secret_values_in_env
|
||||
PASS loki(1).not_privileged
|
||||
PASS loki(1).no_host_namespaces mtusi-lab7_telemetry//private
|
||||
PASS loki(1).no_docker_socket
|
||||
PASS loki(1).no_new_privileges
|
||||
PASS loki(1).memory_cpu_limits mem=512MiB cpu=0.50
|
||||
PASS loki(1).cap_drop_all
|
||||
PASS loki(1).cap_add_only_documented
|
||||
PASS loki(1).read_only_rootfs
|
||||
PASS loki(1).no_vault_token_in_env
|
||||
PASS loki(1).no_secret_values_in_env
|
||||
PASS openbao(1).not_privileged
|
||||
PASS openbao(1).no_host_namespaces mtusi-lab7_vault//private
|
||||
PASS openbao(1).no_docker_socket
|
||||
PASS openbao(1).no_new_privileges
|
||||
PASS openbao(1).memory_cpu_limits mem=256MiB cpu=0.50
|
||||
PASS openbao(1).cap_drop_all
|
||||
PASS openbao(1).cap_add_only_documented
|
||||
PASS openbao(1).read_only_rootfs
|
||||
PASS openbao(1).no_vault_token_in_env
|
||||
PASS openbao(1).no_secret_values_in_env
|
||||
PASS otel-collector(1).not_privileged
|
||||
PASS otel-collector(1).no_host_namespaces mtusi-lab7_telemetry//private
|
||||
PASS otel-collector(1).no_docker_socket
|
||||
PASS otel-collector(1).no_new_privileges
|
||||
PASS otel-collector(1).memory_cpu_limits mem=256MiB cpu=0.50
|
||||
PASS otel-collector(1).cap_drop_all
|
||||
PASS otel-collector(1).cap_add_only_documented
|
||||
PASS otel-collector(1).read_only_rootfs
|
||||
PASS otel-collector(1).no_vault_token_in_env
|
||||
PASS otel-collector(1).no_secret_values_in_env
|
||||
PASS prometheus(1).not_privileged
|
||||
PASS prometheus(1).no_host_namespaces mtusi-lab7_telemetry//private
|
||||
PASS prometheus(1).no_docker_socket
|
||||
PASS prometheus(1).no_new_privileges
|
||||
PASS prometheus(1).memory_cpu_limits mem=512MiB cpu=0.50
|
||||
PASS prometheus(1).cap_drop_all
|
||||
PASS prometheus(1).cap_add_only_documented
|
||||
PASS prometheus(1).read_only_rootfs
|
||||
PASS prometheus(1).no_vault_token_in_env
|
||||
PASS prometheus(1).no_secret_values_in_env
|
||||
PASS relay(1).not_privileged
|
||||
PASS relay(1).no_host_namespaces mtusi-lab7_backend//private
|
||||
PASS relay(1).no_docker_socket
|
||||
PASS relay(1).no_new_privileges
|
||||
PASS relay(1).memory_cpu_limits mem=128MiB cpu=0.25
|
||||
PASS relay(1).cap_drop_all
|
||||
PASS relay(1).cap_add_only_documented
|
||||
PASS relay(1).non_root_uid 10001:10001
|
||||
PASS relay(1).read_only_rootfs
|
||||
PASS relay(1).no_vault_token_in_env
|
||||
PASS relay(1).no_secret_values_in_env
|
||||
PASS relay(1).only_own_tls_identity_mounted /run/secrets/service.key,/run/secrets/internal-ca.crt,/run/secrets/service.crt
|
||||
PASS s3(1).not_privileged
|
||||
PASS s3(1).no_host_namespaces mtusi-lab7_backend//private
|
||||
PASS s3(1).no_docker_socket
|
||||
PASS s3(1).no_new_privileges
|
||||
PASS s3(1).memory_cpu_limits mem=768MiB cpu=1.00
|
||||
PASS s3(1).cap_drop_all add=CHOWN,SETGID,SETUID
|
||||
PASS s3(1).cap_add_only_documented CHOWN,SETGID,SETUID
|
||||
PASS s3(1).no_vault_token_in_env
|
||||
PASS s3(1).no_secret_values_in_env
|
||||
PASS tempo(1).not_privileged
|
||||
PASS tempo(1).no_host_namespaces mtusi-lab7_telemetry//private
|
||||
PASS tempo(1).no_docker_socket
|
||||
PASS tempo(1).no_new_privileges
|
||||
PASS tempo(1).memory_cpu_limits mem=512MiB cpu=0.50
|
||||
PASS tempo(1).cap_drop_all
|
||||
PASS tempo(1).cap_add_only_documented
|
||||
PASS tempo(1).read_only_rootfs
|
||||
PASS tempo(1).no_vault_token_in_env
|
||||
PASS tempo(1).no_secret_values_in_env
|
||||
PASS worker(1).not_privileged
|
||||
PASS worker(1).no_host_namespaces mtusi-lab7_backend//private
|
||||
PASS worker(1).no_docker_socket
|
||||
PASS worker(1).no_new_privileges
|
||||
PASS worker(1).memory_cpu_limits mem=1024MiB cpu=1.00
|
||||
PASS worker(1).cap_drop_all
|
||||
PASS worker(1).cap_add_only_documented
|
||||
PASS worker(1).non_root_uid 10001:10001
|
||||
PASS worker(1).read_only_rootfs
|
||||
PASS worker(1).no_vault_token_in_env
|
||||
PASS worker(1).no_secret_values_in_env
|
||||
PASS worker(1).only_own_tls_identity_mounted /run/secrets/internal-ca.crt,/run/secrets/service.crt,/run/secrets/service.key
|
||||
PASS worker(2).not_privileged
|
||||
PASS worker(2).no_host_namespaces mtusi-lab7_backend//private
|
||||
PASS worker(2).no_docker_socket
|
||||
PASS worker(2).no_new_privileges
|
||||
PASS worker(2).memory_cpu_limits mem=1024MiB cpu=1.00
|
||||
PASS worker(2).cap_drop_all
|
||||
PASS worker(2).cap_add_only_documented
|
||||
PASS worker(2).non_root_uid 10001:10001
|
||||
PASS worker(2).read_only_rootfs
|
||||
PASS worker(2).no_vault_token_in_env
|
||||
PASS worker(2).no_secret_values_in_env
|
||||
PASS worker(2).only_own_tls_identity_mounted /run/secrets/internal-ca.crt,/run/secrets/service.crt,/run/secrets/service.key
|
||||
PASS api(6506bf).health_listener_only_health {"GET /health/ready": "200", "GET /api/v1/chats": "404", "POST /api/v1/users": "404", "GET /api/v1/users/me": "404"}
|
||||
PASS api(c66490).health_listener_only_health {"GET /health/ready": "200", "GET /api/v1/chats": "404", "POST /api/v1/users": "404", "GET /api/v1/users/me": "404"}
|
||||
PASS image.no_key_or_secret_files no_secrets_dir
|
||||
PASS image.no_secrets_dir
|
||||
PASS image.history_without_secret_values
|
||||
PASS image.default_user_non_root 10001:10001
|
||||
PASS repo.scan_secrets_clean checked 125 secret values from 50 files; files with leaks: none
|
||||
PASS telemetry.loki_search_positive_control matching lines: 2
|
||||
PASS telemetry.loki_no_bearer_token hits=0
|
||||
PASS telemetry.loki_no_password hits=0
|
||||
PASS telemetry.loki_no_token_prefix hits=0
|
||||
PASS telemetry.tempo_no_token_or_password checked 5 traces
|
||||
PASS: 182 checks, 0 failed
|
||||
@@ -0,0 +1,422 @@
|
||||
{
|
||||
"checked_at": "2026-11-18T20:28:13Z",
|
||||
"total": 83,
|
||||
"failed": 0,
|
||||
"results": [
|
||||
{
|
||||
"check": "status.initialized_unsealed",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "status.storage_raft_persistent",
|
||||
"pass": true,
|
||||
"detail": "raft"
|
||||
},
|
||||
{
|
||||
"check": "status.shares_threshold",
|
||||
"pass": true,
|
||||
"detail": "t=2 n=3"
|
||||
},
|
||||
{
|
||||
"check": "status.not_dev_mode",
|
||||
"pass": true,
|
||||
"detail": "[\"bao\",\"server\",\"-config=/openbao/config/openbao.hcl\"] null"
|
||||
},
|
||||
{
|
||||
"check": "api.login_policies",
|
||||
"pass": true,
|
||||
"detail": "default,messenger-api"
|
||||
},
|
||||
{
|
||||
"check": "api.token_ttl_bounded",
|
||||
"pass": true,
|
||||
"detail": "ttl=900"
|
||||
},
|
||||
{
|
||||
"check": "api.read_own_path_200",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api.own_fields_exact",
|
||||
"pass": true,
|
||||
"detail": "POSTGRES_PASSWORD,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY"
|
||||
},
|
||||
{
|
||||
"check": "api.deny_read_other_service",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "api.deny_read_migrate_admin",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "api.deny_list_metadata",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "api.deny_write_own_secret",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "api.deny_write_policy",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "api.deny_create_token",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "api.deny_seal",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "api.deny_list_auth_roles",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "api.renew_self",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api.revoked_token_denied",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "api.no_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api.only_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "internal-ca.crt,service.crt,service.key"
|
||||
},
|
||||
{
|
||||
"check": "api.db_role_not_privileged",
|
||||
"pass": true,
|
||||
"detail": "api_svc TLSv1.3"
|
||||
},
|
||||
{
|
||||
"check": "worker.login_policies",
|
||||
"pass": true,
|
||||
"detail": "default,messenger-worker"
|
||||
},
|
||||
{
|
||||
"check": "worker.token_ttl_bounded",
|
||||
"pass": true,
|
||||
"detail": "ttl=900"
|
||||
},
|
||||
{
|
||||
"check": "worker.read_own_path_200",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker.own_fields_exact",
|
||||
"pass": true,
|
||||
"detail": "BROKER_URL,POSTGRES_PASSWORD,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY"
|
||||
},
|
||||
{
|
||||
"check": "worker.deny_read_other_service",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "worker.deny_read_migrate_admin",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "worker.deny_list_metadata",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "worker.deny_write_own_secret",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "worker.deny_write_policy",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "worker.deny_create_token",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "worker.deny_seal",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "worker.deny_list_auth_roles",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "worker.renew_self",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker.revoked_token_denied",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "worker.no_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker.only_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "internal-ca.crt,service.crt,service.key"
|
||||
},
|
||||
{
|
||||
"check": "worker.db_role_not_privileged",
|
||||
"pass": true,
|
||||
"detail": "worker_svc TLSv1.3"
|
||||
},
|
||||
{
|
||||
"check": "relay.login_policies",
|
||||
"pass": true,
|
||||
"detail": "default,messenger-relay"
|
||||
},
|
||||
{
|
||||
"check": "relay.token_ttl_bounded",
|
||||
"pass": true,
|
||||
"detail": "ttl=900"
|
||||
},
|
||||
{
|
||||
"check": "relay.read_own_path_200",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay.own_fields_exact",
|
||||
"pass": true,
|
||||
"detail": "BROKER_URL,POSTGRES_PASSWORD"
|
||||
},
|
||||
{
|
||||
"check": "relay.deny_read_other_service",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "relay.deny_read_migrate_admin",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "relay.deny_list_metadata",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "relay.deny_write_own_secret",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "relay.deny_write_policy",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "relay.deny_create_token",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "relay.deny_seal",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "relay.deny_list_auth_roles",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "relay.renew_self",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay.revoked_token_denied",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "relay.no_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "relay.only_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "internal-ca.crt,service.crt,service.key"
|
||||
},
|
||||
{
|
||||
"check": "relay.db_role_not_privileged",
|
||||
"pass": true,
|
||||
"detail": "relay_svc TLSv1.3"
|
||||
},
|
||||
{
|
||||
"check": "janitor.login_policies",
|
||||
"pass": true,
|
||||
"detail": "default,messenger-janitor"
|
||||
},
|
||||
{
|
||||
"check": "janitor.token_ttl_bounded",
|
||||
"pass": true,
|
||||
"detail": "ttl=900"
|
||||
},
|
||||
{
|
||||
"check": "janitor.read_own_path_200",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor.own_fields_exact",
|
||||
"pass": true,
|
||||
"detail": "POSTGRES_PASSWORD,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY"
|
||||
},
|
||||
{
|
||||
"check": "janitor.deny_read_other_service",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "janitor.deny_read_migrate_admin",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "janitor.deny_list_metadata",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "janitor.deny_write_own_secret",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "janitor.deny_write_policy",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "janitor.deny_create_token",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "janitor.deny_seal",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "janitor.deny_list_auth_roles",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "janitor.renew_self",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor.revoked_token_denied",
|
||||
"pass": true,
|
||||
"detail": "403"
|
||||
},
|
||||
{
|
||||
"check": "janitor.no_token_in_env",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "janitor.only_tls_identity_mounted",
|
||||
"pass": true,
|
||||
"detail": "internal-ca.crt,service.crt,service.key"
|
||||
},
|
||||
{
|
||||
"check": "janitor.db_role_not_privileged",
|
||||
"pass": true,
|
||||
"detail": "janitor_svc TLSv1.3"
|
||||
},
|
||||
{
|
||||
"check": "worker.has_own_s3_key",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker.no_admin_or_api_s3_key",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "worker.db_no_users_sessions_messages",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "api.db_no_ddl_truncate",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "sealed.after_restart_sealed",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "sealed.running_api_keeps_serving",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "sealed.restarted_replica_not_healthy",
|
||||
"pass": true,
|
||||
"detail": "unhealthy"
|
||||
},
|
||||
{
|
||||
"check": "sealed.restarted_replica_waits_for_openbao",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
},
|
||||
{
|
||||
"check": "sealed.lb_serves_from_other_replica",
|
||||
"pass": true,
|
||||
"detail": "r-752aa9a6c1"
|
||||
},
|
||||
{
|
||||
"check": "sealed.replica_healthy_after_unseal",
|
||||
"pass": true,
|
||||
"detail": "11.5s after unseal (total 42s)"
|
||||
},
|
||||
{
|
||||
"check": "sealed.kv_persisted_after_restart",
|
||||
"pass": true,
|
||||
"detail": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
PASS status.initialized_unsealed
|
||||
PASS status.storage_raft_persistent raft
|
||||
PASS status.shares_threshold t=2 n=3
|
||||
PASS status.not_dev_mode ["bao","server","-config=/openbao/config/openbao.hcl"] null
|
||||
PASS api.login_policies default,messenger-api
|
||||
PASS api.token_ttl_bounded ttl=900
|
||||
PASS api.read_own_path_200
|
||||
PASS api.own_fields_exact POSTGRES_PASSWORD,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY
|
||||
PASS api.deny_read_other_service 403
|
||||
PASS api.deny_read_migrate_admin 403
|
||||
PASS api.deny_list_metadata 403
|
||||
PASS api.deny_write_own_secret 403
|
||||
PASS api.deny_write_policy 403
|
||||
PASS api.deny_create_token 403
|
||||
PASS api.deny_seal 403
|
||||
PASS api.deny_list_auth_roles 403
|
||||
PASS api.renew_self
|
||||
PASS api.revoked_token_denied 403
|
||||
PASS api.no_token_in_env
|
||||
PASS api.only_tls_identity_mounted internal-ca.crt,service.crt,service.key
|
||||
PASS api.db_role_not_privileged api_svc TLSv1.3
|
||||
PASS worker.login_policies default,messenger-worker
|
||||
PASS worker.token_ttl_bounded ttl=900
|
||||
PASS worker.read_own_path_200
|
||||
PASS worker.own_fields_exact BROKER_URL,POSTGRES_PASSWORD,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY
|
||||
PASS worker.deny_read_other_service 403
|
||||
PASS worker.deny_read_migrate_admin 403
|
||||
PASS worker.deny_list_metadata 403
|
||||
PASS worker.deny_write_own_secret 403
|
||||
PASS worker.deny_write_policy 403
|
||||
PASS worker.deny_create_token 403
|
||||
PASS worker.deny_seal 403
|
||||
PASS worker.deny_list_auth_roles 403
|
||||
PASS worker.renew_self
|
||||
PASS worker.revoked_token_denied 403
|
||||
PASS worker.no_token_in_env
|
||||
PASS worker.only_tls_identity_mounted internal-ca.crt,service.crt,service.key
|
||||
PASS worker.db_role_not_privileged worker_svc TLSv1.3
|
||||
PASS relay.login_policies default,messenger-relay
|
||||
PASS relay.token_ttl_bounded ttl=900
|
||||
PASS relay.read_own_path_200
|
||||
PASS relay.own_fields_exact BROKER_URL,POSTGRES_PASSWORD
|
||||
PASS relay.deny_read_other_service 403
|
||||
PASS relay.deny_read_migrate_admin 403
|
||||
PASS relay.deny_list_metadata 403
|
||||
PASS relay.deny_write_own_secret 403
|
||||
PASS relay.deny_write_policy 403
|
||||
PASS relay.deny_create_token 403
|
||||
PASS relay.deny_seal 403
|
||||
PASS relay.deny_list_auth_roles 403
|
||||
PASS relay.renew_self
|
||||
PASS relay.revoked_token_denied 403
|
||||
PASS relay.no_token_in_env
|
||||
PASS relay.only_tls_identity_mounted internal-ca.crt,service.crt,service.key
|
||||
PASS relay.db_role_not_privileged relay_svc TLSv1.3
|
||||
PASS janitor.login_policies default,messenger-janitor
|
||||
PASS janitor.token_ttl_bounded ttl=900
|
||||
PASS janitor.read_own_path_200
|
||||
PASS janitor.own_fields_exact POSTGRES_PASSWORD,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY
|
||||
PASS janitor.deny_read_other_service 403
|
||||
PASS janitor.deny_read_migrate_admin 403
|
||||
PASS janitor.deny_list_metadata 403
|
||||
PASS janitor.deny_write_own_secret 403
|
||||
PASS janitor.deny_write_policy 403
|
||||
PASS janitor.deny_create_token 403
|
||||
PASS janitor.deny_seal 403
|
||||
PASS janitor.deny_list_auth_roles 403
|
||||
PASS janitor.renew_self
|
||||
PASS janitor.revoked_token_denied 403
|
||||
PASS janitor.no_token_in_env
|
||||
PASS janitor.only_tls_identity_mounted internal-ca.crt,service.crt,service.key
|
||||
PASS janitor.db_role_not_privileged janitor_svc TLSv1.3
|
||||
PASS worker.has_own_s3_key
|
||||
PASS worker.no_admin_or_api_s3_key
|
||||
PASS worker.db_no_users_sessions_messages
|
||||
PASS api.db_no_ddl_truncate
|
||||
PASS sealed.after_restart_sealed
|
||||
PASS sealed.running_api_keeps_serving
|
||||
PASS sealed.restarted_replica_not_healthy unhealthy
|
||||
PASS sealed.restarted_replica_waits_for_openbao
|
||||
PASS sealed.lb_serves_from_other_replica r-752aa9a6c1
|
||||
PASS sealed.replica_healthy_after_unseal 11.5s after unseal (total 42s)
|
||||
PASS sealed.kv_persisted_after_restart
|
||||
PASS: 83 checks, 0 failed
|
||||
@@ -0,0 +1,607 @@
|
||||
{
|
||||
"checked_at": "2026-11-18T20:26:44Z",
|
||||
"total": 67,
|
||||
"failed": 0,
|
||||
"results": [
|
||||
{
|
||||
"link": "LB->API",
|
||||
"case": "replicas_resolved",
|
||||
"pass": true,
|
||||
"detail": 2
|
||||
},
|
||||
{
|
||||
"link": "LB->API[0]",
|
||||
"case": "no client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[0]",
|
||||
"case": "client cert of rogue CA, SAN lb",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV1_ALERT_UNKNOWN_CA",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[0]",
|
||||
"case": "trusted CA, identity intruder",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "closed_after_handshake_no_http_response",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[0]",
|
||||
"case": "plaintext HTTP to 8443",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "reset_by_server",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[0]",
|
||||
"case": "health listener 8081 from network",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[0]",
|
||||
"case": "server cert, wrong expected hostname",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'db'.",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[0]",
|
||||
"case": "identity lb -> /health/ready",
|
||||
"expect": "ok",
|
||||
"observed": "ok",
|
||||
"detail": 200,
|
||||
"pass": true,
|
||||
"note": "status=200"
|
||||
},
|
||||
{
|
||||
"link": "LB->API[0]",
|
||||
"case": "identity lb, no Bearer -> business API",
|
||||
"expect": "ok",
|
||||
"observed": "ok",
|
||||
"detail": 401,
|
||||
"pass": true,
|
||||
"note": "mTLS не заменяет сессию: ожидается 401, получено 401"
|
||||
},
|
||||
{
|
||||
"link": "LB->API[1]",
|
||||
"case": "no client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[1]",
|
||||
"case": "client cert of rogue CA, SAN lb",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV1_ALERT_UNKNOWN_CA",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[1]",
|
||||
"case": "trusted CA, identity intruder",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "closed_after_handshake_no_http_response",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[1]",
|
||||
"case": "plaintext HTTP to 8443",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "reset_by_server",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[1]",
|
||||
"case": "health listener 8081 from network",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[1]",
|
||||
"case": "server cert, wrong expected hostname",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'db'.",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "LB->API[1]",
|
||||
"case": "identity lb -> /health/ready",
|
||||
"expect": "ok",
|
||||
"observed": "ok",
|
||||
"detail": 200,
|
||||
"pass": true,
|
||||
"note": "status=200"
|
||||
},
|
||||
{
|
||||
"link": "LB->API[1]",
|
||||
"case": "identity lb, no Bearer -> business API",
|
||||
"expect": "ok",
|
||||
"observed": "ok",
|
||||
"detail": 401,
|
||||
"pass": true,
|
||||
"note": "mTLS не заменяет сессию: ожидается 401, получено 401"
|
||||
},
|
||||
{
|
||||
"link": "API/worker->PostgreSQL",
|
||||
"case": "sslmode=disable (plaintext)",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection failed: connection to server at \"192.168.0.3\", port 5432 failed: fatal: pg_hba.conf rejects connection for h",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->PostgreSQL",
|
||||
"case": "verify-full, rogue CA as trust",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->PostgreSQL",
|
||||
"case": "verify-full by IP (SAN mismatch)",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->PostgreSQL",
|
||||
"case": "verify-full, internal CA, wrong pwd",
|
||||
"expect": "ok",
|
||||
"observed": "ok",
|
||||
"detail": "tls_ok_then_password_rejected",
|
||||
"pass": true,
|
||||
"note": "TLS проверен; дальше SCRAM отклоняет неверный пароль"
|
||||
},
|
||||
{
|
||||
"link": "API/worker->S3",
|
||||
"case": "plaintext HTTP",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "http_400_plain_http_sent_to_https_port",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->S3",
|
||||
"case": "HTTPS, rogue CA as trust",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:unable to get local issuer certificate",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->S3",
|
||||
"case": "HTTPS verified, anonymous list",
|
||||
"expect": "ok",
|
||||
"observed": "ok",
|
||||
"detail": 403,
|
||||
"pass": true,
|
||||
"note": "TLS ok; анонимно: 403 (ожидается 403)"
|
||||
},
|
||||
{
|
||||
"link": "API/worker->broker",
|
||||
"case": "plaintext AMQP 5672",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->broker",
|
||||
"case": "AMQPS, rogue CA as trust",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:self-signed certificate in certificate chain",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->broker",
|
||||
"case": "AMQPS, client cert of rogue CA",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV1_ALERT_UNKNOWN_CA",
|
||||
"pass": true,
|
||||
"note": "verify_peer: предъявленный чужой сертификат отвергается"
|
||||
},
|
||||
{
|
||||
"link": "API/worker->broker",
|
||||
"case": "AMQPS verified (без cert), Connection.Start",
|
||||
"expect": "ok",
|
||||
"observed": "ok",
|
||||
"detail": "amqp_connection_start",
|
||||
"pass": true,
|
||||
"note": "далее аутентификация паролем + ACL vhost (проверка прав — broker_permissions)"
|
||||
},
|
||||
{
|
||||
"link": "API/worker->broker",
|
||||
"case": "AMQPS, user worker, wrong password",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "auth_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Prometheus->broker metrics",
|
||||
"case": "HTTPS 15691 without client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Prometheus->broker metrics",
|
||||
"case": "plaintext 15692 from network",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->Collector",
|
||||
"case": "plaintext",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "http_400_plain_http_sent_to_https_port",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->Collector",
|
||||
"case": "TLS without client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->Collector",
|
||||
"case": "TLS, client cert of rogue CA",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV1_ALERT_UNKNOWN_CA",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->Collector",
|
||||
"case": "TLS, wrong expected hostname",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector/Grafana->Prometheus",
|
||||
"case": "plaintext",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "http_400_plain_http_sent_to_https_port",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector/Grafana->Prometheus",
|
||||
"case": "TLS without client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector/Grafana->Prometheus",
|
||||
"case": "TLS, client cert of rogue CA",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV1_ALERT_UNKNOWN_CA",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector/Grafana->Prometheus",
|
||||
"case": "TLS, wrong expected hostname",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector/Grafana->Loki",
|
||||
"case": "plaintext",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "http_400_plain_http_sent_to_https_port",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector/Grafana->Loki",
|
||||
"case": "TLS without client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector/Grafana->Loki",
|
||||
"case": "TLS, client cert of rogue CA",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV1_ALERT_UNKNOWN_CA",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector/Grafana->Loki",
|
||||
"case": "TLS, wrong expected hostname",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Grafana->Tempo",
|
||||
"case": "plaintext",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "http_400_plain_http_sent_to_https_port",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Grafana->Tempo",
|
||||
"case": "TLS without client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Grafana->Tempo",
|
||||
"case": "TLS, client cert of rogue CA",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:SSLEOFError",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Grafana->Tempo",
|
||||
"case": "TLS, wrong expected hostname",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector->Tempo OTLP gRPC",
|
||||
"case": "plaintext",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "closed_without_plaintext_response",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector->Tempo OTLP gRPC",
|
||||
"case": "TLS without client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector->Tempo OTLP gRPC",
|
||||
"case": "TLS, client cert of rogue CA",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV1_ALERT_UNKNOWN_CA",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Collector->Tempo OTLP gRPC",
|
||||
"case": "TLS, wrong expected hostname",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Prometheus->LB metrics",
|
||||
"case": "plaintext",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "closed_without_plaintext_response",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Prometheus->LB metrics",
|
||||
"case": "TLS without client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Prometheus->LB metrics",
|
||||
"case": "TLS, client cert of rogue CA",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "tls_alert:TLSV1_ALERT_UNKNOWN_CA",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "Prometheus->LB metrics",
|
||||
"case": "TLS, wrong expected hostname",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "internal-only port",
|
||||
"case": "otel-collector:4317 from network",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "internal-only port",
|
||||
"case": "otel-collector:8888 from network",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "internal-only port",
|
||||
"case": "otel-collector:13133 from network",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "internal-only port",
|
||||
"case": "loki:9095 from network",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "internal-only port",
|
||||
"case": "tempo:9096 from network",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "connection_refused",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "API/worker->Collector",
|
||||
"case": "trusted CA, foreign identity (intruder)",
|
||||
"expect": "documented",
|
||||
"observed": "ok",
|
||||
"detail": 405,
|
||||
"pass": true,
|
||||
"note": "level 3: CA-only mTLS; разграничение identity — уровень 4 (см. trust-matrix)"
|
||||
},
|
||||
{
|
||||
"link": "services->OpenBao",
|
||||
"case": "plaintext HTTP",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "http_400_plain_http_sent_to_https_port",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "services->OpenBao",
|
||||
"case": "TLS, rogue CA as trust",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "server_cert_rejected_by_client:unable to get local issuer certificate",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "services->OpenBao",
|
||||
"case": "TLS verified, /v1/sys/health",
|
||||
"expect": "ok",
|
||||
"observed": "ok",
|
||||
"detail": 200,
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "services->OpenBao",
|
||||
"case": "cert login as role api with intruder cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "http_400",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"link": "services->OpenBao",
|
||||
"case": "cert login as role api with lb cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "http_400",
|
||||
"pass": true,
|
||||
"note": "сертификат того же CA, но SAN не api -> роль не подходит"
|
||||
},
|
||||
{
|
||||
"link": "services->OpenBao",
|
||||
"case": "cert login without client cert",
|
||||
"expect": "fail",
|
||||
"observed": "fail",
|
||||
"detail": "http_400",
|
||||
"pass": true,
|
||||
"note": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
API replicas: 2
|
||||
PASS LB->API[0] no client cert expect=fail got=fail tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED
|
||||
PASS LB->API[0] client cert of rogue CA, SAN lb expect=fail got=fail tls_alert:TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS LB->API[0] trusted CA, identity intruder expect=fail got=fail closed_after_handshake_no_http_response
|
||||
PASS LB->API[0] plaintext HTTP to 8443 expect=fail got=fail reset_by_server
|
||||
PASS LB->API[0] health listener 8081 from network expect=fail got=fail connection_refused
|
||||
PASS LB->API[0] server cert, wrong expected hostname expect=fail got=fail server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'db'.
|
||||
PASS LB->API[0] identity lb -> /health/ready expect=ok got=ok 200
|
||||
PASS LB->API[0] identity lb, no Bearer -> business API expect=ok got=ok 401
|
||||
PASS LB->API[1] no client cert expect=fail got=fail tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED
|
||||
PASS LB->API[1] client cert of rogue CA, SAN lb expect=fail got=fail tls_alert:TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS LB->API[1] trusted CA, identity intruder expect=fail got=fail closed_after_handshake_no_http_response
|
||||
PASS LB->API[1] plaintext HTTP to 8443 expect=fail got=fail reset_by_server
|
||||
PASS LB->API[1] health listener 8081 from network expect=fail got=fail connection_refused
|
||||
PASS LB->API[1] server cert, wrong expected hostname expect=fail got=fail server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'db'.
|
||||
PASS LB->API[1] identity lb -> /health/ready expect=ok got=ok 200
|
||||
PASS LB->API[1] identity lb, no Bearer -> business API expect=ok got=ok 401
|
||||
PASS API/worker->PostgreSQL sslmode=disable (plaintext) expect=fail got=fail connection failed: connection to server at "192.168.0.3", port 5432 failed: fatal: pg_hba.conf rejects connection for h
|
||||
PASS API/worker->PostgreSQL verify-full, rogue CA as trust expect=fail got=fail server_cert_rejected_by_client
|
||||
PASS API/worker->PostgreSQL verify-full by IP (SAN mismatch) expect=fail got=fail server_cert_rejected_by_client
|
||||
PASS API/worker->PostgreSQL verify-full, internal CA, wrong pwd expect=ok got=ok tls_ok_then_password_rejected
|
||||
PASS API/worker->S3 plaintext HTTP expect=fail got=fail http_400_plain_http_sent_to_https_port
|
||||
PASS API/worker->S3 HTTPS, rogue CA as trust expect=fail got=fail server_cert_rejected_by_client:unable to get local issuer certificate
|
||||
PASS API/worker->S3 HTTPS verified, anonymous list expect=ok got=ok 403
|
||||
PASS API/worker->broker plaintext AMQP 5672 expect=fail got=fail connection_refused
|
||||
PASS API/worker->broker AMQPS, rogue CA as trust expect=fail got=fail server_cert_rejected_by_client:self-signed certificate in certificate chain
|
||||
PASS API/worker->broker AMQPS, client cert of rogue CA expect=fail got=fail tls_alert:TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS API/worker->broker AMQPS verified (без cert), Connection.Start expect=ok got=ok amqp_connection_start
|
||||
PASS API/worker->broker AMQPS, user worker, wrong password expect=fail got=fail auth_refused
|
||||
PASS Prometheus->broker metrics HTTPS 15691 without client cert expect=fail got=fail tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED
|
||||
PASS Prometheus->broker metrics plaintext 15692 from network expect=fail got=fail connection_refused
|
||||
PASS API/worker->Collector plaintext expect=fail got=fail http_400_plain_http_sent_to_https_port
|
||||
PASS API/worker->Collector TLS without client cert expect=fail got=fail tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED
|
||||
PASS API/worker->Collector TLS, client cert of rogue CA expect=fail got=fail tls_alert:TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS API/worker->Collector TLS, wrong expected hostname expect=fail got=fail server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.
|
||||
PASS Collector/Grafana->Prometheus plaintext expect=fail got=fail http_400_plain_http_sent_to_https_port
|
||||
PASS Collector/Grafana->Prometheus TLS without client cert expect=fail got=fail tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED
|
||||
PASS Collector/Grafana->Prometheus TLS, client cert of rogue CA expect=fail got=fail tls_alert:TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS Collector/Grafana->Prometheus TLS, wrong expected hostname expect=fail got=fail server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.
|
||||
PASS Collector/Grafana->Loki plaintext expect=fail got=fail http_400_plain_http_sent_to_https_port
|
||||
PASS Collector/Grafana->Loki TLS without client cert expect=fail got=fail tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED
|
||||
PASS Collector/Grafana->Loki TLS, client cert of rogue CA expect=fail got=fail tls_alert:TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS Collector/Grafana->Loki TLS, wrong expected hostname expect=fail got=fail server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.
|
||||
PASS Grafana->Tempo plaintext expect=fail got=fail http_400_plain_http_sent_to_https_port
|
||||
PASS Grafana->Tempo TLS without client cert expect=fail got=fail tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED
|
||||
PASS Grafana->Tempo TLS, client cert of rogue CA expect=fail got=fail tls_alert:SSLEOFError
|
||||
PASS Grafana->Tempo TLS, wrong expected hostname expect=fail got=fail server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.
|
||||
PASS Collector->Tempo OTLP gRPC plaintext expect=fail got=fail closed_without_plaintext_response
|
||||
PASS Collector->Tempo OTLP gRPC TLS without client cert expect=fail got=fail tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED
|
||||
PASS Collector->Tempo OTLP gRPC TLS, client cert of rogue CA expect=fail got=fail tls_alert:TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS Collector->Tempo OTLP gRPC TLS, wrong expected hostname expect=fail got=fail server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.
|
||||
PASS Prometheus->LB metrics plaintext expect=fail got=fail closed_without_plaintext_response
|
||||
PASS Prometheus->LB metrics TLS without client cert expect=fail got=fail tls_alert:TLSV13_ALERT_CERTIFICATE_REQUIRED
|
||||
PASS Prometheus->LB metrics TLS, client cert of rogue CA expect=fail got=fail tls_alert:TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS Prometheus->LB metrics TLS, wrong expected hostname expect=fail got=fail server_cert_rejected_by_client:Hostname mismatch, certificate is not valid for 'api'.
|
||||
PASS internal-only port otel-collector:4317 from network expect=fail got=fail connection_refused
|
||||
PASS internal-only port otel-collector:8888 from network expect=fail got=fail connection_refused
|
||||
PASS internal-only port otel-collector:13133 from network expect=fail got=fail connection_refused
|
||||
PASS internal-only port loki:9095 from network expect=fail got=fail connection_refused
|
||||
PASS internal-only port tempo:9096 from network expect=fail got=fail connection_refused
|
||||
INFO API/worker->Collector intruder cert: ('ok', 405)
|
||||
PASS services->OpenBao plaintext HTTP expect=fail got=fail http_400_plain_http_sent_to_https_port
|
||||
PASS services->OpenBao TLS, rogue CA as trust expect=fail got=fail server_cert_rejected_by_client:unable to get local issuer certificate
|
||||
PASS services->OpenBao TLS verified, /v1/sys/health expect=ok got=ok 200
|
||||
PASS services->OpenBao cert login as role api with intruder cert expect=fail got=fail http_400
|
||||
PASS services->OpenBao cert login as role api with lb cert expect=fail got=fail http_400
|
||||
PASS services->OpenBao cert login without client cert expect=fail got=fail http_400
|
||||
PASS: 67 checks, 0 failed
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 7,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.007,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 9588,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 319.526,
|
||||
"successful_latency_ms": {
|
||||
"p50": 8.292,
|
||||
"p95": 37.698,
|
||||
"p99": 77.457
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 7,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.029,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 2429,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 80.888,
|
||||
"successful_latency_ms": {
|
||||
"p50": 48.835,
|
||||
"p95": 52.869,
|
||||
"p99": 75.113
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 7,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.008,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 9084,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 302.72,
|
||||
"successful_latency_ms": {
|
||||
"p50": 7.827,
|
||||
"p95": 43.767,
|
||||
"p99": 82.808
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 7,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.008,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 9084,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 302.72,
|
||||
"successful_latency_ms": {
|
||||
"p50": 7.827,
|
||||
"p95": 43.767,
|
||||
"p99": 82.808
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/security.py --base-url "https://localhost:8443" --ca-file "/Users/uralazarev/Documents/mtusi2026lab7/secrets/pki/public-ca.crt"
|
||||
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/Users/uralazarev/Documents/mtusi2026lab7/secrets/pki/public-ca.crt"
|
||||
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,238 @@
|
||||
{
|
||||
"scenario": "lab6 signal correlation: request -> trace -> log, upload -> relay -> worker",
|
||||
"date_utc": "2026-11-18T20:30:27+00:00",
|
||||
"steps": [
|
||||
{
|
||||
"t": 0.2,
|
||||
"utc": "20:30:18.797",
|
||||
"step": "message sent",
|
||||
"request_id": "e755c640d7c64606817798996b38e737",
|
||||
"trace_id": "a5395a7a0d14fddbe988dd3fbc8052c3",
|
||||
"instance": "r-f7dd6d1932"
|
||||
},
|
||||
{
|
||||
"t": 2.25,
|
||||
"utc": "20:30:20.844",
|
||||
"step": "message trace in Tempo",
|
||||
"spans": 4,
|
||||
"server_ms": 5.068,
|
||||
"db_spans": [
|
||||
"db get_session_user",
|
||||
"db get_chat_for",
|
||||
"db add_message"
|
||||
]
|
||||
},
|
||||
{
|
||||
"t": 2.28,
|
||||
"utc": "20:30:20.875",
|
||||
"step": "structured API log in Loki",
|
||||
"event": "http.request",
|
||||
"trace_id": "a5395a7a0d14fddbe988dd3fbc8052c3",
|
||||
"span_id": "96d2ff4278525fc6",
|
||||
"severity": "INFO",
|
||||
"service_name": "messenger-api",
|
||||
"line": "POST /api/v1/chats/{chat_id}/messages -> 201 4.7ms request_id=e755c640d7c64606817798996b38e737"
|
||||
},
|
||||
{
|
||||
"t": 2.63,
|
||||
"utc": "20:30:21.223",
|
||||
"step": "upload accepted and ready",
|
||||
"attachment_id": "530ec172-4a69-4d17-b809-7c4f1323c9af",
|
||||
"trace_id": "f257a257a05eb9b2129200a8a2e3763f",
|
||||
"status": "ready"
|
||||
},
|
||||
{
|
||||
"t": 5.78,
|
||||
"utc": "20:30:24.380",
|
||||
"step": "one trace upload -> relay -> worker",
|
||||
"spans": 26,
|
||||
"services": [
|
||||
"messenger-api",
|
||||
"messenger-relay",
|
||||
"messenger-worker"
|
||||
],
|
||||
"job_id": "2febd212-9808-4ff5-bf84-f3e5b6f8a705",
|
||||
"outbox_traceparent": "00-f257a257a05eb9b2129200a8a2e3763f-974c4ff4bf81a0a4-03",
|
||||
"process_parent_is_send": true,
|
||||
"send_parent_is_create": true,
|
||||
"worker_s3_puts": 4,
|
||||
"api_to_worker_gap_ms": 6.8,
|
||||
"process_ms": 146.945,
|
||||
"outcome": "ready"
|
||||
},
|
||||
{
|
||||
"t": 5.8,
|
||||
"utc": "20:30:24.393",
|
||||
"step": "worker structured logs in Loki by trace_id",
|
||||
"events": [
|
||||
"job.claimed",
|
||||
"job.completed"
|
||||
],
|
||||
"job_id": "2febd212-9808-4ff5-bf84-f3e5b6f8a705",
|
||||
"span_id": "daa51e4f3cc7737a",
|
||||
"line": "job 2febd212-9808-4ff5-bf84-f3e5b6f8a705 attempt 1 -> ready in 131ms"
|
||||
},
|
||||
{
|
||||
"t": 9.21,
|
||||
"utc": "20:30:27.803",
|
||||
"step": "no secrets/bodies in telemetry, no ID labels in metrics",
|
||||
"leaks": {
|
||||
"loki:message_text": 0,
|
||||
"loki:password": 0,
|
||||
"loki:token": 0,
|
||||
"loki:filename": 0,
|
||||
"tempo:message_text": 0,
|
||||
"tempo:password": 0,
|
||||
"tempo:token": 0,
|
||||
"tempo:filename": 0
|
||||
},
|
||||
"metric_labels": [
|
||||
"__name__",
|
||||
"db_client_connection_pool_name",
|
||||
"db_client_connection_state",
|
||||
"db_operation_name",
|
||||
"db_system_name",
|
||||
"deployment_environment_name",
|
||||
"error_type",
|
||||
"http_request_method",
|
||||
"http_response_status_class",
|
||||
"http_response_status_code",
|
||||
"http_route",
|
||||
"instance",
|
||||
"job",
|
||||
"le",
|
||||
"messenger_job_outcome",
|
||||
"messenger_job_status",
|
||||
"messenger_job_type",
|
||||
"messenger_s3_operation",
|
||||
"otel_component_name",
|
||||
"otel_component_type",
|
||||
"otel_span_parent_origin",
|
||||
"otel_span_sampling_result",
|
||||
"outcome",
|
||||
"reason",
|
||||
"server_address",
|
||||
"server_port",
|
||||
"service_version",
|
||||
"telemetry_sdk_language",
|
||||
"telemetry_sdk_name",
|
||||
"telemetry_sdk_version"
|
||||
]
|
||||
}
|
||||
],
|
||||
"message_trace_tree": [
|
||||
"POST /api/v1/chats/{chat_id}/messages messenger-api + 0.0ms 5.1ms SERVER",
|
||||
" db get_session_user messenger-api + 0.1ms 0.8ms CLIENT",
|
||||
" db get_chat_for messenger-api + 1.0ms 0.8ms CLIENT",
|
||||
" db add_message messenger-api + 1.9ms 2.3ms CLIENT"
|
||||
],
|
||||
"message": {
|
||||
"request_id": "e755c640d7c64606817798996b38e737",
|
||||
"trace_id": "a5395a7a0d14fddbe988dd3fbc8052c3",
|
||||
"loki_labels": [
|
||||
"code_file_path",
|
||||
"code_function_name",
|
||||
"code_line_number",
|
||||
"deployment_environment_name",
|
||||
"detected_level",
|
||||
"duration_ms",
|
||||
"event",
|
||||
"flags",
|
||||
"http_request_method",
|
||||
"http_response_status_code",
|
||||
"http_route",
|
||||
"observed_timestamp",
|
||||
"request_id",
|
||||
"scope_name",
|
||||
"service_instance_id",
|
||||
"service_name",
|
||||
"service_version",
|
||||
"severity_number",
|
||||
"severity_text",
|
||||
"span_id",
|
||||
"telemetry_sdk_language",
|
||||
"telemetry_sdk_name",
|
||||
"telemetry_sdk_version",
|
||||
"trace_id"
|
||||
]
|
||||
},
|
||||
"upload_trace_tree": [
|
||||
"POST /api/v1/chats/{chat_id}/attachments messenger-api + 0.0ms 15.6ms SERVER",
|
||||
" db get_session_user messenger-api + 0.1ms 1.0ms CLIENT",
|
||||
" db get_chat_for messenger-api + 1.2ms 0.8ms CLIENT",
|
||||
" http.receive_body messenger-api + 2.2ms 0.2ms INTERNAL",
|
||||
" image.validate messenger-api + 2.5ms 0.9ms INTERNAL",
|
||||
" db create_pending_attachment messenger-api + 3.5ms 2.6ms CLIENT",
|
||||
" s3 PutObject messenger-api + 6.2ms 3.3ms CLIENT",
|
||||
" db enqueue_attachment messenger-api + 9.6ms 5.3ms CLIENT",
|
||||
" db jobs.enqueue messenger-api + 10.0ms 3.6ms CLIENT",
|
||||
" attachment.process.v1 create messenger-api + 12.3ms 1.2ms PRODUCER",
|
||||
" attachments send messenger-relay + 16.4ms 3.9ms PRODUCER",
|
||||
" attachments.process.v1 process messenger-worker + 22.3ms 146.9ms CONSUMER",
|
||||
" db jobs.claim messenger-worker + 31.3ms 3.8ms CLIENT",
|
||||
" db jobs.heartbeat messenger-worker + 36.5ms 0.3ms CLIENT",
|
||||
" worker.fetch_staging messenger-worker + 37.3ms 2.4ms INTERNAL",
|
||||
" s3 GetObject messenger-worker + 37.4ms 2.0ms CLIENT",
|
||||
" db jobs.heartbeat messenger-worker + 39.8ms 0.2ms CLIENT",
|
||||
" worker.transform messenger-worker + 40.3ms 117.8ms INTERNAL",
|
||||
" db jobs.heartbeat messenger-worker + 158.4ms 0.3ms CLIENT",
|
||||
" s3 PutObject messenger-worker + 159.2ms 2.4ms CLIENT",
|
||||
" s3 PutObject messenger-worker + 161.7ms 0.8ms CLIENT",
|
||||
" s3 PutObject messenger-worker + 162.6ms 0.8ms CLIENT",
|
||||
" s3 PutObject messenger-worker + 163.5ms 0.8ms CLIENT",
|
||||
" db jobs.heartbeat messenger-worker + 164.7ms 0.3ms CLIENT",
|
||||
" db jobs.complete messenger-worker + 165.3ms 1.6ms CLIENT",
|
||||
" s3 DeleteObject messenger-worker + 167.8ms 0.9ms CLIENT"
|
||||
],
|
||||
"upload": {
|
||||
"attachment_id": "530ec172-4a69-4d17-b809-7c4f1323c9af",
|
||||
"job_id": "2febd212-9808-4ff5-bf84-f3e5b6f8a705",
|
||||
"trace_id": "f257a257a05eb9b2129200a8a2e3763f",
|
||||
"worker_log_events": [
|
||||
"job.claimed",
|
||||
"job.completed"
|
||||
]
|
||||
},
|
||||
"leaks": {
|
||||
"loki:message_text": 0,
|
||||
"loki:password": 0,
|
||||
"loki:token": 0,
|
||||
"loki:filename": 0,
|
||||
"tempo:message_text": 0,
|
||||
"tempo:password": 0,
|
||||
"tempo:token": 0,
|
||||
"tempo:filename": 0
|
||||
},
|
||||
"metric_labels": [
|
||||
"__name__",
|
||||
"db_client_connection_pool_name",
|
||||
"db_client_connection_state",
|
||||
"db_operation_name",
|
||||
"db_system_name",
|
||||
"deployment_environment_name",
|
||||
"error_type",
|
||||
"http_request_method",
|
||||
"http_response_status_class",
|
||||
"http_response_status_code",
|
||||
"http_route",
|
||||
"instance",
|
||||
"job",
|
||||
"le",
|
||||
"messenger_job_outcome",
|
||||
"messenger_job_status",
|
||||
"messenger_job_type",
|
||||
"messenger_s3_operation",
|
||||
"otel_component_name",
|
||||
"otel_component_type",
|
||||
"otel_span_parent_origin",
|
||||
"otel_span_sampling_result",
|
||||
"outcome",
|
||||
"reason",
|
||||
"server_address",
|
||||
"server_port",
|
||||
"service_version",
|
||||
"telemetry_sdk_language",
|
||||
"telemetry_sdk_name",
|
||||
"telemetry_sdk_version"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# message trace a5395a7a0d14fddbe988dd3fbc8052c3
|
||||
POST /api/v1/chats/{chat_id}/messages messenger-api + 0.0ms 5.1ms SERVER
|
||||
db get_session_user messenger-api + 0.1ms 0.8ms CLIENT
|
||||
db get_chat_for messenger-api + 1.0ms 0.8ms CLIENT
|
||||
db add_message messenger-api + 1.9ms 2.3ms CLIENT
|
||||
|
||||
# upload trace f257a257a05eb9b2129200a8a2e3763f
|
||||
POST /api/v1/chats/{chat_id}/attachments messenger-api + 0.0ms 15.6ms SERVER
|
||||
db get_session_user messenger-api + 0.1ms 1.0ms CLIENT
|
||||
db get_chat_for messenger-api + 1.2ms 0.8ms CLIENT
|
||||
http.receive_body messenger-api + 2.2ms 0.2ms INTERNAL
|
||||
image.validate messenger-api + 2.5ms 0.9ms INTERNAL
|
||||
db create_pending_attachment messenger-api + 3.5ms 2.6ms CLIENT
|
||||
s3 PutObject messenger-api + 6.2ms 3.3ms CLIENT
|
||||
db enqueue_attachment messenger-api + 9.6ms 5.3ms CLIENT
|
||||
db jobs.enqueue messenger-api + 10.0ms 3.6ms CLIENT
|
||||
attachment.process.v1 create messenger-api + 12.3ms 1.2ms PRODUCER
|
||||
attachments send messenger-relay + 16.4ms 3.9ms PRODUCER
|
||||
attachments.process.v1 process messenger-worker + 22.3ms 146.9ms CONSUMER
|
||||
db jobs.claim messenger-worker + 31.3ms 3.8ms CLIENT
|
||||
db jobs.heartbeat messenger-worker + 36.5ms 0.3ms CLIENT
|
||||
worker.fetch_staging messenger-worker + 37.3ms 2.4ms INTERNAL
|
||||
s3 GetObject messenger-worker + 37.4ms 2.0ms CLIENT
|
||||
db jobs.heartbeat messenger-worker + 39.8ms 0.2ms CLIENT
|
||||
worker.transform messenger-worker + 40.3ms 117.8ms INTERNAL
|
||||
db jobs.heartbeat messenger-worker + 158.4ms 0.3ms CLIENT
|
||||
s3 PutObject messenger-worker + 159.2ms 2.4ms CLIENT
|
||||
s3 PutObject messenger-worker + 161.7ms 0.8ms CLIENT
|
||||
s3 PutObject messenger-worker + 162.6ms 0.8ms CLIENT
|
||||
s3 PutObject messenger-worker + 163.5ms 0.8ms CLIENT
|
||||
db jobs.heartbeat messenger-worker + 164.7ms 0.3ms CLIENT
|
||||
db jobs.complete messenger-worker + 165.3ms 1.6ms CLIENT
|
||||
s3 DeleteObject messenger-worker + 167.8ms 0.9ms CLIENT
|
||||
@@ -0,0 +1,8 @@
|
||||
[ 0.20s] message sent {"request_id": "e755c640d7c64606817798996b38e737", "trace_id": "a5395a7a0d14fddbe988dd3fbc8052c3", "instance": "r-f7dd6d1932"}
|
||||
[ 2.25s] message trace in Tempo {"spans": 4, "server_ms": 5.068, "db_spans": ["db get_session_user", "db get_chat_for", "db add_message"]}
|
||||
[ 2.28s] structured API log in Loki {"event": "http.request", "trace_id": "a5395a7a0d14fddbe988dd3fbc8052c3", "span_id": "96d2ff4278525fc6", "severity": "INFO", "service_name": "messenger-api", "line": "POST /api/v1/chats/{chat_id}/messages -> 201 4.7ms request_id=e755c640d7c64606817798996b38e737"}
|
||||
[ 2.63s] upload accepted and ready {"attachment_id": "530ec172-4a69-4d17-b809-7c4f1323c9af", "trace_id": "f257a257a05eb9b2129200a8a2e3763f", "status": "ready"}
|
||||
[ 5.78s] one trace upload -> relay -> worker {"spans": 26, "services": ["messenger-api", "messenger-relay", "messenger-worker"], "job_id": "2febd212-9808-4ff5-bf84-f3e5b6f8a705", "outbox_traceparent": "00-f257a257a05eb9b2129200a8a2e3763f-974c4ff4bf81a0a4-03", "process_parent_is_send": true, "send_parent_is_create": true, "worker_s3_puts": 4, "api_to_worker_gap_ms": 6.8, "process_ms": 146.945, "outcome": "ready"}
|
||||
[ 5.80s] worker structured logs in Loki by trace_id {"events": ["job.claimed", "job.completed"], "job_id": "2febd212-9808-4ff5-bf84-f3e5b6f8a705", "span_id": "daa51e4f3cc7737a", "line": "job 2febd212-9808-4ff5-bf84-f3e5b6f8a705 attempt 1 -> ready in 131ms"}
|
||||
[ 9.21s] no secrets/bodies in telemetry, no ID labels in metrics {"leaks": {"loki:message_text": 0, "loki:password": 0, "loki:token": 0, "loki:filename": 0, "tempo:message_text": 0, "tempo:password": 0, "tempo:token": 0, "tempo:filename": 0}, "metric_labels": ["__name__", "db_client_connection_pool_name", "db_client_connection_state", "db_operation_name", "db_system_name", "deployment_environment_name", "error_type", "http_request_method", "http_response_status_class", "http_response_status_code", "http_route", "instance", "job", "le", "messenger_job_outcome", "messenger_job_status", "messenger_job_type", "messenger_s3_operation", "otel_component_name", "otel_component_type", "otel_span_parent_origin", "otel_span_sampling_result", "outcome", "reason", "server_address", "server_port", "service_version", "telemetry_sdk_language", "telemetry_sdk_name", "telemetry_sdk_version"]}
|
||||
PASS: correlation request->trace->log and upload->relay->worker
|
||||
@@ -0,0 +1,16 @@
|
||||
mtusi-lab7-api-1 Up 7 seconds (healthy)
|
||||
mtusi-lab7-api-2 Up 7 seconds (healthy)
|
||||
mtusi-lab7-broker-1 Up 46 seconds (healthy)
|
||||
mtusi-lab7-db-1 Up 47 seconds (healthy)
|
||||
mtusi-lab7-grafana-1 Up 10 seconds (healthy)
|
||||
mtusi-lab7-janitor-1 Up Less than a second (health: starting)
|
||||
mtusi-lab7-lb-1 Up Less than a second (health: starting)
|
||||
mtusi-lab7-loki-1 Up 47 seconds
|
||||
mtusi-lab7-openbao-1 Up 46 seconds (healthy)
|
||||
mtusi-lab7-otel-collector-1 Up 10 seconds
|
||||
mtusi-lab7-prometheus-1 Up 47 seconds (healthy)
|
||||
mtusi-lab7-relay-1 Up 9 seconds (healthy)
|
||||
mtusi-lab7-s3-1 Up 30 seconds (healthy)
|
||||
mtusi-lab7-tempo-1 Up 47 seconds
|
||||
mtusi-lab7-worker-1 Up 9 seconds (healthy)
|
||||
mtusi-lab7-worker-2 Up 9 seconds (healthy)
|
||||
@@ -0,0 +1,16 @@
|
||||
mtusi-lab7-api-1 Up 11 seconds (healthy)
|
||||
mtusi-lab7-api-2 Up 10 seconds (healthy)
|
||||
mtusi-lab7-broker-1 Up 12 minutes (healthy)
|
||||
mtusi-lab7-db-1 Up 8 minutes (healthy)
|
||||
mtusi-lab7-grafana-1 Up 12 minutes (healthy)
|
||||
mtusi-lab7-janitor-1 Up 11 seconds (healthy)
|
||||
mtusi-lab7-lb-1 Up 10 seconds (healthy)
|
||||
mtusi-lab7-loki-1 Up 12 minutes
|
||||
mtusi-lab7-openbao-1 Up 2 minutes (healthy)
|
||||
mtusi-lab7-otel-collector-1 Up 12 minutes
|
||||
mtusi-lab7-prometheus-1 Up 12 minutes (healthy)
|
||||
mtusi-lab7-relay-1 Up 12 seconds (healthy)
|
||||
mtusi-lab7-s3-1 Up 11 minutes (healthy)
|
||||
mtusi-lab7-tempo-1 Up 12 minutes
|
||||
mtusi-lab7-worker-1 Up 11 seconds (healthy)
|
||||
mtusi-lab7-worker-2 Up 10 seconds (healthy)
|
||||
@@ -0,0 +1,7 @@
|
||||
haproxy lb:8404 1
|
||||
loki loki:3100 1
|
||||
otelcol-contrib 00cecf88-3117-40c3-aeeb-1c212dc8d9e3 1
|
||||
prometheus localhost:9090 1
|
||||
rabbitmq broker:15691 1
|
||||
rabbitmq-node broker:15691 1
|
||||
tempo tempo:3200 1
|
||||
@@ -0,0 +1,61 @@
|
||||
== make-check (2026-11-18T20:26:42Z)
|
||||
PASS
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
== make-test (2026-11-18T20:26:42Z)
|
||||
PASS
|
||||
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||
== make-test-security (2026-11-18T20:26:43Z)
|
||||
PASS
|
||||
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||
== lab7-tls-matrix (2026-11-18T20:26:43Z)
|
||||
PASS
|
||||
PASS: 67 checks, 0 failed
|
||||
== lab7-api-security (2026-11-18T20:26:44Z)
|
||||
PASS
|
||||
PASS: 33 checks, 0 failed
|
||||
== lab7-openbao (2026-11-18T20:27:21Z)
|
||||
PASS
|
||||
PASS: 83 checks, 0 failed
|
||||
== lab7-hardening (2026-11-18T20:28:13Z)
|
||||
PASS
|
||||
PASS: 180 checks, 0 failed
|
||||
== test-persistence (2026-11-18T20:28:35Z)
|
||||
PASS
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
== test-failover (2026-11-18T20:29:23Z)
|
||||
PASS
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
Container mtusi-lab7-api-1 Created
|
||||
Container mtusi-lab7-api-2 Running
|
||||
Container mtusi-lab7-worker-1 Running
|
||||
Container mtusi-lab7-worker-2 Running
|
||||
Container mtusi-lab7-api-1 Starting
|
||||
Container mtusi-lab7-api-1 Started
|
||||
Container mtusi-lab7-worker-2 Waiting
|
||||
Container mtusi-lab7-worker-1 Waiting
|
||||
Container mtusi-lab7-api-1 Waiting
|
||||
Container mtusi-lab7-api-2 Waiting
|
||||
Container mtusi-lab7-worker-2 Healthy
|
||||
Container mtusi-lab7-worker-1 Healthy
|
||||
Container mtusi-lab7-api-1 Healthy
|
||||
Container mtusi-lab7-api-2 Healthy
|
||||
== load (2026-11-18T20:29:45Z)
|
||||
PASS
|
||||
}
|
||||
== scan-secrets (2026-11-18T20:30:15Z)
|
||||
PASS
|
||||
checked 125 secret values from 50 files; files with leaks: none
|
||||
== check-rules (2026-11-18T20:30:15Z)
|
||||
PASS
|
||||
dashboard OK
|
||||
== obs-correlation (2026-11-18T20:30:18Z)
|
||||
PASS
|
||||
PASS: correlation request->trace->log and upload->relay->worker
|
||||
== dashboard-check (2026-11-18T20:30:27Z)
|
||||
PASS
|
||||
{"dashboard": {"uid": "messenger-overview", "title": "Messenger — наблюдаемость (lab6)", "provisioned": true, "folder": "Messenger", "panels": 56}, "datasource_health": {"prometheus": "OK", "loki": "OK", "tempo": "OK"}, "query_errors": [], "empty_required_panels": [], "pass": true}
|
||||
== worker-outage (2026-11-18T20:31:09Z)
|
||||
PASS
|
||||
PASS: worker outage, api+broker restart, ready, duplicate delivery no-op
|
||||
== done: ALL PASS
|
||||
EXIT=0
|
||||
@@ -0,0 +1 @@
|
||||
checked 125 secret values from 50 files; files with leaks: none
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/Users/uralazarev/Documents/mtusi2026lab7/secrets/pki/public-ca.crt"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 126, "failed_attempts": 0, "first_recovery_seconds": 4.001}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,3 @@
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://localhost:8443" --ca-file "/Users/uralazarev/Documents/mtusi2026lab7/secrets/pki/public-ca.crt"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,11 @@
|
||||
[ 1.70s] worker stopped {"running": []}
|
||||
[ 2.27s] upload while worker is down {"http": 202, "attachment_id": "9628fe62-37bf-4db1-b0a6-304909aba2fd", "status": "queued"}
|
||||
[ 2.30s] metadata and content while queued {"status": "queued", "content": 409, "thumbnail": 409, "error_code": "conflict"}
|
||||
[ 2.31s] messages while worker is down {"with_queued_attachment": true, "plain_message_id": "4c5ed20e-1101-48b2-b823-e2f7bac51602"}
|
||||
[ 7.54s] job is durable in broker {"queue": {"messages": 1, "messages_ready": 1, "messages_unacknowledged": 0, "consumers": 0}, "outbox_published": true, "job_id": "e81a051a-a685-43c4-95f9-0ae1fb1b7027", "job_status": "queued"}
|
||||
[ 17.67s] api restarted {"status": "queued"}
|
||||
[ 26.89s] broker restarted with volume {"queue": {"messages": 1, "messages_ready": 1, "messages_unacknowledged": 0, "consumers": 0}, "status": "queued"}
|
||||
[ 32.84s] worker started
|
||||
[ 32.90s] ready after worker start {"variants": [["thumbnail", 256, 160], ["crop", 128, 128], ["optimized", 320, 200]], "original_sha256_ok": true, "thumbnail_bytes": 4679}
|
||||
[ 35.21s] redelivery of the same job is a no-op {"events": ["enqueued", "claimed", "ready", "staging_deleted", "duplicate_ignored"], "invariants": {"variants": ["crop", "optimized", "thumbnail"], "variants_ok": true, "final_objects": 4, "final_objects_ok": true, "staging_left": false, "job_status": "ready", "attempt": 1}}
|
||||
PASS: worker outage, api+broker restart, ready, duplicate delivery no-op
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,15 @@
|
||||
# Dashboards из Git: infra/grafana/dashboards/*.json монтируются в /var/lib/grafana/dashboards.
|
||||
# allowUiUpdates: false — источник истины JSON в репозитории (генератор: scripts/build_dashboard.py).
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: messenger
|
||||
orgId: 1
|
||||
folder: Messenger
|
||||
folderUid: messenger
|
||||
type: file
|
||||
disableDeletion: true
|
||||
allowUiUpdates: false
|
||||
updateIntervalSeconds: 30
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
foldersFromFilesStructure: false
|
||||
@@ -0,0 +1,103 @@
|
||||
# Grafana datasources (provisioning, применяется при старте; правки в UI не сохраняются).
|
||||
# Grafana — интерфейс и запросы к хранилищам, сама сигналы не хранит.
|
||||
# Связи сигналов: метрика (exemplar trace_id) -> Tempo; лог (structured metadata trace_id) -> Tempo;
|
||||
# span -> логи Loki того же trace_id; span -> метрики Prometheus по service.name.
|
||||
# В provisioning `$` пишется как `$$` (иначе Grafana подставит переменную окружения).
|
||||
# Lab7: все datasources — HTTPS с проверкой internal-ca и SAN (serverName) и client cert grafana
|
||||
# (identity только для чтения; Prometheus/Loki/Tempo требуют client cert). Ключ — $__file{} из
|
||||
# Docker secret, в provisioning/Git его нет.
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: https://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
secureJsonData:
|
||||
tlsCACert: $__file{/run/secrets/internal-ca.crt}
|
||||
tlsClientCert: $__file{/run/secrets/service.crt}
|
||||
tlsClientKey: $__file{/run/secrets/service.key}
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
serverName: prometheus
|
||||
httpMethod: POST
|
||||
timeInterval: 15s
|
||||
prometheusType: Prometheus
|
||||
exemplarTraceIdDestinations:
|
||||
- name: trace_id
|
||||
datasourceUid: tempo
|
||||
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: https://loki:3100
|
||||
editable: false
|
||||
secureJsonData:
|
||||
tlsCACert: $__file{/run/secrets/internal-ca.crt}
|
||||
tlsClientCert: $__file{/run/secrets/service.crt}
|
||||
tlsClientKey: $__file{/run/secrets/service.key}
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
serverName: loki
|
||||
maxLines: 1000
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: tempo
|
||||
url: "$${__value.raw}"
|
||||
urlDisplayLabel: "Trace в Tempo"
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: https://tempo:3200
|
||||
editable: false
|
||||
secureJsonData:
|
||||
tlsCACert: $__file{/run/secrets/internal-ca.crt}
|
||||
tlsClientCert: $__file{/run/secrets/service.crt}
|
||||
tlsClientKey: $__file{/run/secrets/service.key}
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
serverName: tempo
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: "-5m"
|
||||
spanEndTimeShift: "5m"
|
||||
filterByTraceID: true
|
||||
filterBySpanID: false
|
||||
customQuery: false
|
||||
tags:
|
||||
- key: service.name
|
||||
value: service_name
|
||||
tracesToMetrics:
|
||||
datasourceUid: prometheus
|
||||
spanStartTimeShift: "-10m"
|
||||
spanEndTimeShift: "10m"
|
||||
tags:
|
||||
- key: service.name
|
||||
value: job
|
||||
queries:
|
||||
- name: "HTTP p95 по маршруту"
|
||||
query: 'histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{$$__tags}[5m])))'
|
||||
nodeGraph:
|
||||
enabled: true
|
||||
search:
|
||||
hide: false
|
||||
lokiSearch:
|
||||
datasourceUid: loki
|
||||
traceQuery:
|
||||
timeShiftEnabled: true
|
||||
spanStartTimeShift: "-30m"
|
||||
spanEndTimeShift: "30m"
|
||||
@@ -0,0 +1,122 @@
|
||||
# Lab3/4/6/7: единая точка входа перед API-репликами.
|
||||
#
|
||||
# Lab7: снаружи только HTTPS :8443 (сертификат public-ca, SAN localhost/127.0.0.1). LB -> каждая
|
||||
# API-реплика: mTLS — LB предъявляет identity `lb` (internal-ca), сам проверяет сертификат API
|
||||
# (internal-ca + SAN api). Readiness-проверки идут тем же mTLS-каналом. Plaintext до API нет.
|
||||
#
|
||||
# Lab4: upload вложений — тело идёт потоком (без http-buffer-request); для upload timeout server
|
||||
# увеличен до 75 с (> UPLOAD_TIMEOUT_SECONDS=60 у API + запись в S3). Content-Length
|
||||
# больше лимита API отклоняет сам, не читая тело.
|
||||
#
|
||||
# Обнаружение реплик: DNS Docker (127.0.0.11) отдаёт по имени сервиса `api` адреса
|
||||
# ВСЕХ его контейнеров; server-template создаёт до 8 слотов и заполняет их по DNS.
|
||||
# Поэтому `docker compose up --scale api=N` не требует правки конфигурации.
|
||||
#
|
||||
# Readiness: активная проверка GET /health/ready каждую 1 с; 2 неудачи подряд -> DOWN,
|
||||
# 2 успеха -> UP. Максимальное время обнаружения отказа:
|
||||
# inter(1s) + timeout check(1s) + fastinter(0.5s) + timeout check(1s) ~= 3.5 с;
|
||||
# ready=503 или refused без ожидания таймаута -> ~1.5 с.
|
||||
# Sticky sessions НЕ используются: balance roundrobin без cookie/stick-table для backend
|
||||
# (stick-table во frontend считает только частоту входов по IP, на выбор реплики не влияет).
|
||||
#
|
||||
# Перегрузка: maxconn 10 на реплику (= DB_POOL_SIZE) — лишние запросы ждут в очереди LB
|
||||
# (timeout queue 5s), а не плодят потоки внутри Python-процесса. Переполнение -> 503 JSON.
|
||||
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 4096
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||||
ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
|
||||
ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||||
# Без кэша TLS-сессий к backend: каждое новое соединение с API — полный handshake с проверкой.
|
||||
tune.ssl.cachesize 0
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 2s
|
||||
hold other 2s
|
||||
hold refused 2s
|
||||
hold nx 2s
|
||||
hold timeout 2s
|
||||
hold obsolete 2s
|
||||
accepted_payload_size 8192
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option dontlognull
|
||||
# Внутри одного Docker-host соединение устанавливается за доли мс: 500 мс хватает с запасом,
|
||||
# а при внезапно исчезнувшей реплике запрос быстро уходит в retry на другую.
|
||||
timeout connect 500ms
|
||||
timeout client 30s
|
||||
timeout server 10s
|
||||
timeout http-request 10s
|
||||
timeout http-keep-alive 5s
|
||||
timeout queue 5s
|
||||
timeout check 1s
|
||||
# Повтор только если соединение с backend НЕ установлено (запрос точно не дошёл
|
||||
# до приложения) — это безопасно даже для неидемпотентных POST. Повтор уходит
|
||||
# на другую реплику (redispatch). Ответы/таймауты после отправки не повторяются.
|
||||
retries 2
|
||||
retry-on conn-failure
|
||||
option redispatch 1
|
||||
|
||||
# Ошибки, которые формирует сам HAProxy (нет живых реплик, обрыв backend, timeout,
|
||||
# переполнение очереди), отдаются в общем JSON-формате ошибки контракта, а не HTML.
|
||||
# Ответы приложения (в т.ч. его 503) эти правила не затрагивают.
|
||||
unique-id-format %[uuid()]
|
||||
http-error status 400 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"invalid_request","message":"Неверный запрос","request_id":"%ID"}}'
|
||||
http-error status 408 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"invalid_request","message":"Запрос не получен вовремя","request_id":"%ID"}}'
|
||||
http-error status 413 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"payload_too_large","message":"Файл больше допустимого размера","request_id":"%ID"}}'
|
||||
http-error status 429 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "10" lf-string '{"error":{"code":"rate_limited","message":"Слишком много запросов, повторите позже","request_id":"%ID"}}'
|
||||
http-error status 500 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"internal_error","message":"Внутренняя ошибка сервера","request_id":"%ID"}}'
|
||||
http-error status 502 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "1" lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%ID"}}'
|
||||
http-error status 503 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "1" lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%ID"}}'
|
||||
http-error status 504 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "1" lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%ID"}}'
|
||||
|
||||
frontend fe_api
|
||||
bind :8443 ssl crt /run/secrets/lb-public.pem alpn http/1.1
|
||||
http-response set-header Strict-Transport-Security "max-age=31536000"
|
||||
# Ответ не раскрывает внутренние адреса/версии LB.
|
||||
http-response del-header Server
|
||||
# X-Request-Id формирует само приложение; LB только пробрасывает адрес клиента.
|
||||
option forwardfor
|
||||
# Защита входа от перебора паролей и шторма scrypt: не более LOGIN_RATE_LIMIT
|
||||
# попыток POST /auth/sessions за 10 с с одного IP, сверх — 429 rate_limited.
|
||||
stick-table type ip size 100k expire 60s store http_req_rate(10s)
|
||||
acl is_login method POST
|
||||
acl is_login_path path /api/v1/auth/sessions
|
||||
# Явно вычисляем unique-id до deny: иначе в ответе 429 request_id остаётся пустым.
|
||||
http-request set-var(txn.request_id) unique-id
|
||||
http-request track-sc0 src if is_login is_login_path
|
||||
http-request deny deny_status 429 if is_login is_login_path { sc_http_req_rate(0) gt "${LOGIN_RATE_LIMIT}" }
|
||||
# Lab4: лимит размера upload проверяет API по Content-Length ДО чтения тела (ответ 413
|
||||
# с X-Instance-Id по контракту). Дублирующий deny на LB убран: его ответ без X-Instance-Id.
|
||||
default_backend be_api
|
||||
|
||||
backend be_api
|
||||
balance roundrobin
|
||||
http-request set-timeout server 75s if METH_POST { path_reg ^/api/v1/chats/[^/]+/attachments$ }
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host lb
|
||||
http-check expect status 200
|
||||
# on-marked-down shutdown-sessions НЕ используется: при штатной остановке реплика ещё
|
||||
# дообслуживает начатые запросы (drain), и обрыв их сессий дал бы лишние 502.
|
||||
default-server maxconn 10 check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr libc,none ssl verify required ca-file /run/secrets/internal-ca.crt verifyhost api sni str(api) check-sni api crt /run/secrets/lb.pem alpn http/1.1 no-ssl-reuse
|
||||
server-template api 8 api:8443
|
||||
|
||||
# Статистика LB и /metrics: только сеть telemetry, HTTPS с обязательным client cert internal-ca
|
||||
# (Prometheus). Наружу (на хост) не публикуется.
|
||||
frontend stats
|
||||
bind :8404 ssl crt /run/secrets/lb.pem ca-file /run/secrets/internal-ca.crt verify required
|
||||
# Lab6: встроенный Prometheus-экспортёр HAProxy (USE_PROMEX) — снимает Prometheus по сети telemetry.
|
||||
http-request use-service prometheus-exporter if { path /metrics }
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 2s
|
||||
stats show-legends
|
||||
@@ -0,0 +1,81 @@
|
||||
# Loki (grafana/loki:3.6.19) — хранилище ЛОГОВ, монолитный режим, файловая система (volume lokidata).
|
||||
# Приём: нативный OTLP /otlp/v1/logs от Collector. Индексные labels — только ресурсные
|
||||
# service.name, service.instance.id, deployment.environment.name (низкая кардинальность).
|
||||
# Атрибуты записи (event, request_id, trace_id, span_id, http.route, ...) хранятся как
|
||||
# structured metadata: по ним можно фильтровать, но они не раздувают индекс.
|
||||
auth_enabled: false
|
||||
|
||||
# Lab7: HTTP :3100 (OTLP-приём от Collector, запросы Grafana, scrape Prometheus) — только TLS
|
||||
# с обязательным client cert internal-ca. Внутренний gRPC (querier <-> frontend одного процесса)
|
||||
# слушает только 127.0.0.1 контейнера.
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
grpc_listen_address: 127.0.0.1
|
||||
grpc_listen_port: 9095
|
||||
http_tls_config:
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
client_auth_type: RequireAndVerifyClientCert
|
||||
client_ca_file: /run/secrets/internal-ca.crt
|
||||
log_level: warn
|
||||
|
||||
common:
|
||||
instance_addr: 127.0.0.1
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
|
||||
# WAL ингестера — явно на volume: логи, ещё не сброшенные в chunks, переживают рестарт Loki.
|
||||
ingester:
|
||||
wal:
|
||||
enabled: true
|
||||
dir: /loki/wal
|
||||
flush_on_shutdown: true
|
||||
chunk_idle_period: 5m
|
||||
max_chunk_age: 1h
|
||||
|
||||
schema_config:
|
||||
configs:
|
||||
- from: "2024-04-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
|
||||
max_query_lookback: 168h
|
||||
reject_old_samples: true
|
||||
reject_old_samples_max_age: 24h
|
||||
volume_enabled: true
|
||||
otlp_config:
|
||||
resource_attributes:
|
||||
attributes_config:
|
||||
- action: index_label
|
||||
attributes:
|
||||
- deployment.environment.name
|
||||
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
|
||||
pattern_ingester:
|
||||
enabled: false
|
||||
|
||||
ruler:
|
||||
enable_api: false
|
||||
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
+61
-1
@@ -1,7 +1,67 @@
|
||||
# OpenBao — реализовать конфигурацию и политики
|
||||
# OpenBao — конфигурация, политики и процедуры оператора (lab7)
|
||||
|
||||
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
|
||||
|
||||
## Что здесь лежит
|
||||
|
||||
| Файл | Назначение |
|
||||
| --- | --- |
|
||||
| [openbao.hcl](openbao.hcl) | Сервер **не в dev-mode**: integrated storage Raft (одна нода) на volume `baodata`, TLS-listener `0.0.0.0:8200` (сертификат `openbao` от internal-ca, TLS ≥ 1.2, клиентский сертификат запрашивается для auth/cert), кластерный адрес только `127.0.0.1:8201`, декларативный audit device → stdout (значения HMAC) |
|
||||
| [policies/messenger-<svc>.hcl](policies/) | По одной policy на сервис: `read` **только** `kv/data/messenger/<svc>`. Без list/metadata, без записи, без `sys/*`. Широкого `path "*"` нет |
|
||||
| ../../scripts/bao-init.sh | Операторский bootstrap (идемпотентный): init → unseal → KV v2 `kv/` → policies → роли `auth/cert/certs/<svc>` → запись `kv/messenger/<svc>` |
|
||||
| ../../scripts/bao-unseal.sh | Операторский unseal после рестарта (2 из 3 shares) |
|
||||
|
||||
Почему Raft, а не file: в OpenBao 2.7 file storage удалён (`unknown storage type file`). Почему без mlock: в OpenBao 2.7 параметр убран; swap в Docker Desktop VM отключён, а контейнер работает без `IPC_LOCK` (cap_drop ALL).
|
||||
|
||||
## Аутентификация сервисов — auth/cert
|
||||
|
||||
Identity сервиса — его leaf-сертификат internal-ca (тот же, что для mTLS). Роль на каждый сервис:
|
||||
|
||||
```
|
||||
auth/cert/certs/<svc>: certificate=internal-ca.crt allowed_dns_sans=<svc> token_policies=messenger-<svc>
|
||||
token_type=service token_ttl=15m token_max_ttl=1h (migrate, s3-init: 5m / 10m)
|
||||
```
|
||||
|
||||
Сертификат того же CA, но с другим SAN (например `intruder` или `lb`) не подходит ни под одну чужую роль → `400`. В процессе нет root token, `BAO_TOKEN`, SecretID: bootstrap trust = `internal-ca.crt` + собственный ключ (Docker secret). Клиент: [src/vault.py](../../src/vault.py) — login, чтение KV v2, renew-self на ½ TTL, при неудаче — повторный login и перечитывание KV; при недоступном OpenBao работающий процесс сохраняет значения в памяти.
|
||||
|
||||
| Сервис | KV-путь | Поля |
|
||||
| --- | --- | --- |
|
||||
| api | `kv/messenger/api` | `POSTGRES_PASSWORD` (роль api_svc), `S3_ACCESS_KEY_ID/SECRET` (ключ api) |
|
||||
| worker | `kv/messenger/worker` | пароль worker_svc, ключ S3 worker, `BROKER_URL` (пользователь worker, amqps) |
|
||||
| relay | `kv/messenger/relay` | пароль relay_svc, `BROKER_URL` (пользователь relay) |
|
||||
| janitor | `kv/messenger/janitor` | пароль janitor_svc, ключ S3 janitor (List+Write) |
|
||||
| migrate | `kv/messenger/migrate` | пароль суперпользователя `postgres` и пароли всех сервисных ролей (job выставляет их ролям) |
|
||||
| s3-init | `kv/messenger/s3-init` | ключ S3 admin (только создание bucket) |
|
||||
| ops | `kv/messenger/ops` | пароль ops_svc, `BROKER_URL` ops, ключ S3 janitor |
|
||||
|
||||
## Процедуры оператора
|
||||
|
||||
**Первый запуск (новый volume `baodata`):**
|
||||
|
||||
```sh
|
||||
./scripts/init-secrets.sh # пароли + PKI (CA keys -> $OPERATOR_DIR/ca)
|
||||
./scripts/bao-init.sh # init (3 shares, порог 2) -> $OPERATOR_DIR/openbao/init.json; unseal; policies; роли; KV
|
||||
docker compose --env-file .env up -d --build --wait
|
||||
```
|
||||
|
||||
`$OPERATOR_DIR` по умолчанию `~/.mtusi2026lab7-operator` (700, файлы 600, вне проекта, в контейнеры не монтируется). Скрипт ничего секретного не печатает; root token передаётся только через env процесса `docker compose exec -e BAO_TOKEN`, shares и значения KV — через stdin.
|
||||
|
||||
**После рестарта OpenBao** (рестарт контейнера/хоста, `scripts/restart.sh`): процесс стартует **sealed**, healthcheck `bao status` → unhealthy.
|
||||
|
||||
```sh
|
||||
./scripts/bao-unseal.sh
|
||||
```
|
||||
|
||||
Обычный рестарт API/worker unseal не требует. Пока OpenBao sealed: уже работающие процессы обслуживают запросы; новые ждут (не ready) до 300 с, затем выходят и перезапускаются Docker.
|
||||
|
||||
**Изменить секрет/policy/роль:** поправить `secrets/…` или `policies/*.hcl` → `./scripts/bao-init.sh` (перезапишет) → для паролей ролей БД `docker compose up migrate` → пересоздать затронутый сервис.
|
||||
|
||||
**Отозвать identity сервиса:** с root token (`BAO_TOKEN` из init.json в env): `bao delete auth/cert/certs/<svc>`, `bao token revoke -mode=path auth/cert/login`.
|
||||
|
||||
**Потеря volume `baodata`:** все KV пропадут; заново `bao-init.sh` (init.json придётся удалить вручную — скрипт отказывается перезаписывать материал оператора), значения восстанавливаются из `secrets/`.
|
||||
|
||||
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
|
||||
|
||||
Проверка: `python3 student-tests/lab7_openbao.py` ([evidence/lab7-openbao.json](../../evidence/lab7-openbao.json)) и [src/selfcheck.py](../../src/selfcheck.py), запускаемый внутри каждого сервиса под его identity.
|
||||
|
||||
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# OpenBao 2.7.2 — НЕ dev-mode. Integrated storage (Raft, одна нода) на volume baodata: данные
|
||||
# переживают рестарт; после каждого старта процесс sealed до unseal оператором (scripts/bao-unseal.sh).
|
||||
# (file storage в OpenBao 2.7 удалён; mlock не используется — swap в Docker VM выключен, см. REPORT.md.)
|
||||
ui = false
|
||||
api_addr = "https://openbao:8200"
|
||||
# Кластерный канал Raft не нужен одной ноде: слушает только loopback контейнера.
|
||||
cluster_addr = "https://127.0.0.1:8201"
|
||||
log_level = "info"
|
||||
default_lease_ttl = "1h"
|
||||
max_lease_ttl = "4h"
|
||||
|
||||
storage "raft" {
|
||||
path = "/openbao/file"
|
||||
node_id = "openbao-1"
|
||||
}
|
||||
|
||||
# Единственный listener — TLS 1.2+ с сертификатом internal-ca (SAN openbao/localhost).
|
||||
# tls_client_ca_file: сервер ЗАПРАШИВАЕТ клиентский сертификат (не требует — оператору внутри
|
||||
# контейнера он не нужен); метод auth/cert проверяет его цепочку и SAN по роли.
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
cluster_address = "127.0.0.1:8201"
|
||||
tls_cert_file = "/run/secrets/service.crt"
|
||||
tls_key_file = "/run/secrets/service.key"
|
||||
tls_client_ca_file = "/run/secrets/internal-ca.crt"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
|
||||
# Аудит (OpenBao 2.7: только декларативно в конфиге). В stdout -> docker logs. Значения
|
||||
# токенов/секретов в записях аудита — HMAC, не plaintext.
|
||||
audit "file" "stdout" {
|
||||
description = "audit to container stdout"
|
||||
options {
|
||||
file_path = "stdout"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Policy сервиса api: ТОЛЬКО чтение своего секрета KV v2 (mount kv/, путь messenger/api).
|
||||
# Нет list/metadata, нет записи, нет sys/*, нет чужих путей. renew-self/lookup-self даёт default.
|
||||
path "kv/data/messenger/api" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Policy сервиса janitor: ТОЛЬКО чтение своего секрета KV v2 (mount kv/, путь messenger/janitor).
|
||||
# Нет list/metadata, нет записи, нет sys/*, нет чужих путей. renew-self/lookup-self даёт default.
|
||||
path "kv/data/messenger/janitor" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Policy сервиса migrate: ТОЛЬКО чтение своего секрета KV v2 (mount kv/, путь messenger/migrate).
|
||||
# Нет list/metadata, нет записи, нет sys/*, нет чужих путей. renew-self/lookup-self даёт default.
|
||||
path "kv/data/messenger/migrate" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Policy сервиса ops: ТОЛЬКО чтение своего секрета KV v2 (mount kv/, путь messenger/ops).
|
||||
# Нет list/metadata, нет записи, нет sys/*, нет чужих путей. renew-self/lookup-self даёт default.
|
||||
path "kv/data/messenger/ops" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Policy сервиса relay: ТОЛЬКО чтение своего секрета KV v2 (mount kv/, путь messenger/relay).
|
||||
# Нет list/metadata, нет записи, нет sys/*, нет чужих путей. renew-self/lookup-self даёт default.
|
||||
path "kv/data/messenger/relay" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Policy сервиса s3-init: ТОЛЬКО чтение своего секрета KV v2 (mount kv/, путь messenger/s3-init).
|
||||
# Нет list/metadata, нет записи, нет sys/*, нет чужих путей. renew-self/lookup-self даёт default.
|
||||
path "kv/data/messenger/s3-init" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Policy сервиса worker: ТОЛЬКО чтение своего секрета KV v2 (mount kv/, путь messenger/worker).
|
||||
# Нет list/metadata, нет записи, нет sys/*, нет чужих путей. renew-self/lookup-self даёт default.
|
||||
path "kv/data/messenger/worker" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -5,3 +5,18 @@
|
||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
||||
|
||||
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
|
||||
|
||||
## Решение lab7
|
||||
|
||||
- [collector.yaml](collector.yaml): приём только OTLP/HTTPS `:4318` с **обязательным** client cert internal-ca
|
||||
(`client_ca_file`); gRPC 4317 выключен; собственные метрики (`127.0.0.1:8888`) и `health_check`
|
||||
(`127.0.0.1:13133`) — только loopback, метрики Collector попадают в Prometheus через receiver
|
||||
`prometheus/self` и общий pipeline (job `otelcol-contrib`).
|
||||
- Экспорт: Tempo OTLP gRPC, Loki `/otlp`, Prometheus `/api/v1/otlp` — TLS с проверкой CA и
|
||||
`server_name_override`, client cert `otel-collector` (backends требуют его).
|
||||
- Scrub (`transform/scrub`): Authorization/Cookie/url.query/параметры SQL и всё похожее на
|
||||
password/secret/token удаляется из атрибутов spans/логов, Bearer/Basic в теле лога маскируются.
|
||||
- Prometheus — [web.yml](../prometheus/web.yml) (`RequireAndVerifyClientCert`), scrape только HTTPS;
|
||||
Loki/Tempo — `server.http_tls_config` + внутренний gRPC на 127.0.0.1; Grafana datasources —
|
||||
HTTPS + client cert `grafana` (`$__file{}` из Docker secret). Проверка: `scripts/check_rules.sh`,
|
||||
`student-tests/lab7_tls_matrix.py`, `student-tests/dashboard_check.py`.
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
# OpenTelemetry Collector (otel/opentelemetry-collector-contrib:0.163.2) — получатель, обработчик
|
||||
# и экспортёр телеметрии. Долговременно ничего не хранит: буфер только в памяти и ограничен.
|
||||
#
|
||||
# API/relay/worker/janitor --OTLP/HTTP :4318--> receivers.otlp
|
||||
# -> memory_limiter (первым: отказ приёма при давлении памяти, а не OOM)
|
||||
# -> resource/lab, transform/scrub (защита в глубину от секретов в атрибутах)
|
||||
# -> batch
|
||||
# -> exporters: traces -> Tempo (OTLP gRPC), logs -> Loki (/otlp), metrics -> Prometheus (/api/v1/otlp)
|
||||
#
|
||||
# Поведение при недоступном backend: у каждого экспортёра своя ограниченная очередь
|
||||
# (sending_queue.queue_size батчей, в памяти) и retry с экспоненциальной паузой до 60 с.
|
||||
# Переполнение очереди или исчерпание retry = потеря данных, она считается в собственных
|
||||
# метриках Collector (otelcol_exporter_enqueue_failed_*, otelcol_exporter_send_failed_*),
|
||||
# которые Prometheus снимает с :8888. Приложение от этого не зависит: SDK отправляет асинхронно.
|
||||
# Lab7 (TLS/mTLS):
|
||||
# * приём OTLP/HTTPS :4318 — TLS 1.2+, сертификат otel-collector (internal-ca) и ОБЯЗАТЕЛЬНЫЙ
|
||||
# клиентский сертификат internal-ca (client_ca_file): без него произвольный ingest невозможен;
|
||||
# OTLP gRPC :4317 выключен (приложения его не используют — меньше поверхность);
|
||||
# * экспорт в Tempo/Loki/Prometheus — TLS с проверкой CA+SAN и client cert otel-collector (mTLS);
|
||||
# * собственные метрики Collector (:8888) слушают только 127.0.0.1 контейнера и забираются
|
||||
# receiver-ом prometheus/self -> общий pipeline -> Prometheus по mTLS (раньше Prometheus
|
||||
# скрейпил :8888 по plaintext); health_check — тоже 127.0.0.1.
|
||||
# На хост ничего не публикуется.
|
||||
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 127.0.0.1:13133
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
max_request_body_size: 8388608 # 8 MiB на запрос экспорта
|
||||
tls:
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
client_ca_file: /run/secrets/internal-ca.crt
|
||||
min_version: "1.2"
|
||||
|
||||
# Собственная телеметрия Collector с loopback (job/instance сохраняются как labels в Prometheus).
|
||||
prometheus/self:
|
||||
config:
|
||||
scrape_configs:
|
||||
- job_name: otel-collector
|
||||
scrape_interval: 15s
|
||||
static_configs:
|
||||
- targets: ["127.0.0.1:8888"]
|
||||
|
||||
processors:
|
||||
# Мягкий предел 150 MiB (limit - spike), жёсткий 190 MiB при лимите контейнера 256 MiB
|
||||
# и GOMEMLIMIT 200MiB. Выше мягкого — receiver отвечает ошибкой (SDK повторит/отбросит).
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 190
|
||||
spike_limit_mib: 40
|
||||
|
||||
resource/lab:
|
||||
attributes:
|
||||
- key: deployment.environment.name
|
||||
value: lab
|
||||
action: insert
|
||||
|
||||
# Атрибуты, которых в нашей телеметрии быть не должно. Код их не пишет; процессор гарантирует,
|
||||
# что случайно добавленный заголовок/секрет не дойдёт до хранилищ.
|
||||
transform/scrub:
|
||||
error_mode: ignore
|
||||
trace_statements:
|
||||
- delete_key(span.attributes, "http.request.header.authorization")
|
||||
- delete_key(span.attributes, "http.request.header.cookie")
|
||||
- delete_key(span.attributes, "url.query")
|
||||
- delete_key(span.attributes, "db.query.parameters")
|
||||
- delete_matching_keys(span.attributes, "(?i).*(password|secret|token|authorization).*")
|
||||
log_statements:
|
||||
- delete_key(log.attributes, "http.request.header.authorization")
|
||||
- delete_key(log.attributes, "url.query")
|
||||
- delete_matching_keys(log.attributes, "(?i).*(password|secret|token|authorization).*")
|
||||
- replace_pattern(log.body, "(?i)(bearer|basic)\\s+[A-Za-z0-9._~+/=-]{6,}", "$$1 [REDACTED]")
|
||||
|
||||
batch:
|
||||
send_batch_size: 512
|
||||
send_batch_max_size: 1024
|
||||
timeout: 1s
|
||||
|
||||
exporters:
|
||||
otlp_grpc/tempo:
|
||||
endpoint: tempo:4317
|
||||
tls:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name_override: tempo
|
||||
min_version: "1.2"
|
||||
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: 60s
|
||||
|
||||
otlp_http/loki:
|
||||
endpoint: https://loki:3100/otlp
|
||||
tls:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name_override: loki
|
||||
min_version: "1.2"
|
||||
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: 60s
|
||||
|
||||
otlp_http/prometheus:
|
||||
endpoint: https://prometheus:9090/api/v1/otlp
|
||||
tls:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name_override: prometheus
|
||||
min_version: "1.2"
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 50
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
telemetry:
|
||||
logs:
|
||||
level: info
|
||||
encoding: json
|
||||
metrics:
|
||||
level: normal
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 127.0.0.1
|
||||
port: 8888
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource/lab, transform/scrub, batch]
|
||||
exporters: [otlp_grpc/tempo]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource/lab, transform/scrub, batch]
|
||||
exporters: [otlp_http/loki]
|
||||
metrics:
|
||||
receivers: [otlp, prometheus/self]
|
||||
processors: [memory_limiter, resource/lab, batch]
|
||||
exporters: [otlp_http/prometheus]
|
||||
@@ -0,0 +1,12 @@
|
||||
# Lab7: только TLS. Локальный сокет внутри контейнера — peer (ОС-пользователь postgres = роль
|
||||
# postgres: initdb-скрипты образа, pg_isready, оператор через docker compose exec).
|
||||
# TYPE DATABASE USER ADDRESS METHOD
|
||||
local all postgres peer
|
||||
local all all reject
|
||||
# Сеть: только hostssl + SCRAM-SHA-256. Любое подключение без TLS отвергается.
|
||||
hostssl messenger postgres 0.0.0.0/0 scram-sha-256
|
||||
hostssl messenger api_svc,worker_svc,relay_svc,janitor_svc,ops_svc 0.0.0.0/0 scram-sha-256
|
||||
hostnossl all all 0.0.0.0/0 reject
|
||||
hostnossl all all ::/0 reject
|
||||
host all all 0.0.0.0/0 reject
|
||||
host all all ::/0 reject
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
# Lab7: PostgreSQL требует, чтобы ключ TLS принадлежал postgres (или root) с правами 0600/0640,
|
||||
# а Docker secret — bind mount с правами хоста. Копируем сертификат/ключ в tmpfs /run/pgtls с
|
||||
# нужными правами (выполняется root-ом entrypoint-а, затем образ сам переходит на uid postgres).
|
||||
set -eu
|
||||
install -d -m 0700 -o postgres -g postgres /run/pgtls
|
||||
install -m 0600 -o postgres -g postgres /run/secrets/service.key /run/pgtls/server.key
|
||||
install -m 0644 -o postgres -g postgres /run/secrets/service.crt /run/pgtls/server.crt
|
||||
exec docker-entrypoint.sh postgres \
|
||||
-c ssl=on \
|
||||
-c ssl_cert_file=/run/pgtls/server.crt \
|
||||
-c ssl_key_file=/run/pgtls/server.key \
|
||||
-c ssl_min_protocol_version=TLSv1.2 \
|
||||
-c password_encryption=scram-sha-256 \
|
||||
-c hba_file=/etc/postgresql/pg_hba.conf \
|
||||
-c log_connections=on \
|
||||
-c log_hostname=off
|
||||
@@ -0,0 +1,6 @@
|
||||
# Lab7: HTTP-клиент promtool для Docker healthcheck (тот же client cert Prometheus).
|
||||
tls_config:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name: prometheus
|
||||
@@ -0,0 +1,97 @@
|
||||
# Prometheus (prom/prometheus:v3.13.5) — хранилище МЕТРИК (TSDB на volume promdata, 15 дней / 2 GB).
|
||||
# Источники:
|
||||
# * OTLP push от Collector: /api/v1/otlp (флаг --web.enable-otlp-receiver) — метрики API,
|
||||
# worker, relay, janitor и (lab7) собственные метрики Collector (job=otel-collector).
|
||||
# job = service.name, instance = service.instance.id (= X-Instance-Id);
|
||||
# * scrape (lab7 — только HTTPS + client cert prometheus, проверка CA и SAN цели): HAProxy
|
||||
# (lb:8404/metrics), RabbitMQ (broker:15691), Loki, Tempo и сам Prometheus.
|
||||
# Alert rules — rules/*.yml (локальное состояние firing/resolved, без Alertmanager:
|
||||
# доставка наружу по заданию не нужна).
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
scrape_timeout: 5s
|
||||
evaluation_interval: 15s
|
||||
|
||||
otlp:
|
||||
# Ресурсные атрибуты, которые станут labels всех OTLP-метрик (низкая кардинальность).
|
||||
# service.name -> job, service.instance.id -> instance (Prometheus делает сам).
|
||||
promote_resource_attributes:
|
||||
- service.version
|
||||
- deployment.environment.name
|
||||
|
||||
storage:
|
||||
tsdb:
|
||||
# OTLP-метрики приходят push-ом от нескольких процессов: допускаем небольшой разброс времени.
|
||||
out_of_order_time_window: 10m
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/*.yml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: prometheus
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name: prometheus
|
||||
static_configs:
|
||||
- targets: ["localhost:9090"]
|
||||
|
||||
- job_name: haproxy
|
||||
metrics_path: /metrics
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name: lb
|
||||
static_configs:
|
||||
- targets: ["lb:8404"]
|
||||
|
||||
# Глубина очередей брокера (ready/unacked/consumers) по vhost messenger.
|
||||
- job_name: rabbitmq
|
||||
metrics_path: /metrics/detailed
|
||||
params:
|
||||
vhost: [messenger]
|
||||
family: [queue_coarse_metrics, queue_consumer_count]
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name: broker
|
||||
static_configs:
|
||||
- targets: ["broker:15691"]
|
||||
|
||||
# Агрегированные метрики узла RabbitMQ (память, алармы, соединения).
|
||||
- job_name: rabbitmq-node
|
||||
metrics_path: /metrics
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name: broker
|
||||
static_configs:
|
||||
- targets: ["broker:15691"]
|
||||
|
||||
- job_name: loki
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name: loki
|
||||
static_configs:
|
||||
- targets: ["loki:3100"]
|
||||
|
||||
- job_name: tempo
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/internal-ca.crt
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
server_name: tempo
|
||||
static_configs:
|
||||
- targets: ["tempo:3200"]
|
||||
@@ -0,0 +1,158 @@
|
||||
# Recording и alert rules мессенджера (Prometheus 3.13). Проверка: promtool check rules,
|
||||
# unit-тесты — infra/prometheus/tests/messenger.test.yml (scripts/check_rules.sh).
|
||||
# Состояние alerts видно локально: Prometheus /alerts, /api/v1/alerts, ряд ALERTS{alertstate},
|
||||
# Grafana -> Alerting (data source-managed) и панель «Alerts» дашборда. Доставки наружу нет.
|
||||
#
|
||||
# SLI (бизнес-запросы = все маршруты, кроме /health/* и unmatched):
|
||||
# доступность = доля ответов не 5xx; SLO 99.5 % за 7 дней (rolling)
|
||||
# задержка = доля запросов не дольше 0.5 с (без upload
|
||||
# и входа/регистрации: scrypt by design); SLO 99 % за 7 дней
|
||||
# time to ready = доля вложений, ready не позже 30 с после
|
||||
# durable acceptance (COMMIT enqueue); SLO 99 % за 7 дней
|
||||
# Числитель ошибок — только 5xx (отказ сервера). 4xx (неверный пароль, 404, 409) — корректные
|
||||
# ответы на ошибку клиента и бюджет не расходуют. Error budget доступности = 0.5 % запросов.
|
||||
groups:
|
||||
- name: messenger-sli
|
||||
interval: 15s
|
||||
rules:
|
||||
- record: messenger:http_requests:rate2m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*|unmatched"}[2m]))
|
||||
- record: messenger:http_errors:rate2m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*|unmatched", http_response_status_class="5xx"}[2m])) or vector(0)
|
||||
- record: messenger:http_error_ratio:rate2m
|
||||
expr: messenger:http_errors:rate2m / messenger:http_requests:rate2m
|
||||
- record: messenger:http_requests:rate5m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*|unmatched"}[5m]))
|
||||
- record: messenger:http_error_ratio:rate5m
|
||||
expr: (sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*|unmatched", http_response_status_class="5xx"}[5m])) or vector(0)) / messenger:http_requests:rate5m
|
||||
# p50/p95/p99 из buckets ВСЕХ реплик (сначала sum by le, потом quantile) — не среднее p95.
|
||||
- record: messenger:http_latency_seconds:p50_5m
|
||||
expr: histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*|unmatched"}[5m])))
|
||||
- record: messenger:http_latency_seconds:p95_5m
|
||||
expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*|unmatched"}[5m])))
|
||||
- record: messenger:http_latency_seconds:p99_5m
|
||||
expr: histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*|unmatched"}[5m])))
|
||||
# Ошибки на входе (HAProxy): если упала БД, реплики не ready и LB сам отвечает 503 —
|
||||
# до API такие запросы не доходят, и метрика API их не видит.
|
||||
- record: messenger:lb_requests:rate2m
|
||||
expr: sum(rate(haproxy_frontend_http_responses_total{proxy="fe_api"}[2m]))
|
||||
- record: messenger:lb_error_ratio:rate2m
|
||||
expr: (sum(rate(haproxy_frontend_http_responses_total{proxy="fe_api", code="5xx"}[2m])) or vector(0)) / messenger:lb_requests:rate2m
|
||||
- record: messenger:db_operation_seconds:p95_2m
|
||||
expr: histogram_quantile(0.95, sum by (le) (rate(db_client_operation_duration_seconds_bucket{job="messenger-api"}[2m])))
|
||||
- record: messenger:time_to_ready_seconds:p95_5m
|
||||
expr: histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{outcome="ready"}[5m])))
|
||||
|
||||
- name: messenger-slo
|
||||
interval: 1m
|
||||
rules:
|
||||
- record: messenger:slo_availability:ratio_7d
|
||||
expr: 1 - ((sum(increase(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*|unmatched", http_response_status_class="5xx"}[7d])) or vector(0)) / sum(increase(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*|unmatched"}[7d])))
|
||||
- record: messenger:slo_availability:error_budget_remaining_7d
|
||||
expr: 1 - (1 - messenger:slo_availability:ratio_7d) / (1 - 0.995)
|
||||
- record: messenger:slo_latency:ratio_7d
|
||||
expr: sum(increase(http_server_request_duration_seconds_bucket{job="messenger-api", le="0.5", http_route!~"/health/.*|unmatched|/api/v1/chats/\\{chat_id\\}/attachments|/api/v1/users|/api/v1/auth/sessions"}[7d])) / sum(increase(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*|unmatched|/api/v1/chats/\\{chat_id\\}/attachments|/api/v1/users|/api/v1/auth/sessions"}[7d]))
|
||||
- record: messenger:slo_time_to_ready:ratio_7d
|
||||
expr: sum(increase(messenger_attachment_time_to_ready_seconds_bucket{outcome="ready", le="30"}[7d])) / sum(increase(messenger_attachment_time_to_ready_seconds_count{outcome="ready"}[7d]))
|
||||
|
||||
- name: messenger-alerts
|
||||
interval: 15s
|
||||
rules:
|
||||
- alert: MessengerHighErrorRate
|
||||
# Окно 2 м, порог 5 % 5xx, минимум 0.1 запроса/с (не будить на единичной ошибке ночью), for 1m.
|
||||
expr: messenger:http_error_ratio:rate2m > 0.05 and on() messenger:http_requests:rate2m > 0.1
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
source: api
|
||||
annotations:
|
||||
summary: "API: {{ $value | humanizePercentage }} ответов 5xx за 2 минуты"
|
||||
description: "Доля 5xx среди бизнес-запросов (без /health) выше 5 % дольше минуты. Error budget SLO 99.5 % расходуется в ~10 раз быстрее допустимого."
|
||||
runbook_url: "infra/runbooks/README.md#messengerhigherrorrate"
|
||||
- alert: MessengerHighErrorRate
|
||||
expr: messenger:lb_error_ratio:rate2m > 0.05 and on() messenger:lb_requests:rate2m > 0.1
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
source: lb
|
||||
annotations:
|
||||
summary: "LB: {{ $value | humanizePercentage }} ответов 5xx за 2 минуты"
|
||||
description: "HAProxy отвечает 5xx (вероятно, нет ready-реплик: проверьте /health/ready и БД)."
|
||||
runbook_url: "infra/runbooks/README.md#messengerhigherrorrate"
|
||||
|
||||
- alert: MessengerQueueLagGrowing
|
||||
# Самое старое «созревшее» задание ждёт worker дольше 30 с, и ожидание не уменьшается.
|
||||
expr: max(messenger_jobs_ready_lag_seconds) > 30 and on() deriv(max(messenger_jobs_ready_lag_seconds)[2m:15s]) >= 0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
annotations:
|
||||
summary: "Очередь обработки вложений растёт: старейшее задание ждёт {{ $value | humanizeDuration }}"
|
||||
description: "messenger_jobs_ready_lag_seconds > 30 с дольше минуты. Вероятно, worker остановлены/перегружены или брокер недоступен."
|
||||
runbook_url: "infra/runbooks/README.md#messengerqueuelaggrowing"
|
||||
- alert: MessengerOutboxStuck
|
||||
expr: max(messenger_outbox_oldest_age_seconds) > 30
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
annotations:
|
||||
summary: "Outbox не публикуется {{ $value | humanizeDuration }}"
|
||||
description: "Задания приняты (COMMIT), но relay не может опубликовать их в RabbitMQ."
|
||||
runbook_url: "infra/runbooks/README.md#messengeroutboxstuck"
|
||||
- alert: MessengerWorkerSaturated
|
||||
# last_over_time[30s]: только живые реплики (ряды остановленных контейнеров видны ещё 5 мин).
|
||||
expr: sum(rate(messenger_worker_busy_time_seconds_total[2m])) / sum(last_over_time(messenger_worker_capacity[30s])) > 0.9
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Worker заняты на {{ $value | humanizePercentage }} дольше 5 минут"
|
||||
runbook_url: "infra/runbooks/README.md#messengerworkersaturated"
|
||||
|
||||
- alert: MessengerDbSlow
|
||||
# p95 логической операции БД в API выше 250 мс (норма — единицы мс).
|
||||
expr: messenger:db_operation_seconds:p95_2m > 0.25
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
annotations:
|
||||
summary: "PostgreSQL медленная: p95 операции {{ $value | humanizeDuration }}"
|
||||
description: "Задержка в spans/гистограмме db.client.operation.duration, а не в коде обработчика. Проверьте блокировки и ресурсы БД."
|
||||
runbook_url: "infra/runbooks/README.md#messengerdbslow"
|
||||
- alert: MessengerDbPoolSaturated
|
||||
expr: max(avg_over_time(db_client_connection_pending_requests{job="messenger-api"}[1m])) > 1
|
||||
for: 1m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Пул соединений API исчерпан: в среднем {{ $value }} запросов ждут соединение"
|
||||
runbook_url: "infra/runbooks/README.md#messengerdbpoolsaturated"
|
||||
- alert: MessengerApiLatencyHigh
|
||||
expr: messenger:http_latency_seconds:p95_5m > 1
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "p95 бизнес-запросов API {{ $value | humanizeDuration }}"
|
||||
runbook_url: "infra/runbooks/README.md#messengerapilatencyhigh"
|
||||
|
||||
- alert: MessengerTelemetryExportFailing
|
||||
# Collector не смог отправить/поставить в очередь данные в backend: телеметрия теряется.
|
||||
# Collector 0.163 публикует счётчики без суффикса _total — regex по __name__ покрывает оба варианта.
|
||||
expr: sum(rate({__name__=~"otelcol_exporter_send_failed_spans(_total)?"}[2m]) or vector(0)) + sum(rate({__name__=~"otelcol_exporter_send_failed_log_records(_total)?"}[2m]) or vector(0)) + sum(rate({__name__=~"otelcol_exporter_enqueue_failed_spans(_total)?"}[2m]) or vector(0)) + sum(rate({__name__=~"otelcol_exporter_enqueue_failed_log_records(_total)?"}[2m]) or vector(0)) > 0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Collector теряет телеметрию ({{ $value | printf \"%.1f\" }} записей/с)"
|
||||
runbook_url: "infra/runbooks/README.md#messengertelemetryexportfailing"
|
||||
- alert: MessengerTelemetryBackendDown
|
||||
# Lab7: метрики Collector приходят push-ом через его же pipeline (receiver prometheus/self),
|
||||
# поэтому упавший Collector виден как ОТСУТСТВИЕ его up, а не up == 0.
|
||||
expr: up{job=~"loki|tempo"} == 0 or absent_over_time(up{job="otelcol-contrib"}[2m])
|
||||
for: 1m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Telemetry backend {{ $labels.job }} недоступен"
|
||||
runbook_url: "infra/runbooks/README.md#messengertelemetrybackenddown"
|
||||
@@ -0,0 +1,82 @@
|
||||
# Unit-тесты alert rules: promtool test rules (запуск — scripts/check_rules.sh, в контейнере
|
||||
# prom/prometheus той же версии, что и стенд). Синтетические ряды с шагом 15 с.
|
||||
rule_files:
|
||||
- ../rules/messenger.yml
|
||||
|
||||
evaluation_interval: 15s
|
||||
|
||||
tests:
|
||||
# 1) Высокая доля 5xx в API: 4 rps успешных, с t=165 с ещё ~0.67 rps 5xx (≈14 %).
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api", instance="a", http_route="/api/v1/chats/{chat_id}/messages", http_response_status_class="2xx"}'
|
||||
values: '0+60x60'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api", instance="a", http_route="/api/v1/chats/{chat_id}/messages", http_response_status_class="5xx"}'
|
||||
values: '0x10 10+10x20 310x29'
|
||||
# health не входит в SLI: тысячи 5xx /health/ready не должны поднимать alert.
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api", instance="a", http_route="/health/ready", http_response_status_class="5xx"}'
|
||||
values: '0+1000x60'
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
- eval_time: 5m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: page
|
||||
source: api
|
||||
exp_annotations:
|
||||
summary: "API: 14.29% ответов 5xx за 2 минуты"
|
||||
description: "Доля 5xx среди бизнес-запросов (без /health) выше 5 % дольше минуты. Error budget SLO 99.5 % расходуется в ~10 раз быстрее допустимого."
|
||||
runbook_url: "infra/runbooks/README.md#messengerhigherrorrate"
|
||||
# 5xx прекратились в t=465 с: через 2-минутное окно alert снят (resolved).
|
||||
- eval_time: 12m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
|
||||
# 2) Worker остановлен: возраст старейшего созревшего задания растёт с t=135 с, после
|
||||
# восстановления (t=330 с) — 0.
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'messenger_jobs_ready_lag_seconds{job="messenger-relay", instance="r"}'
|
||||
values: '0x8 15+15x12 0x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: MessengerQueueLagGrowing
|
||||
exp_alerts: []
|
||||
- eval_time: 5m
|
||||
alertname: MessengerQueueLagGrowing
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: page
|
||||
exp_annotations:
|
||||
summary: "Очередь обработки вложений растёт: старейшее задание ждёт 3m 0s"
|
||||
description: "messenger_jobs_ready_lag_seconds > 30 с дольше минуты. Вероятно, worker остановлены/перегружены или брокер недоступен."
|
||||
runbook_url: "infra/runbooks/README.md#messengerqueuelaggrowing"
|
||||
- eval_time: 9m
|
||||
alertname: MessengerQueueLagGrowing
|
||||
exp_alerts: []
|
||||
|
||||
# 3) Медленная БД: все операции попадают в bucket 1 с (p95 ≈ 0.95 с) с t=150 с.
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'db_client_operation_duration_seconds_bucket{job="messenger-api", instance="a", le="0.01"}'
|
||||
values: '0+100x10 1000x30'
|
||||
- series: 'db_client_operation_duration_seconds_bucket{job="messenger-api", instance="a", le="1"}'
|
||||
values: '0+100x10 1000+100x30'
|
||||
- series: 'db_client_operation_duration_seconds_bucket{job="messenger-api", instance="a", le="+Inf"}'
|
||||
values: '0+100x10 1000+100x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: MessengerDbSlow
|
||||
exp_alerts: []
|
||||
- eval_time: 6m
|
||||
alertname: MessengerDbSlow
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: page
|
||||
exp_annotations:
|
||||
summary: "PostgreSQL медленная: p95 операции 950.5ms"
|
||||
description: "Задержка в spans/гистограмме db.client.operation.duration, а не в коде обработчика. Проверьте блокировки и ресурсы БД."
|
||||
runbook_url: "infra/runbooks/README.md#messengerdbslow"
|
||||
@@ -0,0 +1,8 @@
|
||||
# Lab7: HTTP API Prometheus (OTLP-приём от Collector, запросы Grafana, self-scrape) — только TLS
|
||||
# с обязательным клиентским сертификатом internal-ca. Без сертификата — отказ на handshake.
|
||||
tls_server_config:
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
client_auth_type: RequireAndVerifyClientCert
|
||||
client_ca_file: /run/secrets/internal-ca.crt
|
||||
min_version: TLS12
|
||||
@@ -0,0 +1,30 @@
|
||||
# RabbitMQ 4.1 (lab7). Топология и пользователи — из definitions (Docker secret, только хеши паролей).
|
||||
load_definitions = /run/secrets/rabbitmq_definitions.json
|
||||
loopback_users.guest = true
|
||||
# Lab7: plaintext AMQP выключен, только AMQPS 5671 (TLS 1.2/1.3).
|
||||
listeners.tcp = none
|
||||
listeners.ssl.default = 5671
|
||||
ssl_options.cacertfile = /run/secrets/internal-ca.crt
|
||||
ssl_options.certfile = /run/secrets/service.crt
|
||||
ssl_options.keyfile = /run/secrets/service.key
|
||||
# verify_peer: предъявленный клиентский сертификат проверяется по internal-ca (relay/worker/ops
|
||||
# предъявляют свои). Авторизация на 3 — пользователь/пароль + ACL vhost (см. definitions).
|
||||
ssl_options.verify = verify_peer
|
||||
ssl_options.fail_if_no_peer_cert = false
|
||||
ssl_options.versions.1 = tlsv1.3
|
||||
ssl_options.versions.2 = tlsv1.2
|
||||
# Метрики rabbitmq_prometheus — только HTTPS :15691 с обязательным client cert (Prometheus).
|
||||
prometheus.tcp.port = 15692
|
||||
prometheus.tcp.ip = 127.0.0.1
|
||||
prometheus.ssl.port = 15691
|
||||
prometheus.ssl.cacertfile = /run/secrets/internal-ca.crt
|
||||
prometheus.ssl.certfile = /run/secrets/service.crt
|
||||
prometheus.ssl.keyfile = /run/secrets/service.key
|
||||
prometheus.ssl.verify = verify_peer
|
||||
prometheus.ssl.fail_if_no_peer_cert = true
|
||||
vm_memory_high_watermark.relative = 0.6
|
||||
disk_free_limit.absolute = 256MB
|
||||
consumer_timeout = 1800000
|
||||
log.console = true
|
||||
log.console.level = info
|
||||
log.file = false
|
||||
@@ -0,0 +1,128 @@
|
||||
# Runbooks alerts мессенджера (lab6)
|
||||
|
||||
Alerts вычисляет Prometheus (`infra/prometheus/rules/messenger.yml`), состояние видно локально:
|
||||
Grafana → дашборд «Messenger — наблюдаемость (lab6)» (панели «Alerts firing» и «История alerts»),
|
||||
Grafana → Alerting → Alert rules (data source-managed), либо запросом `ALERTS{alertstate="firing"}`.
|
||||
Доставки наружу нет (Alertmanager не используется — по заданию достаточно firing/resolved).
|
||||
|
||||
Общий порядок диагностики (метрика → трасса → лог):
|
||||
|
||||
1. **Метрика** отвечает «что и насколько плохо»: какая доля ошибок, какой перцентиль, где насыщение.
|
||||
2. **Трасса** отвечает «где именно тратится время/возникает ошибка»: какой span длинный/с ошибкой —
|
||||
код обработчика, БД, S3, ожидание в очереди (разрыв между `attachments send` и `process`).
|
||||
3. **Лог** отвечает «что конкретно произошло»: `event`, `error.type`, `request_id`, `job_id`,
|
||||
и по `trace_id` ведёт обратно в трассу (в Grafana — ссылка «Trace в Tempo» у записи Loki).
|
||||
|
||||
Команды ниже выполняются из корня репозитория. Доступ к Grafana: <http://127.0.0.1:3000>,
|
||||
пользователь `admin`, пароль в `secrets/grafana_admin_password` (не печатать в отчёты).
|
||||
|
||||
---
|
||||
|
||||
## MessengerHighErrorRate
|
||||
|
||||
**Условие:** доля 5xx среди бизнес-запросов API (без `/health/*` и `unmatched`) за 2 мин > 5 % при
|
||||
≥ 0.1 запроса/с, `for: 1m` (`source=api`). Вторая копия (`source=lb`) — то же по HAProxy `fe_api`:
|
||||
если реплики не ready, 503 отдаёт сам LB, и до API запросы не доходят.
|
||||
|
||||
**Смысл для SLO:** при 5 % ошибок бюджет 0.5 % (SLO 99.5 % / 7 дней) расходуется в 10 раз быстрее.
|
||||
|
||||
**Диагностика:**
|
||||
1. Панель «5xx по причине (error.type)»: `db_unavailable`/`db_pool_timeout` → БД (см. MessengerDbSlow),
|
||||
`storage_unavailable` → S3, `overloaded` → лимиты слотов (scrypt/upload), `internal_error` → баг.
|
||||
PromQL: `sum by (error_type, http_route) (rate(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_class="5xx"}[1m]))`.
|
||||
2. `source=lb` и API почти без трафика → `haproxy_backend_active_servers{proxy="be_api"}`; если 0 —
|
||||
реплики не ready: `docker compose ps api`, `curl -s localhost:8080/health/ready`, затем БД.
|
||||
3. Трасса ошибки: Grafana → Explore → Tempo → TraceQL
|
||||
`{ resource.service.name = "messenger-api" && kind = server && status = error }`; длинный
|
||||
`db <операция>` с ошибкой — БД; длинный `s3 *` — S3; ошибки без длинных дочерних spans — код.
|
||||
4. Логи: Loki `{service_name="messenger-api"} | event="http.request" | http_response_status_code >= 500`
|
||||
или `| event="db.unavailable"`; X-Request-Id из ответа клиента → `| request_id="<id>"`.
|
||||
|
||||
**Действия:** устранить причину по error.type (БД/S3/перегрузка); при баге — откатить версию
|
||||
(`scripts/rolling-update.sh <прежняя версия>`). Resolved — когда 2-минутное окно очистится от 5xx.
|
||||
|
||||
## MessengerQueueLagGrowing
|
||||
|
||||
**Условие:** `max(messenger_jobs_ready_lag_seconds) > 30` и производная за 2 мин ≥ 0, `for: 1m`.
|
||||
`ready_lag` — сколько ждёт worker самое старое задание, которому уже пора выполняться
|
||||
(PostgreSQL `jobs`: `status='queued' AND next_attempt_at <= now()`), т. е. backlog по источнику
|
||||
истины, а не по брокеру. Alert снимается, когда lag перестал расти (идёт дренаж) или < 30 с.
|
||||
|
||||
**Диагностика:**
|
||||
1. Панель «Saturation worker»: utilization 0 и нет `messenger_worker_capacity` → worker не работают
|
||||
(`docker compose ps worker`, логи `{service_name="messenger-worker"} | event=~"worker.*"`).
|
||||
Utilization ≈ 1.0 → worker живы, но не успевают (ёмкость `WORKER_REPLICAS × WORKER_CONCURRENCY`).
|
||||
2. «Глубина очереди»: RabbitMQ ready растёт вместе с jobs queued → сообщения доходят, нет потребителей;
|
||||
outbox pending растёт → не работает relay/брокер (см. MessengerOutboxStuck).
|
||||
3. Трасса задания из окна: в трассе upload разрыв между `attachments send` (relay) и
|
||||
`attachments.process.v1 process` (worker) = время в очереди; атрибут `messenger.job.queue_wait_s`.
|
||||
4. `docker compose --profile tools run --rm ops inspect <attachment_id>` — состояние и traceparent.
|
||||
|
||||
**Действия:** `./scripts/start-worker.sh` (или `docker compose up -d worker`); при насыщении —
|
||||
`docker compose up -d --scale worker=N` / `WORKER_CONCURRENCY`. Проверить, что backlog убывает
|
||||
(«Возраст старейшего задания» → 0) и alert resolved. Задания не теряются: они в quorum-очереди и в БД.
|
||||
|
||||
## MessengerOutboxStuck
|
||||
|
||||
**Условие:** старейшая созревшая неопубликованная строка outbox старше 30 с, `for: 1m`.
|
||||
|
||||
**Диагностика:** `docker compose ps relay broker`; логи `{service_name="messenger-relay"} |
|
||||
event=~"broker.*|db.error"`; панель «Relay: публикации outbox» (outcome=failed, error.type);
|
||||
алармы памяти/диска RabbitMQ (`rabbitmq_alarms_*`). **Действия:** восстановить broker/relay;
|
||||
relay опубликует накопленное само (transactional outbox), дубли гасит worker по `jobs`.
|
||||
|
||||
## MessengerWorkerSaturated
|
||||
|
||||
**Условие:** `sum(rate(messenger_worker_busy_time_seconds_total[2m])) / sum(messenger_worker_capacity) > 0.9`, `for: 5m`.
|
||||
**Смысл:** все потоки worker заняты — новые задания копятся (предвестник MessengerQueueLagGrowing).
|
||||
**Действия:** масштабировать worker; проверить «Длительность обработки job p95» и CPU worker
|
||||
(«CPU saturation: доля лимита»): рост длительности при CPU у лимита → нужен CPU, а не реплики.
|
||||
|
||||
## MessengerDbSlow
|
||||
|
||||
**Условие:** p95 `db.client.operation.duration` API за 2 мин > 250 мс, `for: 1m` (норма — единицы мс).
|
||||
|
||||
**Диагностика (отличить БД от кода):**
|
||||
1. «Операции БД p95 по операции»: какая операция медленная (`get_session_user` — сессии, т. е.
|
||||
почти все запросы; `add_message` — блокировка строки чата и т. п.).
|
||||
2. Трасса медленного запроса: длинный CLIENT span `db <операция>` (и `db.client.connection.wait_time_ms`
|
||||
в атрибутах) → время в БД. Если длинный SERVER span, а db spans короткие — проблема в коде
|
||||
обработчика (пример: `handler.compute` при `X-Fault-Inject: slow-handler`, CPU scrypt `security.*`).
|
||||
3. В БД: `docker compose exec -T db sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT pid, wait_event_type, wait_event, state, now()-xact_start AS xact, left(query,60) FROM pg_stat_activity WHERE datname=current_database() ORDER BY xact DESC NULLS LAST"'`
|
||||
— `wait_event_type=Lock` у многих сессий → блокировка; найти держателя (самая старая транзакция).
|
||||
|
||||
**Действия:** снять держателя блокировки (`SELECT pg_terminate_backend(<pid>)`) или дождаться/отменить
|
||||
долгую миграцию; при нехватке ресурсов — CPU/IO БД. После снятия p95 возвращается за окно 2 мин.
|
||||
|
||||
## MessengerDbPoolSaturated
|
||||
|
||||
**Условие:** в среднем за 1 мин > 1 запроса ждут соединение пула API, `for: 1m`.
|
||||
**Смысл:** соединения заняты (медленная БД или слишком мало `DB_POOL_SIZE`); дальше — PoolTimeout (3 с) и 503.
|
||||
**Действия:** как MessengerDbSlow; если БД быстрая, а пул мал — увеличить `DB_POOL_SIZE`
|
||||
(и `maxconn` в HAProxy соразмерно).
|
||||
|
||||
## MessengerApiLatencyHigh
|
||||
|
||||
**Условие:** p95 бизнес-запросов API (все реплики, из buckets) за 5 мин > 1 с, `for: 2m`.
|
||||
**Диагностика:** «p95 по маршруту» → маршрут; exemplars на панели задержки → трасса; дальше как
|
||||
MessengerDbSlow (БД или код). Upload и вход дольше по природе (приём 10 MiB, scrypt).
|
||||
|
||||
## MessengerTelemetryExportFailing
|
||||
|
||||
**Условие:** Collector отбрасывает данные: рост `otelcol_exporter_send_failed_*` (retry исчерпан)
|
||||
или `otelcol_exporter_enqueue_failed_*` (очередь экспортёра полна), `for: 1m`.
|
||||
**Смысл:** телеметрия теряется (бизнес-путь — нет: SDK экспортирует асинхронно).
|
||||
**Диагностика:** панель «Collector: очередь экспортёров» (size → capacity), какой exporter;
|
||||
`up{job=~"loki|tempo"}`; логи Collector `docker compose logs otel-collector | grep Exporting`.
|
||||
**Действия:** восстановить backend (`docker compose up -d tempo loki prometheus`); потери за период
|
||||
оценить по `increase(otelcol_exporter_*_failed_*[окно])`. Восполнить потерянное нельзя — это
|
||||
осознанный выбор: ограниченный буфер в памяти вместо неограниченного роста RAM.
|
||||
|
||||
## MessengerTelemetryBackendDown
|
||||
|
||||
**Условие:** `up{job=~"otel-collector|loki|tempo"} == 0`, `for: 1m`.
|
||||
**Действия:** `docker compose ps`, `docker compose up -d <service>`. Если упал сам Collector —
|
||||
SDK приложений теряют данные после заполнения своих очередей (2048 spans / log records на
|
||||
процесс); потери видны после восстановления в `otel_sdk_exporter_*_exported_total{error_type!=""}`
|
||||
и `otel_sdk_processor_*_processed_total{error_type="queue_full"}`. Если упал Prometheus — alerts
|
||||
не вычисляются вовсе (ограничение учебного стенда: нет внешнего мониторинга мониторинга).
|
||||
@@ -0,0 +1,55 @@
|
||||
# Tempo (grafana/tempo:2.10.10) — хранилище ТРАСС, монолитный режим, локальный backend
|
||||
# (volume tempodata: WAL + блоки), хранение 7 дней. Приём OTLP gRPC :4317 от Collector,
|
||||
# запросы Grafana — HTTP :3200 (TraceQL, поиск по trace_id).
|
||||
stream_over_http_enabled: true
|
||||
|
||||
# Lab7: HTTP :3200 (Grafana, scrape) — TLS + обязательный client cert; приём OTLP gRPC :4317 —
|
||||
# TLS + обязательный client cert (Collector). Внутренний gRPC :9096 — только 127.0.0.1.
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
grpc_listen_address: 127.0.0.1
|
||||
grpc_listen_port: 9096
|
||||
http_tls_config:
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
client_auth_type: RequireAndVerifyClientCert
|
||||
client_ca_file: /run/secrets/internal-ca.crt
|
||||
log_level: warn
|
||||
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
tls:
|
||||
cert_file: /run/secrets/service.crt
|
||||
key_file: /run/secrets/service.key
|
||||
client_ca_file: /run/secrets/internal-ca.crt
|
||||
min_version: "1.2"
|
||||
|
||||
ingester:
|
||||
max_block_duration: 5m
|
||||
trace_idle_period: 10s
|
||||
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
|
||||
overrides:
|
||||
defaults:
|
||||
ingestion:
|
||||
rate_limit_bytes: 15000000
|
||||
burst_size_bytes: 20000000
|
||||
max_traces_per_user: 20000
|
||||
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,40 @@
|
||||
-- Lab2: начальная схема. Источник истины — PostgreSQL.
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
position integer NOT NULL, -- порядок участников как в запросе
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
-- Индекс под keyset-пагинацию истории: (created_at, id) внутри чата.
|
||||
CREATE INDEX messages_chat_order_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY, -- SHA-256 от токена; сам токен не хранится
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
created_at timestamptz NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
revoked_at timestamptz
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Lab3: общая (для всех реплик) идемпотентность POST сообщения.
|
||||
-- Миграция только добавляет таблицу: код lab2 продолжает работать на новой схеме
|
||||
-- (expand-only), поэтому её можно применить до замены реплик при rolling update.
|
||||
--
|
||||
-- Область уникальности по контракту: пользователь + метод + путь чата + ключ.
|
||||
-- Метод всегда POST, путь однозначно задаётся chat_id, поэтому ключ PK — (user_id, chat_id, idem_key).
|
||||
CREATE TABLE idempotency_keys (
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
idem_key text NOT NULL,
|
||||
request_hash bytea NOT NULL, -- SHA-256 канонического JSON тела запроса
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, chat_id, idem_key)
|
||||
);
|
||||
CREATE INDEX idempotency_keys_expires_idx ON idempotency_keys (expires_at);
|
||||
@@ -0,0 +1,40 @@
|
||||
-- Lab4: метаданные вложений (PostgreSQL) отдельно от байтов (приватный S3-bucket).
|
||||
-- Expand-only: только новые таблицы, код lab3 продолжает работать на этой схеме.
|
||||
--
|
||||
-- Жизненный цикл строки attachments:
|
||||
-- pending — намерение записано ДО S3 PUT (известны размер, SHA-256, object_key);
|
||||
-- ready — объект в S3 подтверждён, строка видна API и может быть прикреплена.
|
||||
-- Если процесс упал/БД отказала между PUT и переводом в ready, строка остаётся pending.
|
||||
-- Её находит janitor (src/janitor.py) по created_at старше grace period и удаляет
|
||||
-- сначала объект в S3, затем строку. Поэтому в S3 нет объектов, о которых не знает БД.
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
owner_id uuid NOT NULL REFERENCES users(id),
|
||||
filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
-- Ключ назначает сервер (случайный), filename в нём не участвует.
|
||||
object_key text NOT NULL UNIQUE,
|
||||
status text NOT NULL CHECK (status IN ('pending', 'ready')),
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX attachments_chat_idx ON attachments (chat_id);
|
||||
-- Janitor ищет только «зависшие» pending: частичный индекс маленький.
|
||||
CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending';
|
||||
|
||||
-- Ссылки сообщения на вложения (порядок как в запросе).
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
position integer NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
|
||||
|
||||
-- Отпечаток тела в ключе идемпотентности уже включает attachment_ids (= [] для lab3),
|
||||
-- поэтому существующие ключи остаются валидными без пересчёта.
|
||||
@@ -0,0 +1,126 @@
|
||||
-- Lab5: асинхронная обработка вложений (очередь RabbitMQ + worker).
|
||||
--
|
||||
-- Жизненный цикл attachments.status:
|
||||
-- pending — внутреннее: строка записана ДО PUT в staging, API её не показывает (как в lab4);
|
||||
-- queued — оригинал в staging + задание + запись outbox зафиксированы ОДНОЙ транзакцией, ответ 202;
|
||||
-- processing — worker взял аренду (lease) задания;
|
||||
-- ready — оригинал и все варианты в конечном prefix, метаданные вариантов записаны;
|
||||
-- failed — постоянная ошибка или исчерпаны попытки (error_code).
|
||||
-- Источник истины по состоянию задания — таблица jobs; сообщение брокера — только «пинок»
|
||||
-- с job_id: worker все решения принимает по строке jobs (FOR UPDATE).
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check
|
||||
CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed'));
|
||||
-- Ключ staging-объекта (staging/<uuid>); NULL после безопасной очистки.
|
||||
ALTER TABLE attachments ADD COLUMN staging_key text UNIQUE;
|
||||
ALTER TABLE attachments ADD COLUMN error_code text;
|
||||
-- Версия pipeline, результат которой сейчас опубликован/ожидается (основной курс: 1).
|
||||
ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1;
|
||||
|
||||
-- Одна логическая работа = (attachment_id, pipeline_version). job_id не меняется при
|
||||
-- redelivery и retry; attempt — номер управляемой попытки (растёт при каждом захвате).
|
||||
CREATE TABLE jobs (
|
||||
id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
status text NOT NULL CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
|
||||
attempt integer NOT NULL DEFAULT 0 CHECK (attempt >= 0),
|
||||
max_attempts integer NOT NULL CHECK (max_attempts >= 1),
|
||||
next_attempt_at timestamptz NOT NULL,
|
||||
-- Аренда: кто обрабатывает (host:boot), токен попытки (fencing) и срок.
|
||||
lease_owner text,
|
||||
lease_token uuid,
|
||||
lease_until timestamptz,
|
||||
error_code text,
|
||||
last_error text,
|
||||
replay_count integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
finished_at timestamptz,
|
||||
UNIQUE (attachment_id, pipeline_version),
|
||||
CHECK ((status = 'processing') = (lease_token IS NOT NULL))
|
||||
);
|
||||
CREATE INDEX jobs_lease_idx ON jobs (lease_until) WHERE status = 'processing';
|
||||
CREATE INDEX jobs_queued_idx ON jobs (updated_at) WHERE status = 'queued';
|
||||
CREATE INDEX jobs_failed_idx ON jobs (updated_at) WHERE status = 'failed';
|
||||
|
||||
-- Результаты: ключ эффекта (attachment_id, pipeline_version, variant) — PRIMARY KEY.
|
||||
-- Повтор job не может создать второй набор вариантов.
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
pipeline_version integer NOT NULL,
|
||||
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
|
||||
object_key text NOT NULL UNIQUE,
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes > 0),
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (attachment_id, pipeline_version, name)
|
||||
);
|
||||
|
||||
-- Transactional outbox: сообщение для брокера пишется в той же транзакции, что и
|
||||
-- задание. Relay публикует с publisher confirm и только потом ставит published_at.
|
||||
-- available_at позволяет отложить публикацию (retry с backoff).
|
||||
CREATE TABLE outbox (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES jobs(id),
|
||||
payload jsonb NOT NULL,
|
||||
available_at timestamptz NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
published_at timestamptz,
|
||||
publish_count integer NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX outbox_unpublished_idx ON outbox (available_at, id) WHERE published_at IS NULL;
|
||||
CREATE INDEX outbox_job_idx ON outbox (job_id);
|
||||
|
||||
-- Журнал переходов (audit): кто, когда, какая попытка, причина. Без секретов и bytes.
|
||||
CREATE TABLE job_events (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES jobs(id),
|
||||
at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
event text NOT NULL,
|
||||
attempt integer,
|
||||
actor text,
|
||||
detail jsonb
|
||||
);
|
||||
CREATE INDEX job_events_job_idx ON job_events (job_id, id);
|
||||
|
||||
-- Relay ждёт NOTIFY, а не опрашивает таблицу каждые N мс. Уведомление доставляется
|
||||
-- только после COMMIT; при потере уведомления relay всё равно делает опрос раз в секунду.
|
||||
CREATE FUNCTION outbox_notify() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM pg_notify('outbox', '');
|
||||
RETURN NULL;
|
||||
END $$;
|
||||
CREATE TRIGGER outbox_notify_trg AFTER INSERT ON outbox
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION outbox_notify();
|
||||
|
||||
-- Переход lab4 -> lab5: готовые вложения lab4 не имеют вариантов. Их оригинал
|
||||
-- (originals/<uuid>) становится staging-объектом, вложение — queued, создаётся задание.
|
||||
-- Готовность заявляется только когда все варианты уровня существуют.
|
||||
WITH legacy AS (
|
||||
UPDATE attachments
|
||||
SET staging_key = object_key,
|
||||
object_key = 'attachments/' || id || '/v1/original',
|
||||
status = 'queued',
|
||||
updated_at = now()
|
||||
WHERE status = 'ready'
|
||||
RETURNING id
|
||||
), new_jobs AS (
|
||||
INSERT INTO jobs (id, attachment_id, pipeline_version, status, attempt, max_attempts,
|
||||
next_attempt_at, created_at, updated_at)
|
||||
SELECT gen_random_uuid(), id, 1, 'queued', 0, 5, now(), now(), now() FROM legacy
|
||||
RETURNING id, attachment_id, created_at
|
||||
), events AS (
|
||||
INSERT INTO job_events (job_id, event, attempt, actor, detail)
|
||||
SELECT id, 'enqueued', 1, 'migration', '{"reason":"lab4 backfill"}'::jsonb FROM new_jobs
|
||||
)
|
||||
INSERT INTO outbox (job_id, payload, available_at)
|
||||
SELECT id,
|
||||
jsonb_build_object('schema_version', 1, 'job_id', id, 'type', 'attachment.process.v1',
|
||||
'attachment_id', attachment_id, 'pipeline_version', 1, 'attempt', 1,
|
||||
'created_at', to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')),
|
||||
now()
|
||||
FROM new_jobs;
|
||||
@@ -0,0 +1,48 @@
|
||||
-- Lab7: минимальные права сервисных ролей PostgreSQL. Применяется src/migrate.py ПОСЛЕ миграций
|
||||
-- при каждом запуске (идемпотентно: сначала REVOKE ALL, затем ровно эти GRANT).
|
||||
-- Владелец объектов и DDL — только postgres (job migrate). Ни у одной сервисной роли нет
|
||||
-- CREATE на схеме, TRUNCATE, REFERENCES, TRIGGER и доступа к чужим таблицам.
|
||||
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
|
||||
REVOKE ALL ON SCHEMA public FROM PUBLIC;
|
||||
GRANT CONNECT ON DATABASE messenger TO api_svc, worker_svc, relay_svc, janitor_svc, ops_svc;
|
||||
GRANT USAGE ON SCHEMA public TO api_svc, worker_svc, relay_svc, janitor_svc, ops_svc;
|
||||
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM api_svc, worker_svc, relay_svc, janitor_svc, ops_svc;
|
||||
REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM api_svc, worker_svc, relay_svc, janitor_svc, ops_svc;
|
||||
GRANT SELECT ON schema_migrations TO api_svc, worker_svc, relay_svc, janitor_svc, ops_svc;
|
||||
|
||||
-- api_svc: пользователи/сессии/чаты/сообщения/вложения; постановка задания (jobs+outbox+событие).
|
||||
-- UPDATE users — только для rehash пароля при входе.
|
||||
GRANT SELECT, INSERT, UPDATE ON users, sessions TO api_svc;
|
||||
GRANT SELECT, INSERT ON chats, chat_members, messages, message_attachments TO api_svc;
|
||||
GRANT SELECT, INSERT, DELETE ON idempotency_keys TO api_svc;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON attachments TO api_svc;
|
||||
GRANT SELECT ON attachment_variants TO api_svc;
|
||||
GRANT SELECT, INSERT ON jobs, job_events, outbox TO api_svc;
|
||||
-- SELECT ... FOR UPDATE OF chats (сериализация вставок в чат) требует UPDATE хотя бы на один
|
||||
-- столбец. Даём только UPDATE(id): на id ссылаются FK chat_members/messages, изменить его нельзя.
|
||||
GRANT UPDATE (id) ON chats TO api_svc;
|
||||
|
||||
-- worker_svc: НЕТ доступа к users, sessions (хешам паролей/токенов), chats, messages.
|
||||
GRANT SELECT, UPDATE ON attachments, jobs TO worker_svc;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON attachment_variants TO worker_svc;
|
||||
GRANT SELECT, INSERT ON job_events, outbox TO worker_svc;
|
||||
|
||||
-- relay_svc: публикация outbox и reaper аренд.
|
||||
GRANT SELECT, UPDATE, DELETE ON outbox TO relay_svc;
|
||||
GRANT SELECT, UPDATE ON jobs, attachments TO relay_svc;
|
||||
GRANT SELECT, INSERT ON job_events TO relay_svc;
|
||||
GRANT SELECT ON attachment_variants TO relay_svc;
|
||||
|
||||
-- janitor_svc: уборка брошенных вложений и staging.
|
||||
GRANT SELECT, UPDATE, DELETE ON attachments TO janitor_svc;
|
||||
GRANT SELECT ON jobs, outbox, attachment_variants, message_attachments TO janitor_svc;
|
||||
GRANT UPDATE (id) ON jobs TO janitor_svc; -- только для SELECT ... FOR UPDATE (см. выше)
|
||||
GRANT SELECT, INSERT ON job_events TO janitor_svc;
|
||||
|
||||
-- ops_svc: операторский CLI (inspect/failed/replay/dlq).
|
||||
GRANT SELECT, UPDATE ON jobs, attachments TO ops_svc;
|
||||
GRANT SELECT ON attachment_variants TO ops_svc;
|
||||
GRANT SELECT, INSERT ON job_events, outbox TO ops_svc;
|
||||
|
||||
-- bigserial outbox.id, job_events.id
|
||||
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO api_svc, worker_svc, relay_svc, janitor_svc, ops_svc;
|
||||
@@ -0,0 +1,22 @@
|
||||
# Закреплённые версии. Lab5 (аудит F04): Pillow 13.0.0 (GHSA-wqgw-9xfh-qf2g, EXIF memory DoS),
|
||||
# urllib3 2.8.0 (GHSA-vxq7-64xx-v4gw), minio 7.2.20 — совместимая с новым urllib3.
|
||||
# Драйвер PostgreSQL для Python (из lab3).
|
||||
psycopg[binary]==3.2.3
|
||||
psycopg-pool==3.2.4
|
||||
# Lab4: S3-клиент (SigV4, multipart) и проверка JPEG (draft-декодирование).
|
||||
minio==7.2.20
|
||||
urllib3==2.8.0
|
||||
# Lab5: Pillow также делает варианты (JPEG, WebP — libwebp входит в wheel).
|
||||
Pillow==13.0.0
|
||||
# Lab5: клиент AMQP 0-9-1 для RabbitMQ (publisher confirms, manual ack, basic.qos).
|
||||
pika==1.3.2
|
||||
# Lab6: OpenTelemetry SDK (traces, metrics, logs) и экспорт OTLP/HTTP protobuf в Collector.
|
||||
# Транзитивные зависимости (protobuf, requests, googleapis-common-protos) зафиксированы в
|
||||
# evidence/pip-freeze.txt по фактической сборке образа.
|
||||
opentelemetry-api==1.45.1
|
||||
opentelemetry-sdk==1.45.1
|
||||
opentelemetry-exporter-otlp-proto-http==1.45.1
|
||||
opentelemetry-semantic-conventions==0.66b1
|
||||
# Lab7: Argon2id (libargon2 через CFFI; wheel argon2-cffi-bindings — abi3, есть для amd64/arm64).
|
||||
argon2-cffi==25.1.0
|
||||
argon2-cffi-bindings==25.1.0
|
||||
Executable
+77
@@ -0,0 +1,77 @@
|
||||
#!/bin/sh
|
||||
# ОПЕРАТОР, один раз на новом volume baodata (повторный запуск безопасен — синхронизирует
|
||||
# policies/роли/секреты):
|
||||
# 1) operator init: 3 unseal shares, порог 2; root token и shares -> $OPERATOR_DIR/openbao/init.json
|
||||
# (каталог оператора вне проекта, права 600). На экран ничего секретного не выводится;
|
||||
# 2) unseal (scripts/bao-unseal.sh);
|
||||
# 3) с root token (только в env этого процесса и `docker compose exec -e BAO_TOKEN`):
|
||||
# KV v2 на kv/, policies из infra/openbao/policies,
|
||||
# auth/cert с ролью на каждый сервис (allowed_dns_sans = имя сервиса, TTL токена 15 мин,
|
||||
# max 1 ч), запись сервисных секретов kv/messenger/<svc> из secrets/ (через stdin).
|
||||
# Приложениям root token, unseal shares и BAO_TOKEN не передаются никогда.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
OPERATOR_DIR=${OPERATOR_DIR:-$HOME/.mtusi2026lab7-operator}
|
||||
umask 077
|
||||
mkdir -p "$OPERATOR_DIR/openbao"
|
||||
chmod 700 "$OPERATOR_DIR" "$OPERATOR_DIR/openbao"
|
||||
INIT=$OPERATOR_DIR/openbao/init.json
|
||||
|
||||
docker compose up -d openbao >/dev/null
|
||||
i=0
|
||||
until docker compose exec -T openbao bao status -format=json >/dev/null 2>&1 || [ $? -eq 2 ]; do
|
||||
i=$((i+1)); [ $i -gt 60 ] && { echo "openbao does not respond" >&2; exit 3; }
|
||||
sleep 1
|
||||
done
|
||||
initialized=$(docker compose exec -T openbao bao status -format=json 2>/dev/null | python3 -c "import json,sys; print(json.load(sys.stdin)['initialized'])" || true)
|
||||
if [ "$initialized" != "True" ]; then
|
||||
[ -s "$INIT" ] && { echo "$INIT exists but OpenBao is not initialized: refusing to overwrite operator material" >&2; exit 5; }
|
||||
docker compose exec -T openbao bao operator init -key-shares=3 -key-threshold=2 -format=json > "$INIT.tmp"
|
||||
mv "$INIT.tmp" "$INIT"
|
||||
chmod 600 "$INIT"
|
||||
echo "openbao initialized; root token and 3 unseal shares saved to $INIT (operator only)"
|
||||
fi
|
||||
./scripts/bao-unseal.sh
|
||||
|
||||
BAO_TOKEN=$(python3 -c "import json,sys; print(json.load(open(sys.argv[1]))['root_token'])" "$INIT")
|
||||
export BAO_TOKEN
|
||||
bao() { docker compose exec -T -e BAO_TOKEN openbao bao "$@"; }
|
||||
|
||||
bao secrets list -format=json | grep -q '"kv/"' || bao secrets enable -path=kv -version=2 kv >/dev/null
|
||||
bao auth list -format=json | grep -q '"cert/"' || bao auth enable cert >/dev/null
|
||||
|
||||
SERVICES="api worker relay janitor migrate s3-init ops"
|
||||
for svc in $SERVICES; do
|
||||
bao policy write "messenger-$svc" - < "infra/openbao/policies/messenger-$svc.hcl" >/dev/null
|
||||
ttl=15m; max=1h
|
||||
case $svc in migrate|s3-init) ttl=5m; max=10m ;; esac
|
||||
# Роль cert auth: доверяем ТОЛЬКО internal-ca и ТОЛЬКО сертификату с SAN DNS = имя сервиса.
|
||||
bao write "auth/cert/certs/$svc" display_name="$svc" token_policies="messenger-$svc" \
|
||||
certificate=@/run/secrets/internal-ca.crt allowed_dns_sans="$svc" \
|
||||
token_ttl="$ttl" token_max_ttl="$max" token_type=service >/dev/null
|
||||
done
|
||||
|
||||
# Сервисные секреты -> KV. JSON собирается из secrets/ и идёт в `bao kv put ... -` через stdin.
|
||||
for svc in $SERVICES; do
|
||||
python3 - "$svc" <<'PY' | bao kv put -mount=kv "messenger/$svc" - >/dev/null
|
||||
import json, sys
|
||||
svc = sys.argv[1]
|
||||
r = lambda n: open("secrets/" + n).read().strip()
|
||||
amqps = lambda u: "amqps://%s:%s@broker:5671/messenger" % (u, r("broker_%s_password" % u))
|
||||
s3 = lambda who: {"S3_ACCESS_KEY_ID": r("s3_%s_access_key" % who), "S3_SECRET_ACCESS_KEY": r("s3_%s_secret_key" % who)}
|
||||
data = {
|
||||
"api": lambda: {"POSTGRES_PASSWORD": r("db_api_password"), **s3("api")},
|
||||
"worker": lambda: {"POSTGRES_PASSWORD": r("db_worker_password"), "BROKER_URL": amqps("worker"), **s3("worker")},
|
||||
"relay": lambda: {"POSTGRES_PASSWORD": r("db_relay_password"), "BROKER_URL": amqps("relay")},
|
||||
"janitor": lambda: {"POSTGRES_PASSWORD": r("db_janitor_password"), **s3("janitor")},
|
||||
"migrate": lambda: {"POSTGRES_PASSWORD": r("postgres_password"),
|
||||
**{"DB_%s_PASSWORD" % w.upper(): r("db_%s_password" % w)
|
||||
for w in ("api", "worker", "relay", "janitor", "ops")}},
|
||||
"s3-init": lambda: s3("admin"),
|
||||
"ops": lambda: {"POSTGRES_PASSWORD": r("db_ops_password"), "BROKER_URL": amqps("ops"), **s3("janitor")},
|
||||
}[svc]()
|
||||
json.dump(data, sys.stdout)
|
||||
PY
|
||||
done
|
||||
unset BAO_TOKEN
|
||||
echo "openbao configured: kv v2 'kv/', audit file->stdout, auth/cert roles: $SERVICES"
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
# ОПЕРАТОР: unseal OpenBao после старта/рестарта контейнера (file storage -> процесс sealed).
|
||||
# Берёт ровно threshold (2 из 3) unseal shares из каталога оператора $OPERATOR_DIR/openbao
|
||||
# (вне проекта, 600, никогда не монтируется в контейнеры) и передаёт их через stdin — значения не
|
||||
# появляются ни в выводе, ни в аргументах процессов. Повторный вызов на unsealed OpenBao — no-op.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
OPERATOR_DIR=${OPERATOR_DIR:-$HOME/.mtusi2026lab7-operator}
|
||||
INIT=$OPERATOR_DIR/openbao/init.json
|
||||
[ -s "$INIT" ] || { echo "no $INIT: run scripts/bao-init.sh first" >&2; exit 2; }
|
||||
# Ждём, пока процесс OpenBao начнёт отвечать (после рестарта контейнера).
|
||||
i=0
|
||||
until docker compose exec -T openbao bao status -format=json >/dev/null 2>&1 || [ $? -eq 2 ]; do
|
||||
i=$((i+1)); [ $i -gt 60 ] && { echo "openbao does not respond" >&2; exit 3; }
|
||||
sleep 1
|
||||
done
|
||||
sealed() { docker compose exec -T openbao bao status -format=json 2>/dev/null | python3 -c "import json,sys; print(json.load(sys.stdin)['sealed'])"; }
|
||||
if [ "$(sealed)" = "False" ]; then
|
||||
echo "openbao already unsealed"; exit 0
|
||||
fi
|
||||
for idx in 0 1; do
|
||||
python3 -c "import json,sys; print(json.load(open(sys.argv[1]))['unseal_keys_b64'][int(sys.argv[2])])" "$INIT" "$idx" \
|
||||
| docker compose exec -T openbao bao write -format=json sys/unseal key=- >/dev/null
|
||||
done
|
||||
[ "$(sealed)" = "False" ] && echo "openbao unsealed (2 of 3 shares)" || { echo "unseal failed" >&2; exit 4; }
|
||||
Executable
+323
@@ -0,0 +1,323 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Генератор импортируемого dashboard Grafana: infra/grafana/dashboards/messenger.json.
|
||||
|
||||
JSON лежит в Git и подхватывается provisioning-ом; этот скрипт — воспроизводимый способ его
|
||||
изменить (python3 scripts/build_dashboard.py). Только стандартная библиотека.
|
||||
Все запросы ссылаются на реальные имена метрик (см. REPORT.md «Схема сигналов»).
|
||||
Перцентили — histogram_quantile по sum by (le) buckets всех реплик, не среднее p95.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
OUT = Path(__file__).resolve().parents[1] / "infra/grafana/dashboards/messenger.json"
|
||||
PROM = {"type": "prometheus", "uid": "prometheus"}
|
||||
LOKI = {"type": "loki", "uid": "loki"}
|
||||
TEMPO = {"type": "tempo", "uid": "tempo"}
|
||||
API = 'job="messenger-api", instance=~"$instance"'
|
||||
BUSINESS = API + ', http_route!~"/health/.*|unmatched"'
|
||||
|
||||
_panels = []
|
||||
_id = [0]
|
||||
_pos = {"x": 0, "y": 0, "h": 0}
|
||||
|
||||
|
||||
def _next_id():
|
||||
_id[0] += 1
|
||||
return _id[0]
|
||||
|
||||
|
||||
def place(w, h):
|
||||
if _pos["x"] + w > 24:
|
||||
_pos["x"] = 0
|
||||
_pos["y"] += _pos["h"]
|
||||
_pos["h"] = 0
|
||||
g = {"x": _pos["x"], "y": _pos["y"], "w": w, "h": h}
|
||||
_pos["x"] += w
|
||||
_pos["h"] = max(_pos["h"], h)
|
||||
return g
|
||||
|
||||
|
||||
def row(title):
|
||||
_pos["x"] = 0
|
||||
_pos["y"] += _pos["h"]
|
||||
_pos["h"] = 0
|
||||
_panels.append({"type": "row", "id": _next_id(), "title": title, "collapsed": False,
|
||||
"gridPos": {"x": 0, "y": _pos["y"], "w": 24, "h": 1}, "panels": []})
|
||||
_pos["y"] += 1
|
||||
|
||||
|
||||
def target(expr, legend="", ref="A", exemplar=False, instant=False):
|
||||
t = {"datasource": PROM, "expr": expr, "legendFormat": legend or "__auto", "refId": ref,
|
||||
"range": not instant, "instant": instant}
|
||||
if exemplar:
|
||||
t["exemplar"] = True
|
||||
return t
|
||||
|
||||
|
||||
def ts(title, targets, unit="short", w=8, h=8, description="", stack=False, min0=True, thresholds=None):
|
||||
refs = "ABCDEFGHIJ"
|
||||
tg = [target(*t[:2], ref=refs[i], exemplar=(len(t) > 2 and t[2])) for i, t in enumerate(targets)]
|
||||
p = {"type": "timeseries", "id": _next_id(), "title": title, "description": description,
|
||||
"datasource": PROM, "gridPos": place(w, h), "targets": tg,
|
||||
"fieldConfig": {"defaults": {"unit": unit, "custom": {"lineWidth": 1, "fillOpacity": 10,
|
||||
"showPoints": "never",
|
||||
"stacking": {"mode": "normal" if stack else "none"}},
|
||||
**({"min": 0} if min0 else {})},
|
||||
"overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "bottom", "calcs": ["lastNotNull", "max"]},
|
||||
"tooltip": {"mode": "multi", "sort": "desc"}}}
|
||||
if thresholds:
|
||||
p["fieldConfig"]["defaults"]["thresholds"] = {"mode": "absolute", "steps": thresholds}
|
||||
p["fieldConfig"]["defaults"]["custom"]["thresholdsStyle"] = {"mode": "line+area"}
|
||||
_panels.append(p)
|
||||
|
||||
|
||||
def stat(title, expr, unit="short", w=3, h=4, steps=None, description="", decimals=None):
|
||||
p = {"type": "stat", "id": _next_id(), "title": title, "description": description, "datasource": PROM,
|
||||
"gridPos": place(w, h), "targets": [target(expr, "", instant=True)],
|
||||
"fieldConfig": {"defaults": {"unit": unit, "thresholds": {"mode": "absolute", "steps": steps or [
|
||||
{"color": "green", "value": None}]}}, "overrides": []},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False},
|
||||
"colorMode": "background", "graphMode": "area", "textMode": "value"}}
|
||||
if decimals is not None:
|
||||
p["fieldConfig"]["defaults"]["decimals"] = decimals
|
||||
_panels.append(p)
|
||||
|
||||
|
||||
def build():
|
||||
# ------------------------------------------------------------------ обзор
|
||||
row("Обзор и SLO")
|
||||
stat("RPS бизнес-запросов", "messenger:http_requests:rate2m", "reqps",
|
||||
description="sum(rate(http_server_request_duration_seconds_count{job=messenger-api, без /health}[2m]))")
|
||||
stat("5xx, доля (2m)", "messenger:http_error_ratio:rate2m", "percentunit", decimals=2,
|
||||
steps=[{"color": "green", "value": None}, {"color": "orange", "value": 0.01}, {"color": "red", "value": 0.05}],
|
||||
description="Числитель: 5xx бизнес-запросов; знаменатель: все бизнес-запросы (без /health, unmatched).")
|
||||
stat("p95 API (5m)", "messenger:http_latency_seconds:p95_5m", "s", decimals=3,
|
||||
steps=[{"color": "green", "value": None}, {"color": "orange", "value": 0.5}, {"color": "red", "value": 1}])
|
||||
stat("SLO доступности, 7d", "messenger:slo_availability:ratio_7d", "percentunit", decimals=3,
|
||||
steps=[{"color": "red", "value": None}, {"color": "green", "value": 0.995}],
|
||||
description="SLO: 99.5 % бизнес-запросов без 5xx за скользящие 7 дней.")
|
||||
stat("Остаток error budget, 7d", "messenger:slo_availability:error_budget_remaining_7d", "percentunit",
|
||||
decimals=1, steps=[{"color": "red", "value": None}, {"color": "orange", "value": 0.25},
|
||||
{"color": "green", "value": 0.5}])
|
||||
stat("Time to ready p95", "messenger:time_to_ready_seconds:p95_5m", "s", decimals=2,
|
||||
steps=[{"color": "green", "value": None}, {"color": "orange", "value": 10}, {"color": "red", "value": 30}],
|
||||
description="От durable acceptance (COMMIT enqueue) до COMMIT ready. SLO: 99 % не дольше 30 с.")
|
||||
stat("Ready lag очереди", "max(messenger_jobs_ready_lag_seconds) or vector(0)", "s", decimals=0,
|
||||
steps=[{"color": "green", "value": None}, {"color": "orange", "value": 10}, {"color": "red", "value": 30}],
|
||||
description="Сколько ждёт worker самое старое созревшее задание (PostgreSQL jobs).")
|
||||
stat("Alerts firing", 'count(ALERTS{alertstate="firing"}) or vector(0)', "short",
|
||||
steps=[{"color": "green", "value": None}, {"color": "red", "value": 1}])
|
||||
_panels.append({
|
||||
"type": "state-timeline", "id": _next_id(), "title": "История alerts (pending/firing -> resolved)",
|
||||
"datasource": PROM, "gridPos": place(24, 6),
|
||||
"targets": [target('max by (alertname, source, alertstate) (ALERTS)', "{{alertname}} {{source}} {{alertstate}}")],
|
||||
"fieldConfig": {"defaults": {"color": {"mode": "thresholds"},
|
||||
"thresholds": {"mode": "absolute", "steps": [
|
||||
{"color": "transparent", "value": None}, {"color": "red", "value": 1}]}},
|
||||
"overrides": []},
|
||||
"options": {"showValue": "never", "mergeValues": True, "rowHeight": 0.8,
|
||||
"legend": {"showLegend": False}}})
|
||||
|
||||
# ------------------------------------------------------------------ API
|
||||
row("API: трафик, ошибки, задержка")
|
||||
ts("RPS по маршруту", [("sum by (http_route) (rate(http_server_request_duration_seconds_count{%s}[1m]))" % API,
|
||||
"{{http_route}}")], "reqps", stack=True)
|
||||
ts("Ответы по классу статуса", [(
|
||||
"sum by (http_response_status_class) (rate(http_server_request_duration_seconds_count{%s}[1m]))" % BUSINESS,
|
||||
"{{http_response_status_class}}")], "reqps", stack=True)
|
||||
ts("Доля 5xx: API и LB", [
|
||||
("messenger:http_error_ratio:rate2m", "API (без /health)"),
|
||||
("messenger:lb_error_ratio:rate2m", "HAProxy fe_api")], "percentunit",
|
||||
thresholds=[{"color": "transparent", "value": None}, {"color": "red", "value": 0.05}],
|
||||
description="Если БД недоступна, реплики не ready и 503 отдаёт LB: эти запросы видны только в метрике LB.")
|
||||
ts("Задержка API p50/p95/p99 (из histogram)", [
|
||||
("histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{%s}[1m])))" % BUSINESS, "p50", True),
|
||||
("histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{%s}[1m])))" % BUSINESS, "p95", True),
|
||||
("histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{%s}[1m])))" % BUSINESS, "p99", True)],
|
||||
"s", w=12, description="Точки-exemplars ведут в трассу Tempo конкретного запроса.")
|
||||
ts("p95 по маршруту", [(
|
||||
"histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{%s}[5m])))" % BUSINESS,
|
||||
"{{http_route}}")], "s", w=12)
|
||||
ts("5xx по причине (error.type)", [(
|
||||
'sum by (error_type, http_route) (rate(http_server_request_duration_seconds_count{%s, http_response_status_class="5xx"}[1m]))' % API,
|
||||
"{{error_type}} {{http_route}}")], "reqps", stack=True)
|
||||
ts("Запросы в обработке (saturation API)", [
|
||||
("sum by (instance) (http_server_active_requests{%s})" % API, "{{instance}}")], "short")
|
||||
ts("HAProxy: UP-реплики и очередь LB", [
|
||||
('haproxy_backend_active_servers{proxy="be_api"}', "UP реплик"),
|
||||
('haproxy_backend_current_queue{proxy="be_api"}', "очередь LB")], "short")
|
||||
|
||||
# ------------------------------------------------------------------ worker
|
||||
row("Worker и очередь заданий")
|
||||
ts("Задания по исходу (в минуту)", [(
|
||||
"sum by (messenger_job_outcome) (increase(messenger_jobs_processed_total[1m]))", "{{messenger_job_outcome}}")],
|
||||
"short", stack=True, description="ready / retry / failed / duplicate / lease_lost / rejected / requeued")
|
||||
ts("Длительность обработки job p50/p95/p99", [
|
||||
('histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket{messenger_job_outcome="ready"}[5m])))', "p50", True),
|
||||
('histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{messenger_job_outcome="ready"}[5m])))', "p95", True),
|
||||
('histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket{messenger_job_outcome="ready"}[5m])))', "p99", True)],
|
||||
"s")
|
||||
ts("Time to ready p50/p95/p99", [
|
||||
('histogram_quantile(0.50, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{outcome="ready"}[5m])))', "p50", True),
|
||||
('histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{outcome="ready"}[5m])))', "p95", True),
|
||||
('histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{outcome="ready"}[5m])))', "p99", True)],
|
||||
"s", description="Backlog-ожидание + обработка: время от 202 (COMMIT) до ready.")
|
||||
ts("Глубина очереди: PostgreSQL и RabbitMQ", [
|
||||
('max by (messenger_job_status) (messenger_jobs_count{messenger_job_status=~"queued|processing"})', "jobs {{messenger_job_status}} (БД)"),
|
||||
('max(messenger_outbox_pending)', "outbox не опубликовано"),
|
||||
('sum(rabbitmq_detailed_queue_messages_ready{queue="attachments.process.v1"})', "RabbitMQ ready"),
|
||||
('sum(rabbitmq_detailed_queue_messages_unacked{queue="attachments.process.v1"})', "RabbitMQ unacked"),
|
||||
('sum(rabbitmq_detailed_queue_messages{queue="attachments.dlq"})', "DLQ")], "short")
|
||||
ts("Возраст старейшего задания и lag", [
|
||||
('max by (messenger_job_status) (messenger_jobs_oldest_age_seconds)', "oldest {{messenger_job_status}}"),
|
||||
("max(messenger_jobs_ready_lag_seconds)", "ready lag"),
|
||||
("max(messenger_outbox_oldest_age_seconds)", "outbox oldest")], "s",
|
||||
thresholds=[{"color": "transparent", "value": None}, {"color": "red", "value": 30}])
|
||||
ts("Ожидание в очереди p95 (до claim)", [
|
||||
("histogram_quantile(0.95, sum by (le) (rate(messenger_job_queue_wait_seconds_bucket[5m])))", "p95 queue wait"),
|
||||
("histogram_quantile(0.95, sum by (le) (rate(messenger_outbox_publish_delay_seconds_bucket[5m])))", "p95 outbox -> broker")],
|
||||
"s", description="Backlog (сколько ждут) отдельно от processing latency (сколько обрабатываются).")
|
||||
ts("Saturation worker: занятость потребителей", [
|
||||
("sum(rate(messenger_worker_busy_time_seconds_total[1m])) / sum(last_over_time(messenger_worker_capacity[30s]))", "utilization (busy_time/capacity)"),
|
||||
("sum(messenger_worker_busy) / sum(last_over_time(messenger_worker_capacity[30s]))", "busy/capacity (мгновенно)")],
|
||||
"percentunit", description="1.0 = все WORKER_CONCURRENCY потоков всех реплик заняты; очередь растёт быстрее обработки.")
|
||||
ts("Relay: публикации outbox", [
|
||||
("sum by (outcome) (rate(messenger_outbox_published_total[1m]))", "{{outcome}}")], "short")
|
||||
|
||||
# ------------------------------------------------------------------ DB / S3
|
||||
row("PostgreSQL и S3")
|
||||
ts("Пул соединений API: used / idle / max", [
|
||||
('sum by (instance, db_client_connection_state) (db_client_connection_count{%s})' % API,
|
||||
"{{instance}} {{db_client_connection_state}}"),
|
||||
('max(db_client_connection_max{%s})' % API, "max на реплику")], "short")
|
||||
ts("Ожидающие соединение и таймауты пула", [
|
||||
('sum by (instance) (db_client_connection_pending_requests{%s})' % API, "pending {{instance}}"),
|
||||
('sum by (instance) (increase(db_client_connection_timeouts_total{%s}[1m]))' % API, "timeouts/мин {{instance}}")],
|
||||
"short")
|
||||
ts("Ожидание соединения пула p95", [
|
||||
('histogram_quantile(0.95, sum by (le) (rate(db_client_connection_wait_time_seconds_bucket{%s}[1m])))' % API, "p95 wait")],
|
||||
"s")
|
||||
ts("Операции БД p95 по операции (API)", [
|
||||
('histogram_quantile(0.95, sum by (le, db_operation_name) (rate(db_client_operation_duration_seconds_bucket{%s}[1m])))' % API,
|
||||
"{{db_operation_name}}")], "s", w=12)
|
||||
ts("Операции БД worker/relay p95", [
|
||||
('histogram_quantile(0.95, sum by (le, db_operation_name) (rate(db_client_operation_duration_seconds_bucket{job=~"messenger-worker|messenger-relay"}[5m])))',
|
||||
"{{db_operation_name}}")], "s", w=12)
|
||||
ts("Ошибки операций БД", [
|
||||
('sum by (job, db_operation_name, error_type) (rate(db_client_operation_duration_seconds_count{error_type!=""}[1m]))',
|
||||
"{{job}} {{db_operation_name}} {{error_type}}")], "short")
|
||||
ts("S3 p95 по операции", [
|
||||
('histogram_quantile(0.95, sum by (le, messenger_s3_operation) (rate(messenger_s3_operation_duration_seconds_bucket[5m])))',
|
||||
"{{messenger_s3_operation}}")], "s")
|
||||
ts("S3 ошибки", [
|
||||
('sum by (job, messenger_s3_operation, outcome) (rate(messenger_s3_operation_duration_seconds_count{outcome!="ok"}[1m]))',
|
||||
"{{job}} {{messenger_s3_operation}} {{outcome}}")], "short")
|
||||
|
||||
# ------------------------------------------------------------------ ресурсы
|
||||
row("Ресурсы контейнеров (CPU/RAM)")
|
||||
ts("CPU, ядер (cgroup контейнера)", [
|
||||
("sum by (job, instance) (rate(container_cpu_time_seconds_total[1m]))", "{{job}} {{instance}}")], "short", w=12)
|
||||
ts("CPU saturation: доля лимита", [
|
||||
("rate(container_cpu_time_seconds_total[1m]) / on(job, instance) container_cpu_limit", "{{job}} {{instance}}")],
|
||||
"percentunit", w=12)
|
||||
ts("Память контейнеров приложений", [
|
||||
("container_memory_usage_bytes", "{{job}} {{instance}}")], "bytes", w=12)
|
||||
ts("Память: доля лимита", [
|
||||
("container_memory_usage_bytes / on(job, instance) container_memory_limit_bytes", "{{job}} {{instance}}")],
|
||||
"percentunit", w=12)
|
||||
ts("Память telemetry-стека (RSS)", [
|
||||
('process_resident_memory_bytes{job=~"prometheus|loki|tempo"}', "{{job}}"),
|
||||
('{__name__=~"otelcol_process_memory_rss(_bytes)?"}', "otel-collector RSS (вкл. страницы бинарника)"),
|
||||
('otelcol_process_runtime_heap_alloc_bytes', "otel-collector Go heap"),
|
||||
('rabbitmq_process_resident_memory_bytes', "rabbitmq")], "bytes", w=12)
|
||||
ts("CPU telemetry-стека", [
|
||||
('rate(process_cpu_seconds_total{job=~"prometheus|loki|tempo"}[1m])', "{{job}}"),
|
||||
('rate({__name__=~"otelcol_process_cpu_seconds(_total)?"}[1m])', "otel-collector")], "short", w=12)
|
||||
|
||||
# ------------------------------------------------------------------ telemetry
|
||||
row("Конвейер телеметрии (потери)")
|
||||
ts("Collector: принято / отправлено / потеряно (spans)", [
|
||||
('sum(rate({__name__=~"otelcol_receiver_accepted_spans(_total)?"}[1m]))', "принято"),
|
||||
('sum(rate({__name__=~"otelcol_exporter_sent_spans(_total)?"}[1m]))', "отправлено в Tempo"),
|
||||
('sum(rate({__name__=~"otelcol_exporter_send_failed_spans(_total)?"}[1m]))', "ошибка отправки"),
|
||||
('sum(rate({__name__=~"otelcol_exporter_enqueue_failed_spans(_total)?"}[1m]))', "очередь полна (потеря)"),
|
||||
('sum(rate({__name__=~"otelcol_receiver_refused_spans(_total)?"}[1m]))', "отказ приёма (memory_limiter)")], "short")
|
||||
ts("Collector: логи", [
|
||||
('sum(rate({__name__=~"otelcol_receiver_accepted_log_records(_total)?"}[1m]))', "принято"),
|
||||
('sum(rate({__name__=~"otelcol_exporter_sent_log_records(_total)?"}[1m]))', "отправлено в Loki"),
|
||||
('sum(rate({__name__=~"otelcol_exporter_send_failed_log_records(_total)?"}[1m]))', "ошибка отправки"),
|
||||
('sum(rate({__name__=~"otelcol_exporter_enqueue_failed_log_records(_total)?"}[1m]))', "очередь полна (потеря)")], "short")
|
||||
ts("Collector: очередь экспортёров", [
|
||||
("max by (exporter) (otelcol_exporter_queue_size)", "size {{exporter}}"),
|
||||
("max by (exporter) (otelcol_exporter_queue_capacity)", "capacity {{exporter}}")], "short")
|
||||
ts("SDK приложений: потери на стороне процесса", [
|
||||
('sum by (job, error_type) (rate(otel_sdk_processor_span_processed_total{error_type!=""}[1m]))', "spans dropped {{job}} {{error_type}}"),
|
||||
('sum by (job, error_type) (rate(otel_sdk_processor_log_processed_total{error_type!=""}[1m]))', "logs dropped {{job}} {{error_type}}"),
|
||||
('sum by (job, error_type) (rate(otel_sdk_exporter_span_exported_total{error_type!=""}[1m]))', "span export failed {{job}} {{error_type}}")],
|
||||
"short", w=12)
|
||||
ts("SDK: заполнение очереди BatchSpanProcessor", [
|
||||
("max by (job, instance) (otel_sdk_processor_span_queue_size)", "{{job}} {{instance}}"),
|
||||
("max(otel_sdk_processor_span_queue_capacity)", "capacity")], "short", w=12)
|
||||
|
||||
# ------------------------------------------------------------------ logs / traces
|
||||
row("Логи и трассы")
|
||||
_panels.append({
|
||||
"type": "logs", "id": _next_id(), "title": "Логи WARN/ERROR приложений (Loki)", "datasource": LOKI,
|
||||
"gridPos": place(24, 10),
|
||||
"targets": [{"datasource": LOKI, "refId": "A", "queryType": "range",
|
||||
"expr": '{service_name=~"messenger-.+"} | severity_text=~"WARN.*|ERROR.*|CRITICAL"'}],
|
||||
"options": {"showTime": True, "wrapLogMessage": True, "enableLogDetails": True, "sortOrder": "Descending",
|
||||
"dedupStrategy": "none", "prettifyLogMessage": False}})
|
||||
_panels.append({
|
||||
"type": "logs", "id": _next_id(), "title": "HTTP 5xx (event=http.request)", "datasource": LOKI,
|
||||
"gridPos": place(12, 10),
|
||||
"targets": [{"datasource": LOKI, "refId": "A", "queryType": "range",
|
||||
"expr": '{service_name="messenger-api"} | event="http.request" | http_response_status_code >= 500'}],
|
||||
"options": {"showTime": True, "wrapLogMessage": True, "enableLogDetails": True, "sortOrder": "Descending"}})
|
||||
_panels.append({
|
||||
"type": "table", "id": _next_id(), "title": "Последние трассы обработки заданий (Tempo)", "datasource": TEMPO,
|
||||
"gridPos": place(12, 10),
|
||||
"targets": [{"datasource": TEMPO, "refId": "A", "queryType": "traceql", "limit": 20, "tableType": "traces",
|
||||
"query": '{ resource.service.name = "messenger-worker" && name = "attachments.process.v1 process" }'}]})
|
||||
_panels.append({
|
||||
"type": "table", "id": _next_id(), "title": "Медленные запросы API > 1 s (Tempo)", "datasource": TEMPO,
|
||||
"gridPos": place(12, 10),
|
||||
"targets": [{"datasource": TEMPO, "refId": "A", "queryType": "traceql", "limit": 20, "tableType": "traces",
|
||||
"query": '{ resource.service.name = "messenger-api" && kind = server && duration > 1s }'}]})
|
||||
_panels.append({
|
||||
"type": "table", "id": _next_id(), "title": "Трассы с ошибкой (Tempo)", "datasource": TEMPO,
|
||||
"gridPos": place(12, 10),
|
||||
"targets": [{"datasource": TEMPO, "refId": "A", "queryType": "traceql", "limit": 20, "tableType": "traces",
|
||||
"query": '{ status = error }'}]})
|
||||
|
||||
return {
|
||||
"uid": "messenger-overview",
|
||||
"title": "Messenger — наблюдаемость (lab6)",
|
||||
"description": "API, worker, очередь, PostgreSQL, S3, ресурсы, конвейер телеметрии. Provisioning из Git.",
|
||||
"tags": ["messenger", "lab6", "otel"],
|
||||
"timezone": "browser",
|
||||
"editable": False,
|
||||
"graphTooltip": 1,
|
||||
"refresh": "10s",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"time": {"from": "now-30m", "to": "now"},
|
||||
"templating": {"list": [{
|
||||
"name": "instance", "label": "API-реплика", "type": "query", "datasource": PROM,
|
||||
"query": {"query": 'label_values(http_server_request_duration_seconds_count{job="messenger-api"}, instance)',
|
||||
"refId": "PrometheusVariableQueryEditor-VariableQuery"},
|
||||
"definition": 'label_values(http_server_request_duration_seconds_count{job="messenger-api"}, instance)',
|
||||
"includeAll": True, "multi": True, "allValue": ".*", "current": {"text": "All", "value": "$__all"},
|
||||
"refresh": 2, "sort": 1}]},
|
||||
"annotations": {"list": [{
|
||||
"builtIn": 1, "datasource": {"type": "grafana", "uid": "-- Grafana --"}, "enable": True, "hide": True,
|
||||
"iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "type": "dashboard"}]},
|
||||
"panels": _panels,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUT.write_text(json.dumps(build(), ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
||||
print("written %s (%d panels)" % (OUT.relative_to(OUT.parents[3]), len(_panels)))
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
# Офлайн-проверка конфигураций телеметрии теми же образами, что и стенд (сеть не нужна):
|
||||
# promtool check config + check rules + unit-тесты alert rules,
|
||||
# otelcol-contrib validate, loki -verify-config.
|
||||
# Использование: scripts/check_rules.sh (код возврата 0 — всё валидно)
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
img() { grep -E "^\s+image: $1" compose.yaml | head -1 | awk '{print $2}'; }
|
||||
PROM=$(img prom/prometheus)
|
||||
OTEL=$(img otel/opentelemetry-collector-contrib)
|
||||
LOKI=$(img grafana/loki)
|
||||
echo "== promtool check config ($PROM)"
|
||||
# Lab7: конфиги ссылаются на TLS-файлы /run/secrets/* — монтируем сертификаты стенда (secrets/pki).
|
||||
pki() { # pki <service> -> -v аргументы для CA и leaf
|
||||
echo "-v $PWD/secrets/pki/internal-ca.crt:/run/secrets/internal-ca.crt:ro -v $PWD/secrets/pki/$1.crt:/run/secrets/service.crt:ro -v $PWD/secrets/pki/$1.key:/run/secrets/service.key:ro"
|
||||
}
|
||||
docker run --rm $(pki prometheus) -v "$PWD/infra/prometheus:/etc/prometheus:ro" --entrypoint promtool "$PROM" check config /etc/prometheus/prometheus.yml
|
||||
echo "== promtool check web-config (TLS + обязательный client cert)"
|
||||
docker run --rm $(pki prometheus) -v "$PWD/infra/prometheus:/etc/prometheus:ro" --entrypoint promtool "$PROM" check web-config /etc/prometheus/web.yml
|
||||
echo "== promtool test rules"
|
||||
docker run --rm -v "$PWD/infra/prometheus:/w:ro" -w /w/tests --entrypoint promtool "$PROM" test rules messenger.test.yml
|
||||
echo "== otelcol validate ($OTEL)"
|
||||
docker run --rm $(pki otel-collector) -v "$PWD/infra/otel/collector.yaml:/c.yaml:ro" "$OTEL" validate --config=/c.yaml && echo "collector config OK"
|
||||
echo "== loki -verify-config ($LOKI)"
|
||||
docker run --rm $(pki loki) -v "$PWD/infra/loki/loki.yaml:/c.yaml:ro" "$LOKI" -config.file=/c.yaml -verify-config && echo "loki config OK"
|
||||
echo "== dashboard JSON is up to date with scripts/build_dashboard.py"
|
||||
tmp=$(mktemp)
|
||||
cp infra/grafana/dashboards/messenger.json "$tmp"
|
||||
python3 scripts/build_dashboard.py >/dev/null
|
||||
cmp -s "$tmp" infra/grafana/dashboards/messenger.json && echo "dashboard OK" || { echo "dashboard JSON differs from generator" >&2; exit 1; }
|
||||
Executable
+135
@@ -0,0 +1,135 @@
|
||||
#!/bin/sh
|
||||
# Lab7: локальные секреты, PKI и .env учебного стенда. Повторный запуск ничего не перезаписывает,
|
||||
# значения не печатаются. Ничего из созданного не попадает в Git (.gitignore: secrets/, *.key, *.pem)
|
||||
# и в образы (.dockerignore).
|
||||
#
|
||||
# Где что лежит:
|
||||
# $OPERATOR_DIR (по умолчанию ~/.mtusi2026lab7-operator, вне проекта, 700):
|
||||
# ca/*.key — закрытые ключи public-ca и internal-ca (не монтируются ни в один контейнер);
|
||||
# openbao/ — root token и unseal shares (создаёт scripts/bao-init.sh).
|
||||
# secrets/ (в проекте, вне Git, 700):
|
||||
# pki/*.crt|*.key — leaf-сертификаты сервисов (каждый контейнер получает ТОЛЬКО свой ключ);
|
||||
# pki/test/ — rogue CA и identity intruder для отрицательных тестов;
|
||||
# *_password, s3_* — исходные значения сервисных credentials. Приложения (api, worker,
|
||||
# relay, janitor, migrate, s3-init, ops) получают их НЕ из этих файлов,
|
||||
# а из OpenBao (scripts/bao-init.sh кладёт их в KV). Файлы нужны серверной
|
||||
# стороне: s3_identities.json (SeaweedFS), rabbitmq_definitions.json (только
|
||||
# хеши паролей), postgres_password (суперпользователь в db).
|
||||
#
|
||||
# S3 (SeaweedFS) — разные ключи и права (secrets/s3_identities.json):
|
||||
# admin — только job s3-init; api — Read+Write; worker — Read+Write; janitor — List+Write.
|
||||
# RabbitMQ — пользователи с минимальными правами в vhost messenger:
|
||||
# relay — только publish в exchange attachments; worker — только consume из attachments.process.v1;
|
||||
# ops — consume из DLQ и publish в attachments. Ни у кого нет configure.
|
||||
# PostgreSQL — отдельные роли api_svc, worker_svc, relay_svc, janitor_svc, ops_svc с грантами по
|
||||
# таблицам (migrations/grants.sql); суперпользователь postgres — только у job migrate.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
OPERATOR_DIR=${OPERATOR_DIR:-$HOME/.mtusi2026lab7-operator}
|
||||
mkdir -p secrets/pki "$OPERATOR_DIR"
|
||||
chmod 700 secrets "$OPERATOR_DIR"
|
||||
gen() { # gen <file> <bytes>
|
||||
if [ ! -s "secrets/$1" ]; then
|
||||
python3 -c "import secrets,sys; print(secrets.token_urlsafe(int(sys.argv[1])))" "$2" > "secrets/$1"
|
||||
echo "created secrets/$1"
|
||||
fi
|
||||
}
|
||||
gen postgres_password 24
|
||||
for who in api worker relay janitor ops; do
|
||||
gen "db_${who}_password" 24
|
||||
done
|
||||
gen grafana_admin_password 18
|
||||
for who in admin api worker janitor; do
|
||||
if [ ! -s "secrets/s3_${who}_access_key" ]; then
|
||||
python3 -c "import secrets; print('MTUSI' + secrets.token_hex(8).upper())" > "secrets/s3_${who}_access_key"
|
||||
echo "created secrets/s3_${who}_access_key"
|
||||
fi
|
||||
gen "s3_${who}_secret_key" 30
|
||||
done
|
||||
for who in relay worker ops; do
|
||||
gen "broker_${who}_password" 24
|
||||
done
|
||||
|
||||
# PKI: OpenSSL закреплённого образа (тот же, на котором собрано приложение).
|
||||
PKI_IMAGE=python:3.12.7-slim@sha256:60d9996b6a8a3689d36db740b49f4327be3be09a21122bd02fb8895abb38b50d
|
||||
docker run --rm --network none --user "$(id -u):$(id -g)" \
|
||||
-e PKI_CA_DAYS -e PKI_LEAF_DAYS \
|
||||
-v "$PWD/secrets/pki:/out" -v "$OPERATOR_DIR:/op" -v "$PWD/scripts/pki-issue.sh:/pki-issue.sh:ro" \
|
||||
"$PKI_IMAGE" sh /pki-issue.sh
|
||||
|
||||
BUCKET=$(grep -E '^S3_BUCKET=' .env 2>/dev/null | cut -d= -f2 || true)
|
||||
BUCKET=${BUCKET:-messenger-attachments}
|
||||
python3 - "$BUCKET" <<'PY'
|
||||
import base64, hashlib, json, os, sys
|
||||
b = sys.argv[1]
|
||||
def read(name):
|
||||
return open("secrets/" + name).read().strip()
|
||||
def ident(name, actions):
|
||||
return {"name": name, "credentials": [{"accessKey": read("s3_%s_access_key" % name),
|
||||
"secretKey": read("s3_%s_secret_key" % name)}], "actions": actions}
|
||||
cfg = {"identities": [
|
||||
ident("admin", ["Admin", "Read", "List", "Tagging", "Write"]),
|
||||
ident("api", ["Read:" + b, "Write:" + b]),
|
||||
ident("worker", ["Read:" + b, "Write:" + b]),
|
||||
ident("janitor", ["List:" + b, "Write:" + b]),
|
||||
]}
|
||||
with open("secrets/s3_identities.json", "w") as f:
|
||||
json.dump(cfg, f, indent=1)
|
||||
|
||||
# RabbitMQ: rabbit_password_hashing_sha256 = base64(salt4 + sha256(salt4 + password)).
|
||||
def rmq_hash(password):
|
||||
salt = os.urandom(4)
|
||||
return base64.b64encode(salt + hashlib.sha256(salt + password.encode()).digest()).decode()
|
||||
vhost = "messenger"
|
||||
users, perms = [], []
|
||||
rights = {
|
||||
"relay": {"configure": "^$", "write": "^attachments$", "read": "^$"},
|
||||
"worker": {"configure": "^$", "write": "^$", "read": r"^attachments\.process\.v1$"},
|
||||
"ops": {"configure": "^$", "write": "^attachments$", "read": r"^attachments\.dlq$"},
|
||||
}
|
||||
for user, r in rights.items():
|
||||
users.append({"name": user, "password_hash": rmq_hash(read("broker_%s_password" % user)),
|
||||
"hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []})
|
||||
perms.append(dict(user=user, vhost=vhost, **r))
|
||||
x = lambda name, kind: {"name": name, "vhost": vhost, "type": kind, "durable": True, "auto_delete": False,
|
||||
"internal": False, "arguments": {}}
|
||||
definitions = {
|
||||
"users": users,
|
||||
"vhosts": [{"name": vhost}],
|
||||
"permissions": perms,
|
||||
"exchanges": [x("attachments", "direct"), x("attachments.dlx", "fanout")],
|
||||
"queues": [
|
||||
{"name": "attachments.process.v1", "vhost": vhost, "durable": True, "auto_delete": False,
|
||||
"arguments": {"x-queue-type": "quorum", "x-delivery-limit": 10,
|
||||
"x-dead-letter-exchange": "attachments.dlx",
|
||||
"x-dead-letter-strategy": "at-least-once", "x-overflow": "reject-publish",
|
||||
"x-max-length": 100000}},
|
||||
{"name": "attachments.dlq", "vhost": vhost, "durable": True, "auto_delete": False,
|
||||
"arguments": {"x-queue-type": "quorum"}},
|
||||
],
|
||||
"bindings": [
|
||||
{"source": "attachments", "vhost": vhost, "destination": "attachments.process.v1",
|
||||
"destination_type": "queue", "routing_key": "attachment.process.v1", "arguments": {}},
|
||||
{"source": "attachments.dlx", "vhost": vhost, "destination": "attachments.dlq",
|
||||
"destination_type": "queue", "routing_key": "", "arguments": {}},
|
||||
],
|
||||
}
|
||||
if not os.path.exists("secrets/rabbitmq_definitions.json"):
|
||||
with open("secrets/rabbitmq_definitions.json", "w") as f:
|
||||
json.dump(definitions, f, indent=1)
|
||||
print("created secrets/rabbitmq_definitions.json")
|
||||
PY
|
||||
# Файлы монтируются в контейнеры как Docker secrets (bind mount): uid процесса внутри контейнера
|
||||
# (70 postgres, 10001 app, 100 rabbitmq/openbao, 99 haproxy, 472 grafana, 65534 prometheus, 10001 loki/tempo)
|
||||
# должен их читать. От других пользователей ХОСТА их закрывает каталог secrets/ (700). Каждый
|
||||
# контейнер получает только свои файлы (см. compose.yaml: secrets per service).
|
||||
chmod 644 secrets/*_password secrets/s3_* secrets/rabbitmq_definitions.json secrets/pki/*.crt secrets/pki/*.key \
|
||||
secrets/pki/*.pem secrets/pki/test/*
|
||||
chmod 700 secrets/pki secrets/pki/test
|
||||
if [ ! -f .env ]; then
|
||||
cp .env.example .env
|
||||
chmod 600 .env
|
||||
echo "created .env from .env.example"
|
||||
fi
|
||||
echo "operator material: $OPERATOR_DIR (CA keys; OpenBao init material after scripts/bao-init.sh)"
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/bin/sh
|
||||
# Выпуск учебного PKI lab7. Запускается init-secrets.sh ВНУТРИ закреплённого образа
|
||||
# python:3.12.7-slim (OpenSSL 3.0) — результат не зависит от openssl/LibreSSL хоста.
|
||||
# /op — каталог оператора (вне проекта): закрытые ключи CA, никогда не монтируется в стенд;
|
||||
# /out — secrets/pki проекта (вне Git): сертификаты CA и leaf-сертификаты/ключи сервисов.
|
||||
# Повторный запуск ничего не перевыпускает (кроме явно удалённых файлов); значения не печатаются.
|
||||
#
|
||||
# Два CA с разным назначением:
|
||||
# public-ca — внешний TLS (HAProxy :8443, Grafana :3000). Его сертификат раздаётся клиентам.
|
||||
# internal-ca — mTLS/TLS внутри стенда (LB->API, сервисы -> PostgreSQL/S3/RabbitMQ/Collector/
|
||||
# Prometheus/Loki/Tempo/OpenBao). Клиенты извне ему не доверяют.
|
||||
# Третий, rogue-ca, — ТОЛЬКО для отрицательных тестов (сертификат «lb» от чужого CA).
|
||||
set -eu
|
||||
umask 077
|
||||
OP=/op
|
||||
OUT=/out
|
||||
DAYS_CA=${PKI_CA_DAYS:-365}
|
||||
DAYS_LEAF=${PKI_LEAF_DAYS:-30}
|
||||
mkdir -p "$OP/ca" "$OUT/test"
|
||||
|
||||
ca() { # ca <name> <CN> <dir_for_key>
|
||||
name=$1; cn=$2; keydir=$3
|
||||
if [ ! -s "$keydir/$name.key" ] || [ ! -s "$OUT/$name.crt" ]; then
|
||||
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$keydir/$name.key" 2>/dev/null
|
||||
openssl req -x509 -new -key "$keydir/$name.key" -sha256 -days "$DAYS_CA" \
|
||||
-subj "/O=MTUSI lab7/CN=$cn" \
|
||||
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
|
||||
-addext "keyUsage=critical,keyCertSign,cRLSign" \
|
||||
-addext "subjectKeyIdentifier=hash" \
|
||||
-out "$OUT/$name.crt"
|
||||
echo "created CA $name (key in operator dir)"
|
||||
fi
|
||||
}
|
||||
|
||||
leaf() { # leaf <ca> <name> <eku> <san...>
|
||||
caname=$1; name=$2; eku=$3; shift 3
|
||||
dir=$OUT; [ "$caname" = rogue-ca ] && dir=$OUT/test
|
||||
[ "$name" = intruder ] && dir=$OUT/test
|
||||
if [ -s "$dir/$name.crt" ] && [ -s "$dir/$name.key" ]; then return 0; fi
|
||||
cakey=$OP/ca/$caname.key; [ "$caname" = rogue-ca ] && cakey=$OUT/test/rogue-ca.key
|
||||
cacrt=$OUT/$caname.crt; [ "$caname" = rogue-ca ] && cacrt=$OUT/test/rogue-ca.crt
|
||||
san=""
|
||||
for s in "$@"; do san="${san:+$san,}$s"; done
|
||||
ext=$(mktemp)
|
||||
cat > "$ext" <<EOF
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature
|
||||
extendedKeyUsage=$eku
|
||||
subjectAltName=$san
|
||||
subjectKeyIdentifier=hash
|
||||
authorityKeyIdentifier=keyid
|
||||
EOF
|
||||
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$dir/$name.key" 2>/dev/null
|
||||
openssl req -new -key "$dir/$name.key" -subj "/O=MTUSI lab7/CN=$name" -out "$dir/$name.csr"
|
||||
openssl x509 -req -in "$dir/$name.csr" -CA "$cacrt" -CAkey "$cakey" -CAcreateserial \
|
||||
-CAserial "$OP/ca/$caname.srl" -days "$DAYS_LEAF" -sha256 -extfile "$ext" -out "$dir/$name.crt" 2>/dev/null
|
||||
rm -f "$dir/$name.csr" "$ext"
|
||||
echo "issued $name ($caname, $DAYS_LEAF days)"
|
||||
}
|
||||
|
||||
ca public-ca "MTUSI lab7 Public Ingress CA" "$OP/ca"
|
||||
ca internal-ca "MTUSI lab7 Internal Services CA" "$OP/ca"
|
||||
# rogue CA — тестовый, его ключ не секретен для стенда (лежит в secrets/pki/test).
|
||||
if [ ! -s "$OUT/test/rogue-ca.key" ]; then
|
||||
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$OUT/test/rogue-ca.key" 2>/dev/null
|
||||
openssl req -x509 -new -key "$OUT/test/rogue-ca.key" -sha256 -days 30 -subj "/O=Attacker/CN=Rogue CA" \
|
||||
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign" \
|
||||
-out "$OUT/test/rogue-ca.crt"
|
||||
cp "$OP/ca/internal-ca.srl" "$OP/ca/rogue-ca.srl" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
BOTH=serverAuth,clientAuth
|
||||
# Внешние (public CA): клиенты проверяют hostname localhost / 127.0.0.1.
|
||||
leaf public-ca lb-public serverAuth DNS:localhost IP:127.0.0.1
|
||||
leaf public-ca grafana-public serverAuth DNS:localhost IP:127.0.0.1
|
||||
# Внутренние identities (internal CA). SAN DNS = имя сервиса Compose = проверяемая identity.
|
||||
# lb — клиентская identity LB для mTLS к API (и серверная для scrape :8404).
|
||||
leaf internal-ca lb "$BOTH" DNS:lb
|
||||
leaf internal-ca api "$BOTH" DNS:api
|
||||
for s in worker relay janitor migrate s3-init ops grafana; do
|
||||
leaf internal-ca "$s" clientAuth "DNS:$s"
|
||||
done
|
||||
leaf internal-ca db serverAuth DNS:db DNS:localhost
|
||||
for s in s3 broker otel-collector prometheus loki tempo openbao; do
|
||||
leaf internal-ca "$s" "$BOTH" "DNS:$s" DNS:localhost IP:127.0.0.1
|
||||
done
|
||||
# Отрицательные тесты: доверенный CA, но запрещённая identity; чужой CA с «правильным» SAN lb.
|
||||
leaf internal-ca intruder "$BOTH" DNS:intruder
|
||||
leaf rogue-ca rogue-lb "$BOTH" DNS:lb
|
||||
|
||||
# HAProxy читает сертификат и ключ одним PEM.
|
||||
cat "$OUT/lb-public.crt" "$OUT/lb-public.key" > "$OUT/lb-public.pem"
|
||||
cat "$OUT/lb.crt" "$OUT/lb.key" > "$OUT/lb.pem"
|
||||
chmod 600 "$OP/ca/"*
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# Перезапуск ВСЕХ хранилищ — данных (PostgreSQL, SeaweedFS S3, RabbitMQ), секретов (OpenBao) и
|
||||
# телеметрии (Prometheus, Loki, Tempo) — и всех процессов (API-реплики, relay, worker, janitor, LB,
|
||||
# Collector, Grafana) с сохранением volumes. Не выполняет down -v, не пересоздаёт БД/bucket/очереди.
|
||||
#
|
||||
# Lab7: OpenBao после рестарта sealed — это хук ОПЕРАТОРА, поэтому он выполняет unseal
|
||||
# (scripts/bao-unseal.sh, 2 из 3 shares из $OPERATOR_DIR вне проекта). Процессы приложения
|
||||
# заново проходят cert auth и читают свои секреты; старые токены не нужны.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose restart openbao db s3 broker prometheus loki tempo
|
||||
./scripts/bao-unseal.sh >/dev/null
|
||||
docker compose up -d --no-deps --no-recreate --wait openbao db s3 broker prometheus
|
||||
docker compose restart otel-collector api relay worker janitor lb grafana
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка перед commit (lab7): значения секретов не встречаются ни в одном файле репозитория
|
||||
вне secrets/ и .env. Значения не печатаются — только имена файлов.
|
||||
|
||||
Источники значений:
|
||||
* secrets/**: пароли, ключи S3, password_hash RabbitMQ, ЗАКРЫТЫЕ КЛЮЧИ leaf (тело PEM по строкам);
|
||||
* $OPERATOR_DIR (по умолчанию ~/.mtusi2026lab7-operator): закрытые ключи CA, root token и
|
||||
unseal shares OpenBao (init.json).
|
||||
Публичные сертификаты (*.crt) секретом не являются и не проверяются.
|
||||
python3 scripts/scan_secrets.py (код 0 — чисто)"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OPERATOR_DIR = Path(os.environ.get("OPERATOR_DIR", Path.home() / ".mtusi2026lab7-operator"))
|
||||
SKIP_DIRS = {".git", "secrets", ".venv", "__pycache__", "node_modules"}
|
||||
values = set()
|
||||
|
||||
|
||||
def add_pem(text):
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if len(line) >= 16 and not line.startswith("-----"):
|
||||
values.add(line)
|
||||
|
||||
|
||||
def walk(x):
|
||||
if isinstance(x, dict):
|
||||
for k, v in x.items():
|
||||
if k in ("accessKey", "secretKey", "password_hash", "root_token", "unseal_keys_b64", "unseal_keys_hex"):
|
||||
for item in (v if isinstance(v, list) else [v]):
|
||||
values.add(str(item))
|
||||
walk(v)
|
||||
elif isinstance(x, list):
|
||||
for v in x:
|
||||
walk(v)
|
||||
|
||||
|
||||
sources = [f for f in (ROOT / "secrets").rglob("*") if f.is_file() and f.suffix != ".crt"]
|
||||
sources += [f for f in OPERATOR_DIR.rglob("*") if f.is_file()] if OPERATOR_DIR.is_dir() else []
|
||||
for f in sources:
|
||||
text = f.read_text(encoding="utf-8", errors="replace").strip()
|
||||
if f.suffix == ".json":
|
||||
walk(json.loads(text))
|
||||
elif "PRIVATE KEY" in text:
|
||||
add_pem(text)
|
||||
elif len(text) >= 8 and "\n" not in text:
|
||||
values.add(text)
|
||||
if "://" in text and "@" in text:
|
||||
values.add(text.split("://", 1)[1].split("@", 1)[0].split(":", 1)[-1])
|
||||
hits = []
|
||||
for p in ROOT.rglob("*"):
|
||||
if p.is_dir() or set(p.relative_to(ROOT).parts) & SKIP_DIRS or p.name == ".env":
|
||||
continue
|
||||
try:
|
||||
data = p.read_text(encoding="utf-8", errors="ignore")
|
||||
except OSError:
|
||||
continue
|
||||
if any(v in data for v in values):
|
||||
hits.append(str(p.relative_to(ROOT)))
|
||||
print("checked %d secret values from %d files; files with leaks: %s" % (len(values), len(sources), hits or "none"))
|
||||
sys.exit(1 if hits else 0)
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Восстанавливает остановленные API-реплики и worker (после stop-one.sh / stop-worker.sh) и ждёт готовности.
|
||||
# --no-deps: хранилища и job-ы не трогаются; --no-recreate: те же контейнеры (тот же образ).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose up -d --no-deps --no-recreate --wait api worker
|
||||
docker compose ps --format '{{.Name}} {{.Status}}' api worker
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
# Запустить worker после stop-worker.sh (те же контейнеры) и дождаться готовности.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose up -d --no-deps --no-recreate --wait worker
|
||||
docker compose ps --format '{{.Name}} {{.Status}}' worker
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
# Останавливает ОДНУ API-реплику, обслужившую тест, и оставляет её остановленной.
|
||||
# Lab7: TARGET_INSTANCE_ID = X-Instance-Id = СЛУЧАЙНЫЙ alias процесса (r-<10 hex>), не hostname.
|
||||
# Реплика пишет свой alias в /tmp/instance-id (tmpfs) — сопоставляем через docker exec.
|
||||
# DB, LB и volumes не трогаются. Восстановление: scripts/start-all.sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
if ! printf '%s' "$TARGET_INSTANCE_ID" | grep -Eq '^r-[0-9a-f]{10}$'; then
|
||||
echo "unexpected instance id format" >&2
|
||||
exit 2
|
||||
fi
|
||||
target=""
|
||||
for cid in $(docker compose ps -q --status running api); do
|
||||
alias=$(docker exec "$cid" cat /tmp/instance-id 2>/dev/null || true)
|
||||
if [ "$alias" = "$TARGET_INSTANCE_ID" ]; then
|
||||
target=$cid
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$target" ] || { echo "no running api container for $TARGET_INSTANCE_ID" >&2; exit 3; }
|
||||
name=$(docker inspect -f '{{.Name}}' "$target")
|
||||
echo "$(date -u +%FT%TZ) stopping api container $name ($TARGET_INSTANCE_ID)" >&2
|
||||
docker stop -t 20 "$target" >/dev/null
|
||||
echo "$(date -u +%FT%TZ) stopped $name" >&2
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Сценарий защиты: остановить ВСЕ worker (SIGTERM, текущие задания дорабатываются).
|
||||
# API, relay и брокер продолжают работать: upload -> 202, задания копятся в очереди.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop worker
|
||||
docker compose ps --format '{{.Name}} {{.State}}' worker
|
||||
@@ -1,19 +1,74 @@
|
||||
# Модель угроз — заполнить
|
||||
# Модель угроз — мессенджер lab7 (Лазарев Ю. С., БПИ2303)
|
||||
|
||||
Учебный стенд на одном Docker-host (Docker Desktop, macOS), синтетические данные. Модель — для заявленной оценки «3»; уровни 4/5 не заявлены, известные пробелы перечислены в «Остаточных ограничениях».
|
||||
|
||||
## Активы и акторы
|
||||
|
||||
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
|
||||
**Активы**
|
||||
|
||||
| Актив | Где живёт | Чем защищён |
|
||||
| --- | --- | --- |
|
||||
| Пароли пользователей | только хеш Argon2id (m=19 MiB, t=2, p=1, соль 16 байт) в `users.password_hash` | KDF, rehash устаревших схем при входе; plaintext — только в памяти обработчика входа |
|
||||
| Сессии | SHA-256 токена (256 бит энтропии) в `sessions`, TTL 3600 с | токен у клиента, в БД только хеш; отзыв logout; expiry проверяется в SQL |
|
||||
| Сообщения, вложения | PostgreSQL (метаданные/тексты), SeaweedFS (байты, приватный bucket) | ACL участника чата в API (посторонний → 404), TLS ко всем хранилищам |
|
||||
| Service identities | leaf-сертификаты сервисов (ключ — Docker secret только своего контейнера) | срок 30 дней, проверка SAN на стороне сервера |
|
||||
| CA private keys | `$OPERATOR_DIR/ca` (вне проекта, 600) | не монтируются ни в один контейнер |
|
||||
| Сервисные credentials (роли БД, ключи S3, пароли брокера) | OpenBao KV v2 `kv/messenger/<svc>` (+ исходники в `secrets/` оператора) | cert auth + policy только своего пути, TTL токена 15 мин |
|
||||
| Root token и unseal shares OpenBao | `$OPERATOR_DIR/openbao/init.json` (600) | только у оператора, не в контейнерах и не в Git |
|
||||
| Телеметрия | Prometheus/Loki/Tempo | mTLS на приёме, scrub атрибутов в Collector, токены/пароли/тексты не пишутся |
|
||||
|
||||
**Акторы**
|
||||
|
||||
- *Участник чата* — аутентифицирован Bearer, читает/пишет свой чат.
|
||||
- *Посторонний пользователь* — валидная сессия, но не участник чата; цель — чужие сообщения/файлы.
|
||||
- *Внешний клиент без учётной записи* — доступ только к `127.0.0.1:8443` (TLS), может перебирать пароли, слать большие тела.
|
||||
- *Сетевой атакующий внутри стенда* — процесс/контейнер в одной из внутренних сетей Docker без ключей сервисов (модель «скомпрометированный соседний контейнер» или подключённый к сети `docker run --network`).
|
||||
- *Скомпрометированный сервис* — атакующий получил код/ключ одного сервиса (например worker): его cert-identity, его токен OpenBao, его роль БД.
|
||||
- *Оператор* — владелец хоста, CA и unseal shares; доверенный.
|
||||
|
||||
**Границы учебного стенда.** Хост и Docker daemon — доверенные (root на хосте = полный доступ, в модели не защищаемся). Нет HA: один узел каждого хранилища. Нет защиты от DoS на уровне сети (только rate limit входа и лимиты ресурсов).
|
||||
|
||||
## Границы доверия
|
||||
|
||||
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
|
||||
Полная матрица: [contracts/trust-matrix.md](../contracts/trust-matrix.md).
|
||||
|
||||
```
|
||||
хост 127.0.0.1:8443 ──TLS(public-ca)──► lb ══mTLS(id lb)══► api×2 ──TLS verify-full──► db
|
||||
│ apinet(internal) │──HTTPS──────────────► s3
|
||||
хост 127.0.0.1:3000 ──TLS(public-ca)──► grafana │──mTLS OTLP──► otel-collector ══mTLS══► prometheus/loki/tempo
|
||||
│ └──TLS+cert auth──► openbao (сеть vault)
|
||||
relay/worker ──AMQPS──► broker; worker ──HTTPS──► s3; все ──verify-full──► db
|
||||
```
|
||||
|
||||
- **Публичные интерфейсы:** только `127.0.0.1:8443` (HTTPS API) и `127.0.0.1:3000` (HTTPS Grafana, вход admin). Остальное — в internal-сетях Docker без публикации портов.
|
||||
- **Внутренние сети:** `apinet` (lb↔api), `backend` (данные), `telemetry`, `vault` (OpenBao только для процессов приложения). LB не видит БД/S3/брокер/OpenBao; Grafana не видит данные приложения.
|
||||
- **Выдача секретов:** оператор → `init-secrets.sh` (PKI, пароли) → `bao-init.sh` (KV, policies, cert-роли) → процесс сервиса: свой сертификат (Docker secret) → cert login → токен со scoped policy → свой KV-путь. В env/образе секретов нет.
|
||||
|
||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO | TODO |
|
||||
| T1. Обход LB: контейнер в сети `apinet`/`backend` обращается к `api:8443` напрямую (без сертификата или со своим сертификатом от internal-ca, например worker/intruder) и вызывает бизнес-API, минуя rate limit и логирование LB | «Бизнес-API доступен только через LB» | mTLS на API: `CERT_REQUIRED` + SAN ∈ `MTLS_ALLOWED_CLIENTS={lb}`; порт не опубликован; health plaintext только на 127.0.0.1 | M: `LB->API[*]` — без cert, rogue CA, `intruder`, plaintext, `:8081` из сети → отказ; `lb` → 200 | Ключ LB даёт доступ к API (но не к данным без Bearer) — компрометация LB = обход rate limit |
|
||||
| T2. Поддельный сервер: атакующий в сети подменяет `db`/`s3`/`openbao` (DNS-спуфинг в сети Docker) и получает пароль роли/ключ S3/токен | «Credentials уходят только настоящему серверу» | Все клиенты проверяют CA internal-ca + hostname (verify-full, `check_hostname`, `server_hostname`, `verifyhost`); fallback на plaintext нет | M: rogue CA как trust / подключение по IP / чужой ожидаемый hostname → ошибка проверки сертификата для db, s3, broker, collector, backends, openbao | Компрометация internal-ca key = возможность выпустить любой сертификат (ключ у оператора вне стенда) |
|
||||
| T3. Посторонний пользователь читает чужой чат/вложение или прикрепляет чужой файл к своему сообщению, подставляет `X-User-Id` | «Доступ к чату — только участникам; identity = Bearer» | ACL в API (участие в чате проверяется в каждом запросе, 404 без раскрытия существования), `X-User-Id` игнорируется, Basic на бизнес-endpoint → 401 | A: `outsider.*` (chat/history/metadata/content/thumbnail/attach/post → 404, список чатов без чужого), `spoof.*`, `auth.basic_on_business_endpoint_401` | Участник чата может скачивать все его вложения (по контракту) |
|
||||
| T4. Онлайн-перебор паролей и «дорогой login DoS» через `POST /auth/sessions` | «Вход не позволяет перебор и не выбивает реплики по CPU/RAM» | Rate limit на LB (20/10 с с IP → 429 + Retry-After, общий для реплик), Argon2id с ограничением параллелизма `PASSWORD_HASH_CONCURRENCY=2` (+503 при переполнении), одинаковый 401 и dummy-hash для неизвестного логина | A: `ratelimit.login_429_with_retry_after` (429 на 21-й попытке, `Retry-After: 10`), `auth.same_401_unknown_user_and_wrong_password`; замер стоимости хеша — evidence/argon2-bench.json | Лимит по IP: распределённый перебор с многих IP не ограничен; за NAT/Docker все клиенты хоста — один IP |
|
||||
| T5. Утечка таблицы `users`/`sessions` (бэкап, SQL-инъекция в будущем коде, скомпрометированная роль) | «Из БД нельзя получить пароль или готовую сессию» | Argon2id с солью и параметрами в PHC-строке; в `sessions` — только SHA-256 токена; worker/relay/janitor вообще не имеют SELECT на `users`/`sessions` | A: `argon2.stored_format`, `argon2.unique_salt`, `argon2.rehash_legacy_scrypt_on_login`; B: worker `select_users/sessions` → denied | Офлайн-перебор слабых паролей Argon2id (19 MiB) всё ещё возможен; политика сложности паролей — только длина 12+ |
|
||||
| T6. Компрометация worker (RCE через вредоносное изображение) → чтение секретов других сервисов, хешей паролей, сообщений; запись произвольных policy в OpenBao | «Worker не получает admin/чужих credentials» | Отдельная cert-identity и policy `messenger-worker` (read только `kv/data/messenger/worker`); роль БД `worker_svc` без доступа к users/sessions/chats/messages; свой S3-ключ; transform в подпроцессе с RLIMIT, контейнер non-root, read-only, без capabilities, лимиты CPU/RAM/PIDs | B: worker — чужой путь, `migrate`, list, запись, policy, token create, seal → 403; S3-ключ = worker, не admin/api; DB denied; H: `worker.*` (uid 10001, cap_drop ALL, read-only) | Worker читает все вложения bucket (права по bucket, не по prefix) и может писать в jobs/attachments |
|
||||
| T7. Утечка секретов через репозиторий, образ, env или телеметрию (Bearer в логах, пароль в атрибутах span, ключ в слое образа) | «Секреты не покидают своих хранилищ» | `.gitignore`/`.dockerignore` (secrets/, *.key, *.pem), секреты только из OpenBao (в env — нет), scrub в Collector, приложение не логирует заголовки/тела | H: `repo.scan_secrets_clean` (125 значений, вкл. CA keys/root token/shares), `image.*`, `*.no_secret_values_in_env`, `telemetry.loki_no_*` с положительным контролем, `telemetry.tempo_no_token_or_password` | Root на хосте видит всё (`docker inspect`, `/run/secrets`) |
|
||||
| T8. Попытка получить root/широкий токен OpenBao из приложения или переиспользовать украденный токен долго | «Приложение не держит root/безграничный токен» | cert auth → service token, TTL 15 мин, max 1 ч; нет BAO_TOKEN/SecretID в env; revoke-self работает сразу | B: `*.no_token_in_env`, `token_ttl_bounded`, `deny_create_token`, `revoked_token_denied` | Украденный ключ сервиса = повторный login до истечения сертификата (30 дней) или удаления роли; CRL/OCSP не реализованы |
|
||||
| T9. Подмена/чтение телеметрии: произвольный контейнер шлёт фальшивые метрики/логи в Collector или читает Loki/Prometheus | «Ingest и чтение телеметрии — только у сервисов стенда» | mTLS на Collector и всех backend-ах (client cert internal-ca обязателен), сети `telemetry` internal | M: Collector/Prometheus/Loki/Tempo/lb:8404 без cert, rogue CA → отказ | Любой сертификат internal-ca принимается (role не проверяется) — уровень 4 |
|
||||
| T10. Большие тела запросов / zip-бомба изображения истощают память API | «Реплика не падает по OOM от одного клиента» | 1 MiB JSON, 10 MiB upload (Content-Length до чтения), 40 Мпикс до декодирования, подпроцесс проверки JPEG с RLIMIT_AS, cgroup-лимиты, tmpfs 160 MiB | A: `limits.json_body_over_1mib_413`, `limits.upload_over_10mib_413`; lab5: transform_limits | Медленные клиенты (slowloris) ограничены таймаутами LB, отдельно в lab7 не тестировались |
|
||||
|
||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
||||
|
||||
## Lifecycle и инциденты
|
||||
|
||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
||||
**Bootstrap.** Оператор: `./scripts/init-secrets.sh` — пароли сервисов и PKI (OpenSSL закреплённого образа, `--network none`; ключи CA → `$OPERATOR_DIR/ca`, leaf → `secrets/pki`). `./scripts/bao-init.sh` — `operator init` (3 shares, порог 2 → `$OPERATOR_DIR/openbao/init.json`), unseal, KV v2, policies, роли auth/cert, запись KV. Первый секрет для доступа к OpenBao у сервиса — его собственный leaf-ключ (Docker secret); отдельного SecretID нет. Trust anchor — `internal-ca.crt`.
|
||||
|
||||
**Expiry/renewal.** Токен OpenBao: renew-self на половине TTL, после max TTL — новый login (src/vault.py). Сертификаты leaf — 30 дней, CA — 365 дней; продление: удалить leaf-файлы и снова `init-secrets.sh` (выпустит недостающие), затем `docker compose up -d --force-recreate <svc>`. Автоматического renewal сертификатов нет (уровень 4/5).
|
||||
|
||||
**Revoke/rotation.** Отзыв identity сервиса в OpenBao — `bao delete auth/cert/certs/<svc>` (новые логины невозможны), отзыв действующих токенов — `bao token revoke -mode=path auth/cert/login`. Для mTLS к API отзыв = исключение SAN из `MTLS_ALLOWED_CLIENTS` или смена CA; CRL не используется. Ротация секрета: новое значение в `secrets/` → `bao-init.sh` (перезапишет KV) → для роли БД `docker compose up migrate` → рестарт сервиса (новый login читает новое значение). В рамках «3» не демонстрировалось.
|
||||
|
||||
**Компрометация identity.** Пример worker: удалить роль `auth/cert/certs/worker`, отозвать токены, выпустить новый leaf worker, сменить пароли `worker_svc`/S3-ключ worker/брокера в `secrets/`, `bao-init.sh`, `migrate`, пересоздать broker/s3 (identities/definitions), пересоздать worker. Задания не теряются: они в outbox/очереди и повторно доставляются (at-least-once, lab5).
|
||||
|
||||
**Sealed OpenBao и восстановление.** После рестарта контейнера OpenBao — sealed (B: `sealed.after_restart_sealed`). Работающие процессы продолжают обслуживать (секреты в памяти; renew падает → предупреждение `vault.renew_failed`, повтор с backoff до 30 с). Новые/перезапущенные процессы не становятся ready (B: `sealed.restarted_replica_not_healthy`), через 300 с без OpenBao завершаются и перезапускаются Docker. Восстановление: оператор `./scripts/bao-unseal.sh` → реплика healthy за ~12 с (B). Данные KV — на Raft-volume (B: `sealed.kv_persisted_after_restart`). Владелец CA и unseal — оператор (единственный человек с доступом к `$OPERATOR_DIR`); unseal shares хранятся отдельно от OpenBao, но на том же хосте — это учебный компромисс (в production — разные хранители shares/KMS auto-unseal).
|
||||
|
||||
**Scan findings.** Dependency/image scan (pip-audit/Trivy) с разбором применимости — пункт уровня 4, в этой работе не выполнялся. Учтённые известные проблемы зависимостей унаследованы из lab5 (Pillow 13.0.0 — GHSA-wqgw-9xfh-qf2g, urllib3 2.8.0 — GHSA-vxq7-64xx-v4gw). Новая зависимость lab7 — `argon2-cffi 25.1.0` (последняя версия на момент работы).
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
"""Общее для фоновых процессов lab5 (relay, worker, ops): конфигурация, БД, брокер.
|
||||
|
||||
API (server.py) брокер не использует вовсе: он только пишет outbox в PostgreSQL.
|
||||
Поэтому недоступность RabbitMQ не влияет на приём файлов — задания копятся в outbox.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import pika
|
||||
from psycopg.conninfo import make_conninfo
|
||||
|
||||
import tlsutil
|
||||
import vault
|
||||
from instance import INSTANCE_ID
|
||||
|
||||
# Lab6: логирование (JSON stdout + OTLP) настраивает telemetry.setup() в main() каждого процесса.
|
||||
logging.getLogger("pika").setLevel(logging.WARNING)
|
||||
|
||||
# Топология брокера (объявляется декларативно в secrets/rabbitmq_definitions.json,
|
||||
# приложения её не создают — у их пользователей нет права configure).
|
||||
EXCHANGE = "attachments"
|
||||
ROUTING_KEY = "attachment.process.v1"
|
||||
QUEUE = "attachments.process.v1"
|
||||
DLQ = "attachments.dlq"
|
||||
|
||||
HOSTNAME = socket.gethostname()
|
||||
# Идентификатор процесса для lease_owner: hostname контейнера + случайный boot id.
|
||||
BOOT_ID = uuid.uuid4().hex[:8]
|
||||
OWNER = "%s:%s" % (HOSTNAME, BOOT_ID)
|
||||
|
||||
|
||||
def env_int(name, default):
|
||||
return int(os.environ.get(name, str(default)))
|
||||
|
||||
|
||||
def env_float(name, default):
|
||||
return float(os.environ.get(name, str(default)))
|
||||
|
||||
|
||||
def secret(name):
|
||||
"""Lab7: из OpenBao (src/vault.py); NAME_FILE/NAME — только для инфраструктурных job/тестов."""
|
||||
return vault.secret(name)
|
||||
|
||||
|
||||
def database_conninfo():
|
||||
options = "-c statement_timeout=%d" % env_int("DB_STATEMENT_TIMEOUT_MS", 5000)
|
||||
url = vault.secret("DATABASE_URL", required=False)
|
||||
if url:
|
||||
return make_conninfo(url, connect_timeout=3, options=options, sslmode="verify-full",
|
||||
sslrootcert=os.environ.get("DB_SSLROOTCERT", tlsutil.CA_FILE))
|
||||
return make_conninfo(
|
||||
host=os.environ.get("POSTGRES_HOST", "localhost"),
|
||||
port=os.environ.get("POSTGRES_PORT", "5432"),
|
||||
dbname=os.environ.get("POSTGRES_DB", "messenger"),
|
||||
user=os.environ.get("POSTGRES_USER", "messenger"),
|
||||
password=secret("POSTGRES_PASSWORD"),
|
||||
connect_timeout=3,
|
||||
sslmode=os.environ.get("DB_SSLMODE", "verify-full"),
|
||||
sslrootcert=os.environ.get("DB_SSLROOTCERT", tlsutil.CA_FILE),
|
||||
options=options,
|
||||
)
|
||||
|
||||
|
||||
def broker_parameters():
|
||||
"""amqp URL из BROKER_URL_FILE: у relay, worker и ops — разные пользователи RabbitMQ."""
|
||||
params = pika.URLParameters(secret("BROKER_URL"))
|
||||
# Lab7: AMQPS (5671) — проверка CA и hostname брокера; клиентский сертификат сервиса
|
||||
# предъявляется (RabbitMQ verify_peer). Plaintext 5672 у брокера выключен.
|
||||
if params.port == 5671 or os.environ.get("BROKER_TLS", "1") == "1":
|
||||
params.ssl_options = pika.SSLOptions(tlsutil.client_context(),
|
||||
server_hostname=os.environ.get("BROKER_TLS_SERVER_NAME", params.host))
|
||||
# heartbeat: брокер закроет соединение мёртвого/замороженного клиента и вернёт его unacked
|
||||
# сообщения в очередь (в т.ч. выданные заранее по prefetch). 10 с: эксперимент
|
||||
# lease_takeover показал, что при 20 с такое сообщение висело ~35 с. Worker обрабатывает
|
||||
# задание в отдельном потоке и продолжает обслуживать heartbeat (process_data_events),
|
||||
# поэтому долгая обработка соединение не рвёт.
|
||||
params.heartbeat = env_int("BROKER_HEARTBEAT_SECONDS", 10)
|
||||
params.blocked_connection_timeout = 30
|
||||
params.socket_timeout = 5
|
||||
params.connection_attempts = 1
|
||||
params.client_properties = {"connection_name": "%s-%s" % (os.environ.get("SERVICE_NAME", "app"), HOSTNAME)}
|
||||
return params
|
||||
|
||||
|
||||
def connect_broker(log, stop=None):
|
||||
"""Подключение с повторами и паузой до 5 с; stop — threading.Event для выхода."""
|
||||
delay = 0.5
|
||||
while True:
|
||||
try:
|
||||
return pika.BlockingConnection(broker_parameters())
|
||||
except Exception as exc:
|
||||
log.warning("broker unavailable (%s), retry in %.1fs", type(exc).__name__, delay,
|
||||
extra={"event": "broker.unavailable", "error.type": type(exc).__name__})
|
||||
if stop is not None and stop.wait(delay):
|
||||
return None
|
||||
if stop is None:
|
||||
time.sleep(delay)
|
||||
delay = min(5.0, delay * 2)
|
||||
|
||||
|
||||
def touch(path):
|
||||
with open(path, "w") as f:
|
||||
f.write(str(time.time()))
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
"""Проверка загружаемых изображений по СОДЕРЖИМОМУ, с ограниченной памятью.
|
||||
|
||||
Заголовок Content-Type клиента — только заявление: настоящий формат определяется
|
||||
по сигнатуре и структуре файла. Лимит пикселей проверяется по заголовку (PNG IHDR,
|
||||
JPEG SOF) ДО распаковки, поэтому «бомба» 100 000×100 000 не декодируется вовсе.
|
||||
|
||||
PNG проверяется собственным потоковым валидатором (стандартная библиотека):
|
||||
структура и CRC каждого chunk, допустимые IHDR, IDAT распаковывается zlib кусками
|
||||
по 1 MiB без сохранения результата; объём распакованных данных должен ТОЧНО совпасть
|
||||
с размером, который следует из IHDR (больше — бомба/мусор, меньше — обрезанный файл).
|
||||
|
||||
JPEG: разбор маркеров до SOF (размеры), затем пробное декодирование Pillow в режиме
|
||||
draft (масштаб 1/8) в ОТДЕЛЬНОМ процессе с лимитами (src/jpeg_probe.py). Для baseline JPEG
|
||||
draft экономит память, но progressive JPEG держит DCT-коэффициенты всего кадра: до ~250 MiB
|
||||
на 40 Мпикс (аудит F02) — поэтому не в процессе API.
|
||||
|
||||
PNG (аудит F05): кроме CRC/zlib/объёма проверяется байт фильтра КАЖДОЙ строки (0..4),
|
||||
включая проходы Adam7, а также PLTE (кратна 3, <= 256 записей) и пустой IEND.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_SOI = b"\xff\xd8\xff"
|
||||
READ_CHUNK = 64 * 1024
|
||||
INFLATE_STEP = 1024 * 1024
|
||||
|
||||
# Допустимые глубины цвета по типу цвета PNG и число каналов.
|
||||
_PNG_DEPTHS = {0: {1, 2, 4, 8, 16}, 2: {8, 16}, 3: {1, 2, 4, 8}, 4: {8, 16}, 6: {8, 16}}
|
||||
_PNG_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||
# Adam7: (x0, y0, dx, dy)
|
||||
_ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||||
_JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
||||
|
||||
|
||||
class InvalidImage(Exception):
|
||||
"""Файл не является корректным PNG/JPEG заявленного типа -> 415."""
|
||||
|
||||
|
||||
class TooManyPixels(Exception):
|
||||
"""Декодированный размер превышает лимит -> 413."""
|
||||
|
||||
|
||||
class ResourceLimit(Exception):
|
||||
"""Проверка не уложилась в лимиты памяти/времени -> 413 (вход слишком тяжёлый)."""
|
||||
|
||||
|
||||
JPEG_PROBE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "jpeg_probe.py")
|
||||
JPEG_PROBE_TIMEOUT_SECONDS = float(os.environ.get("JPEG_PROBE_TIMEOUT_SECONDS", "15"))
|
||||
|
||||
|
||||
def sniff(head):
|
||||
"""Тип по сигнатуре первых байтов: 'image/png', 'image/jpeg' или None."""
|
||||
if head.startswith(PNG_SIGNATURE):
|
||||
return "image/png"
|
||||
if head.startswith(JPEG_SOI):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def png_header_pixels(head):
|
||||
"""Ранняя проверка по первым 33 байтам (сигнатура + IHDR): (w, h) или None."""
|
||||
if len(head) < 33 or not head.startswith(PNG_SIGNATURE) or head[12:16] != b"IHDR":
|
||||
return None
|
||||
return struct.unpack(">II", head[16:24])
|
||||
|
||||
|
||||
def _read_exact(f, n):
|
||||
data = f.read(n)
|
||||
if len(data) != n:
|
||||
raise InvalidImage("truncated")
|
||||
return data
|
||||
|
||||
|
||||
def _png_passes(w, h, bits_per_pixel, interlace):
|
||||
"""[(строк, байт в строке вместе с байтом фильтра)] для каждого непустого прохода."""
|
||||
def row(pw):
|
||||
return 1 + (pw * bits_per_pixel + 7) // 8
|
||||
if interlace == 0:
|
||||
return [(h, row(w))]
|
||||
out = []
|
||||
for x0, y0, dx, dy in _ADAM7:
|
||||
pw = (w - x0 + dx - 1) // dx if w > x0 else 0
|
||||
ph = (h - y0 + dy - 1) // dy if h > y0 else 0
|
||||
if pw and ph:
|
||||
out.append((ph, row(pw)))
|
||||
return out
|
||||
|
||||
|
||||
class _FilterCheck:
|
||||
"""Байт фильтра в начале каждой строки распакованных данных PNG должен быть 0..4.
|
||||
Проверка срезами bytes[first::rowbytes] — скорость C, без цикла Python по строкам
|
||||
(иначе PNG 1x40 000 000 стал бы атакой на CPU)."""
|
||||
|
||||
def __init__(self, passes):
|
||||
self.passes = passes
|
||||
self.index = 0
|
||||
self.offset = 0 # байт уже пройдено в текущем проходе
|
||||
|
||||
def feed(self, out):
|
||||
i, n = 0, len(out)
|
||||
while i < n:
|
||||
if self.index >= len(self.passes):
|
||||
raise InvalidImage("too much pixel data")
|
||||
rows, rb = self.passes[self.index]
|
||||
total = rows * rb
|
||||
take = min(n - i, total - self.offset)
|
||||
first = (-self.offset) % rb
|
||||
if first < take and max(out[i + first:i + take:rb]) > 4:
|
||||
raise InvalidImage("bad filter type")
|
||||
i += take
|
||||
self.offset += take
|
||||
if self.offset == total:
|
||||
self.index += 1
|
||||
self.offset = 0
|
||||
|
||||
|
||||
def _png_expected_bytes(w, h, bits_per_pixel, interlace):
|
||||
def raw(pw, ph):
|
||||
return ph * (1 + (pw * bits_per_pixel + 7) // 8) if pw and ph else 0
|
||||
if interlace == 0:
|
||||
return raw(w, h)
|
||||
total = 0
|
||||
for x0, y0, dx, dy in _ADAM7:
|
||||
pw = (w - x0 + dx - 1) // dx if w > x0 else 0
|
||||
ph = (h - y0 + dy - 1) // dy if h > y0 else 0
|
||||
total += raw(pw, ph)
|
||||
return total
|
||||
|
||||
|
||||
def validate_png(f, size, max_pixels):
|
||||
if _read_exact(f, 8) != PNG_SIGNATURE:
|
||||
raise InvalidImage("signature")
|
||||
pos = 8
|
||||
width = height = None
|
||||
expected = produced = 0
|
||||
inflater = None
|
||||
seen_plte = idat_done = False
|
||||
color_type = None
|
||||
last_type = None
|
||||
while True:
|
||||
if pos + 12 > size:
|
||||
raise InvalidImage("truncated")
|
||||
length, ctype = struct.unpack(">I4s", _read_exact(f, 8))
|
||||
pos += 8
|
||||
if length > 0x7FFFFFFF or pos + length + 4 > size:
|
||||
raise InvalidImage("chunk length")
|
||||
if not ctype.isalpha():
|
||||
raise InvalidImage("chunk type")
|
||||
if width is None and ctype != b"IHDR":
|
||||
raise InvalidImage("IHDR must be first")
|
||||
crc = zlib.crc32(ctype)
|
||||
if ctype == b"IDAT":
|
||||
if idat_done or (color_type == 3 and not seen_plte):
|
||||
raise InvalidImage("IDAT order")
|
||||
remaining = length
|
||||
while remaining:
|
||||
piece = _read_exact(f, min(READ_CHUNK, remaining))
|
||||
remaining -= len(piece)
|
||||
crc = zlib.crc32(piece, crc)
|
||||
buf = piece
|
||||
while buf:
|
||||
if inflater.eof:
|
||||
raise InvalidImage("data after zlib stream")
|
||||
try:
|
||||
out = inflater.decompress(buf, INFLATE_STEP)
|
||||
except zlib.error:
|
||||
raise InvalidImage("zlib")
|
||||
produced += len(out)
|
||||
if produced > expected:
|
||||
raise InvalidImage("too much pixel data") # бомба/мусор
|
||||
filters.feed(out)
|
||||
buf = inflater.unconsumed_tail
|
||||
else:
|
||||
if last_type == b"IDAT":
|
||||
idat_done = True
|
||||
data = _read_exact(f, length)
|
||||
crc = zlib.crc32(data, crc)
|
||||
if ctype == b"IHDR":
|
||||
if width is not None or length != 13:
|
||||
raise InvalidImage("IHDR")
|
||||
width, height, depth, color_type, comp, filt, interlace = struct.unpack(">IIBBBBB", data)
|
||||
if not (1 <= width <= 0x7FFFFFFF and 1 <= height <= 0x7FFFFFFF):
|
||||
raise InvalidImage("dimensions")
|
||||
if width * height > max_pixels:
|
||||
raise TooManyPixels()
|
||||
if depth not in _PNG_DEPTHS.get(color_type, ()) or comp != 0 or filt != 0 or interlace not in (0, 1):
|
||||
raise InvalidImage("IHDR values")
|
||||
expected = _png_expected_bytes(width, height, _PNG_CHANNELS[color_type] * depth, interlace)
|
||||
filters = _FilterCheck(_png_passes(width, height, _PNG_CHANNELS[color_type] * depth, interlace))
|
||||
inflater = zlib.decompressobj()
|
||||
elif ctype == b"PLTE":
|
||||
# PLTE: кратна 3, 1..256 записей, только одна, не для серых типов, до IDAT.
|
||||
if seen_plte or length == 0 or length % 3 or length > 768 or color_type in (0, 4) \
|
||||
or last_type == b"IDAT" or idat_done:
|
||||
raise InvalidImage("PLTE")
|
||||
seen_plte = True
|
||||
elif ctype == b"IEND":
|
||||
if length != 0:
|
||||
raise InvalidImage("IEND")
|
||||
elif ctype[0:1].isupper():
|
||||
raise InvalidImage("unknown critical chunk") # декодер обязан его понимать
|
||||
if struct.unpack(">I", _read_exact(f, 4))[0] != crc & 0xFFFFFFFF:
|
||||
raise InvalidImage("crc")
|
||||
pos += length + 4
|
||||
last_type = ctype
|
||||
if ctype == b"IEND":
|
||||
break
|
||||
if inflater is None or not inflater.eof or produced != expected:
|
||||
raise InvalidImage("incomplete pixel data")
|
||||
if pos != size:
|
||||
raise InvalidImage("trailing data") # полиглоты PNG+что-то ещё не принимаем
|
||||
return width, height
|
||||
|
||||
|
||||
def jpeg_dimensions(f, size):
|
||||
"""Размеры из первого SOF без декодирования. Ограничено размером файла."""
|
||||
if _read_exact(f, 2) != b"\xff\xd8":
|
||||
raise InvalidImage("signature")
|
||||
pos = 2
|
||||
while pos < size:
|
||||
b = _read_exact(f, 1)
|
||||
pos += 1
|
||||
if b != b"\xff":
|
||||
raise InvalidImage("marker")
|
||||
marker = 0xFF
|
||||
while marker == 0xFF:
|
||||
marker = _read_exact(f, 1)[0]
|
||||
pos += 1
|
||||
if marker == 0x01 or 0xD0 <= marker <= 0xD7:
|
||||
continue
|
||||
if marker in (0xD8, 0xD9, 0xDA):
|
||||
raise InvalidImage("no SOF before scan")
|
||||
seg_len = struct.unpack(">H", _read_exact(f, 2))[0]
|
||||
if seg_len < 2 or pos + seg_len > size:
|
||||
raise InvalidImage("segment length")
|
||||
if marker in _JPEG_SOF:
|
||||
if seg_len < 8:
|
||||
raise InvalidImage("SOF")
|
||||
_precision, height, width = struct.unpack(">BHH", _read_exact(f, 5))
|
||||
if width == 0 or height == 0:
|
||||
raise InvalidImage("dimensions") # DNL-высота не поддерживается
|
||||
return width, height
|
||||
f.seek(seg_len - 2, 1)
|
||||
pos += seg_len
|
||||
raise InvalidImage("no SOF")
|
||||
|
||||
|
||||
def validate_jpeg(f, size, max_pixels):
|
||||
width, height = jpeg_dimensions(f, size)
|
||||
if width * height > max_pixels:
|
||||
raise TooManyPixels()
|
||||
if not hasattr(f, "fileno"):
|
||||
raise InvalidImage("probe needs a real file")
|
||||
f.flush()
|
||||
f.seek(0)
|
||||
try:
|
||||
# stdin подпроцесса — тот же временный файл (анонимный, O_TMPFILE): байты не копируются.
|
||||
proc = subprocess.run([sys.executable, JPEG_PROBE, str(max_pixels), str(width), str(height)],
|
||||
stdin=f, capture_output=True, timeout=JPEG_PROBE_TIMEOUT_SECONDS, check=False)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise ResourceLimit("timeout")
|
||||
finally:
|
||||
f.seek(0)
|
||||
if proc.returncode == 0:
|
||||
return width, height
|
||||
if proc.returncode == 3:
|
||||
raise InvalidImage("decode")
|
||||
raise ResourceLimit("probe exit %d" % proc.returncode) # 5 или убит сигналом (RLIMIT/OOM)
|
||||
|
||||
|
||||
def validate(f, size, content_type, max_pixels):
|
||||
"""(width, height) или InvalidImage/TooManyPixels. f — seekable файл, позиция 0."""
|
||||
f.seek(0)
|
||||
if content_type == "image/png":
|
||||
return validate_png(f, size, max_pixels)
|
||||
if content_type == "image/jpeg":
|
||||
return validate_jpeg(f, size, max_pixels)
|
||||
raise InvalidImage("type")
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Lab7: alias процесса для X-Instance-Id и service.instance.id.
|
||||
|
||||
Случайное значение на жизнь процесса: не раскрывает hostname/IP/ID контейнера. Чтобы
|
||||
scripts/stop-one.sh мог найти контейнер по alias, процесс пишет его в /tmp/instance-id
|
||||
(tmpfs контейнера; читается только через docker exec оператором).
|
||||
"""
|
||||
import os
|
||||
import secrets
|
||||
|
||||
if os.environ.get("INSTANCE_ID"):
|
||||
# Унаследован от родителя (подпроцессы проверки JPEG/transform) — тот же alias, файл не трогаем.
|
||||
INSTANCE_ID = os.environ["INSTANCE_ID"]
|
||||
else:
|
||||
INSTANCE_ID = "r-" + secrets.token_hex(5)
|
||||
os.environ["INSTANCE_ID"] = INSTANCE_ID
|
||||
try:
|
||||
with open(os.environ.get("INSTANCE_ID_FILE", "/tmp/instance-id"), "w") as _f:
|
||||
_f.write(INSTANCE_ID)
|
||||
except OSError:
|
||||
pass
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сверка PostgreSQL <-> S3 и очистка (compose-сервис `janitor`). Lab5.
|
||||
|
||||
Prefix-ы bucket:
|
||||
staging/<uuid> принятые оригиналы до публикации результата (attachments.staging_key);
|
||||
attachments/<id>/v<ver>/<name> конечные объекты: original и варианты;
|
||||
originals/<uuid> оригиналы lab4 (после миграции 004 — staging-объекты backfill-заданий);
|
||||
health/, bootstrap/ служебные, не трогаются.
|
||||
|
||||
За один проход (под pg_try_advisory_lock):
|
||||
1. abandoned: pending-строки старше grace (API упал до постановки в очередь, 202 не было)
|
||||
-> удалить staging-объект, затем строку;
|
||||
2. staging ready: у ready-вложения остался staging (worker не смог удалить после COMMIT)
|
||||
-> удалить объект, staging_key = NULL;
|
||||
3. staging failed: failed дольше STAGING_RETENTION_SECONDS -> удалить staging (replay после
|
||||
этого невозможен: ops replay ответит refused_staging_expired). Для 2 и 3: под блокировкой
|
||||
jobs+attachments условие проверяется заново, staging_key снимается и COMMIT, потом DELETE
|
||||
в S3 — гонка с replay исключена (аудит F01);
|
||||
4. orphan: объекты staging/, originals/, attachments/ старше grace, на которые не ссылается
|
||||
ни одна строка (staging_key, object_key ready-вложения, attachment_variants), и вложение
|
||||
не queued/processing -> удалить;
|
||||
5. missing: ready без объекта оригинала или варианта -> ТОЛЬКО отчёт.
|
||||
Текущую работу (queued/processing) janitor не удаляет никогда: её staging нужен worker.
|
||||
Grace (ATTACHMENT_GRACE_SECONDS, 3600 с) многократно больше UPLOAD_TIMEOUT_SECONDS и
|
||||
JOB_TIMEOUT_SECONDS, поэтому идущая загрузка/обработка не считается брошенной.
|
||||
|
||||
python src/janitor.py --once --dry-run | --once | --interval 300
|
||||
"""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
import jobs
|
||||
import telemetry
|
||||
from server import OBJ, STORE
|
||||
|
||||
log = logging.getLogger("messenger.janitor")
|
||||
JANITOR_LOCK_ID = 727002
|
||||
PREFIXES = ("staging/", "originals/", "attachments/")
|
||||
HEARTBEAT = "/tmp/janitor.heartbeat"
|
||||
STAGING_RETENTION = int(os.environ.get("STAGING_RETENTION_SECONDS", "86400"))
|
||||
# Только для теста гонки (student-tests/janitor_replay_race.py): пауза между выборкой
|
||||
# кандидатов и их захватом — воспроизводит чередование «выбрал -> replay -> удаляю». Обычно 0.
|
||||
PAUSE_AFTER_SELECT = float(os.environ.get("JANITOR_PAUSE_AFTER_SELECT_SECONDS", "0"))
|
||||
_FINAL_RE = re.compile(r"^attachments/([0-9a-f-]{36})/")
|
||||
|
||||
|
||||
def heartbeat():
|
||||
with open(HEARTBEAT, "w") as f:
|
||||
f.write(str(time.time()))
|
||||
|
||||
|
||||
def _delete(report, key, dry_run):
|
||||
if dry_run:
|
||||
return True
|
||||
try:
|
||||
OBJ.delete(key)
|
||||
report["deleted_objects"] += 1
|
||||
return True
|
||||
except Exception as exc:
|
||||
report["errors"] += 1
|
||||
log.warning("object not deleted (%s)", type(exc).__name__)
|
||||
return False
|
||||
|
||||
|
||||
def run_once(grace_seconds, dry_run, staging_retention=STAGING_RETENTION):
|
||||
started = time.monotonic()
|
||||
report = {"dry_run": dry_run, "grace_seconds": grace_seconds, "staging_retention_seconds": staging_retention,
|
||||
"abandoned_pending": 0, "staging_ready_cleaned": 0, "staging_failed_expired": 0,
|
||||
"staging_skipped_changed": 0,
|
||||
"orphan_objects": 0, "missing_objects": 0, "deleted_objects": 0, "deleted_rows": 0, "errors": 0}
|
||||
with STORE.pool.connection() as conn:
|
||||
conn.autocommit = True
|
||||
if not conn.execute("SELECT pg_try_advisory_lock(%s) AS ok", (JANITOR_LOCK_ID,)).fetchone()["ok"]:
|
||||
report["skipped"] = "another janitor is running"
|
||||
return report
|
||||
try:
|
||||
now_db = conn.execute("SELECT now() AS t").fetchone()["t"]
|
||||
cutoff = now_db - dt.timedelta(seconds=grace_seconds)
|
||||
report["rows_by_status"] = {r["status"]: r["n"] for r in conn.execute(
|
||||
"SELECT status, count(*) AS n FROM attachments GROUP BY status")}
|
||||
report["jobs_by_status"] = {r["status"]: r["n"] for r in conn.execute(
|
||||
"SELECT status, count(*) AS n FROM jobs GROUP BY status")}
|
||||
report["outbox_unpublished"] = conn.execute(
|
||||
"SELECT count(*) AS n FROM outbox WHERE published_at IS NULL").fetchone()["n"]
|
||||
|
||||
# 1. брошенные pending
|
||||
abandoned = conn.execute(
|
||||
"""SELECT id, staging_key FROM attachments
|
||||
WHERE status = 'pending' AND created_at < %s ORDER BY created_at""", (cutoff,)).fetchall()
|
||||
report["abandoned_pending"] = len(abandoned)
|
||||
report["abandoned_ids"] = [str(r["id"]) for r in abandoned[:20]]
|
||||
for row in abandoned:
|
||||
if dry_run:
|
||||
continue
|
||||
if row["staging_key"] and not _delete(report, row["staging_key"], dry_run):
|
||||
continue
|
||||
report["deleted_rows"] += conn.execute(
|
||||
"DELETE FROM attachments WHERE id = %s AND status = 'pending'", (row["id"],)).rowcount
|
||||
|
||||
# 2/3. staging, который больше не нужен
|
||||
stale = conn.execute(
|
||||
"""SELECT a.id, a.staging_key, a.status, j.id AS job_id FROM attachments a
|
||||
LEFT JOIN jobs j ON j.attachment_id = a.id AND j.pipeline_version = a.pipeline_version
|
||||
WHERE a.staging_key IS NOT NULL AND (a.status = 'ready'
|
||||
OR (a.status = 'failed' AND a.updated_at < now() - make_interval(secs => %s)))""",
|
||||
(staging_retention,)).fetchall()
|
||||
report["staging_candidates"] = [str(r["id"]) for r in stale][:20]
|
||||
if stale and PAUSE_AFTER_SELECT > 0:
|
||||
time.sleep(PAUSE_AFTER_SELECT)
|
||||
for row in stale:
|
||||
if dry_run:
|
||||
report["staging_ready_cleaned" if row["status"] == "ready" else "staging_failed_expired"] += 1
|
||||
continue
|
||||
# Аудит F01: выборка выше — без блокировок; между ней и удалением оператор мог
|
||||
# выполнить replay (failed -> queued), и удаление уничтожило бы исходник принятой
|
||||
# работы. Поэтому под блокировкой строк (порядок как у replay и worker:
|
||||
# сначала jobs, потом attachments) условие проверяется ЗАНОВО, ссылка
|
||||
# staging_key снимается и фиксируется, и только ПОСЛЕ COMMIT удаляется объект.
|
||||
# Replay после этого увидит staging_key IS NULL и откажет (refused_staging_expired);
|
||||
# replay, успевший раньше, оставит queued — и janitor пропустит строку.
|
||||
with conn.transaction():
|
||||
conn.execute("SELECT 1 FROM jobs WHERE attachment_id = %s FOR UPDATE", (row["id"],))
|
||||
claimed = conn.execute(
|
||||
"""UPDATE attachments SET staging_key = NULL
|
||||
WHERE id = %s AND staging_key = %s AND (status = 'ready'
|
||||
OR (status = 'failed' AND updated_at < now() - make_interval(secs => %s)))
|
||||
RETURNING status""",
|
||||
(row["id"], row["staging_key"], staging_retention)).fetchone()
|
||||
if claimed is None:
|
||||
report["staging_skipped_changed"] += 1 # состояние изменилось (replay и т. п.)
|
||||
continue
|
||||
if row["job_id"]:
|
||||
jobs.add_event(conn, row["job_id"], "staging_released", None, "janitor",
|
||||
{"status": claimed["status"]})
|
||||
report["staging_ready_cleaned" if claimed["status"] == "ready" else "staging_failed_expired"] += 1
|
||||
# Ссылки уже нет: если удаление не удастся, объект станет сиротой и будет удалён
|
||||
# обходом bucket после grace — исходник «живой» работы так не потеряется.
|
||||
_delete(report, row["staging_key"], dry_run)
|
||||
|
||||
# 4/5. обход bucket. Момент начала — по часам БД: ready раньше этого момента обязан
|
||||
# иметь все объекты в листинге (объекты пишутся ДО COMMIT ready).
|
||||
list_started = conn.execute("SELECT now() AS t").fetchone()["t"]
|
||||
listed = {}
|
||||
for prefix in PREFIXES:
|
||||
for obj in OBJ.client.list_objects(OBJ.bucket, prefix=prefix, recursive=True):
|
||||
listed[obj.object_name] = obj.last_modified
|
||||
report["objects_total"] = len(listed)
|
||||
report["objects_by_prefix"] = {p: sum(1 for k in listed if k.startswith(p)) for p in PREFIXES}
|
||||
known = set()
|
||||
busy = set() # вложения с текущей работой: их объекты не трогаем
|
||||
keys = list(listed)
|
||||
for i in range(0, len(keys), 1000):
|
||||
batch = keys[i:i + 1000]
|
||||
for r in conn.execute(
|
||||
"""SELECT staging_key AS k FROM attachments WHERE staging_key = ANY(%(b)s)
|
||||
UNION SELECT object_key FROM attachments WHERE status = 'ready' AND object_key = ANY(%(b)s)
|
||||
UNION SELECT object_key FROM attachment_variants WHERE object_key = ANY(%(b)s)""",
|
||||
{"b": batch}):
|
||||
known.add(r["k"])
|
||||
ids = {m.group(1) for k in keys for m in [_FINAL_RE.match(k)] if m}
|
||||
if ids:
|
||||
for r in conn.execute(
|
||||
"SELECT id FROM attachments WHERE id = ANY(%s::uuid[]) AND status IN ('pending','queued','processing')",
|
||||
(list(ids),)):
|
||||
busy.add(str(r["id"]))
|
||||
orphans = []
|
||||
for k, mtime in listed.items():
|
||||
if k in known or mtime is None or mtime >= cutoff:
|
||||
continue
|
||||
m = _FINAL_RE.match(k)
|
||||
if m and m.group(1) in busy:
|
||||
continue
|
||||
orphans.append(k)
|
||||
report["orphan_objects"] = len(orphans)
|
||||
report["orphan_keys_sample"] = sorted(orphans)[:5]
|
||||
for key in orphans:
|
||||
_delete(report, key, dry_run)
|
||||
|
||||
missing = []
|
||||
for r in conn.execute(
|
||||
"""SELECT a.id, a.object_key AS k FROM attachments a WHERE a.status = 'ready' AND a.updated_at < %s
|
||||
UNION ALL
|
||||
SELECT v.attachment_id, v.object_key FROM attachment_variants v
|
||||
JOIN attachments a ON a.id = v.attachment_id
|
||||
WHERE a.status = 'ready' AND a.updated_at < %s""", (list_started, list_started)):
|
||||
if r["k"] not in listed:
|
||||
missing.append(str(r["id"]))
|
||||
report["missing_objects"] = len(missing)
|
||||
report["missing_ids_sample"] = sorted(set(missing))[:5]
|
||||
if missing:
|
||||
log.error("ready attachments without object: %d (manual investigation needed)", len(missing))
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (JANITOR_LOCK_ID,))
|
||||
report["duration_ms"] = round((time.monotonic() - started) * 1000, 1)
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--once", action="store_true")
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
parser.add_argument("--grace-seconds", type=int,
|
||||
default=int(os.environ.get("ATTACHMENT_GRACE_SECONDS", "3600")))
|
||||
parser.add_argument("--staging-retention-seconds", type=int, default=STAGING_RETENTION)
|
||||
parser.add_argument("--interval", type=int, default=int(os.environ.get("JANITOR_INTERVAL_SECONDS", "300")))
|
||||
args = parser.parse_args()
|
||||
if args.grace_seconds < 1:
|
||||
parser.error("grace period must be positive")
|
||||
if args.once:
|
||||
telemetry.configure_logging(stream=sys.stderr) # stdout — JSON-отчёт для оператора
|
||||
else:
|
||||
telemetry.setup("messenger-janitor")
|
||||
telemetry.observe_pool(STORE.pool, "janitor")
|
||||
STORE.open()
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
print(json.dumps(run_once(args.grace_seconds, args.dry_run, args.staging_retention_seconds),
|
||||
ensure_ascii=False), flush=True)
|
||||
except Exception as exc:
|
||||
log.warning("janitor pass failed (%s)", type(exc).__name__,
|
||||
extra={"event": "janitor.failed", "error.type": type(exc).__name__})
|
||||
if args.once:
|
||||
return 1
|
||||
if args.once:
|
||||
return 0
|
||||
wake = time.monotonic() + args.interval
|
||||
while time.monotonic() < wake:
|
||||
heartbeat()
|
||||
time.sleep(min(30, max(0.1, wake - time.monotonic())))
|
||||
finally:
|
||||
STORE.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+451
@@ -0,0 +1,451 @@
|
||||
"""Задания обработки вложений: схема сообщения, переходы состояний, retry, lease, replay.
|
||||
|
||||
Используется API (постановка в очередь), worker, relay (reaper) и ops-CLI. Все переходы —
|
||||
SQL-транзакции над строкой jobs под FOR UPDATE, поэтому решение «что делать с сообщением»
|
||||
принимается по устойчивому состоянию в PostgreSQL, а не по факту доставки.
|
||||
|
||||
Сообщение брокера (contracts/jobs.schema.json) — только ссылка: job_id, attachment_id,
|
||||
pipeline_version, attempt. Bytes, credentials, URL и ключи S3 в сообщение не попадают:
|
||||
worker берёт доверенные storage metadata из БД.
|
||||
|
||||
Переходы (contracts/attachment-states.md):
|
||||
enqueue нет -> queued API, одна транзакция с outbox
|
||||
claim queued -> processing worker: attempt+1, lease_owner/token/until
|
||||
heartbeat processing (продление) worker, только со своим lease_token
|
||||
complete processing -> ready worker, только со своим lease_token (fencing)
|
||||
retry processing -> queued временная ошибка, backoff + jitter, outbox с available_at
|
||||
fail processing -> failed постоянная ошибка или исчерпаны попытки
|
||||
lease expired processing -> queued reaper (relay), если аренду никто не продлил
|
||||
replay failed -> queued оператор (ops.py), audit, ready не трогается
|
||||
|
||||
Lab6 (W3C Trace Context через очередь): add_outbox внутри активной трассы создаёт PRODUCER span
|
||||
«attachment.process.v1 create» и пишет его traceparent/tracestate в payload outbox (поля
|
||||
разрешены contracts/jobs.schema.json). Relay публикует сообщение в span-е «send» (child), worker
|
||||
обрабатывает в CONSUMER span-е «process» (child от send). Retry из worker пишет новый outbox в
|
||||
контексте текущей попытки -> следующая попытка в той же трассе. Фоновые переходы без трассы
|
||||
(reaper, redrive, replay оператора) берут traceparent последнего outbox этого job — цепочка
|
||||
upload -> все попытки остаётся одной трассой.
|
||||
"""
|
||||
import datetime as dt
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import uuid
|
||||
|
||||
import telemetry
|
||||
from telemetry import SpanKind, db_operation
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
# Аудит F11: публикация результата и выборка вариантов согласованы только для v1.
|
||||
SUPPORTED_PIPELINE_VERSIONS = (1,)
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
|
||||
# Постоянные ошибки: повтор не поможет (тот же вход даст тот же результат).
|
||||
PERMANENT_ERRORS = {"invalid_image", "image_too_large", "staging_corrupted", "staging_missing",
|
||||
"resource_limit"}
|
||||
_UUID_FIELDS = ("job_id", "attachment_id")
|
||||
_ALLOWED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt",
|
||||
"created_at", "traceparent", "tracestate"}
|
||||
|
||||
|
||||
class InvalidMessage(Exception):
|
||||
"""Сообщение не соответствует jobs.schema.json -> reject в DLQ."""
|
||||
|
||||
|
||||
def utc_now_text():
|
||||
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def make_payload(job_id, attachment_id, pipeline_version, attempt, created_at=None, trace_fields=None):
|
||||
payload = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"job_id": str(job_id),
|
||||
"type": JOB_TYPE,
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": int(pipeline_version),
|
||||
"attempt": int(attempt),
|
||||
"created_at": created_at or utc_now_text(),
|
||||
}
|
||||
for key in ("traceparent", "tracestate"):
|
||||
value = (trace_fields or {}).get(key)
|
||||
if key == "traceparent" and value and _TRACEPARENT_RE.match(value):
|
||||
payload[key] = value
|
||||
elif key == "tracestate" and value and len(value) <= 512:
|
||||
payload[key] = value
|
||||
return payload
|
||||
|
||||
|
||||
_UUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
||||
# RFC 3339 date-time: обязательно время и зона (Z или ±hh:mm).
|
||||
_DATETIME_RE = re.compile(r"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$")
|
||||
_TRACEPARENT_RE = re.compile(r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$")
|
||||
|
||||
|
||||
def _strict_int(v):
|
||||
# В Python True == 1 и isinstance(True, int): bool исключается явно (аудит F12).
|
||||
# По JSON Schema 2020-12 integer — число с нулевой дробной частью: 1.0 тоже допустимо.
|
||||
return type(v) is int or (type(v) is float and v.is_integer())
|
||||
|
||||
|
||||
def parse_message(body):
|
||||
"""bytes -> dict строго по jobs.schema.json (без внешних библиотек). Иначе InvalidMessage.
|
||||
Аудит F12: раньше проходили schema_version=true, created_at без времени, traceparent-число
|
||||
и tracestate длиннее 512. Соответствие сверяется с jsonschema тестом job_schema_check.py."""
|
||||
try:
|
||||
msg = json.loads(body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise InvalidMessage("not json")
|
||||
if not isinstance(msg, dict):
|
||||
raise InvalidMessage("not object")
|
||||
if set(msg) - _ALLOWED:
|
||||
raise InvalidMessage("extra fields")
|
||||
for field in ("schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"):
|
||||
if field not in msg:
|
||||
raise InvalidMessage("missing " + field)
|
||||
if not _strict_int(msg["schema_version"]) or msg["schema_version"] != SCHEMA_VERSION:
|
||||
raise InvalidMessage("unsupported schema_version")
|
||||
if msg["type"] != JOB_TYPE:
|
||||
raise InvalidMessage("unsupported type")
|
||||
for field in _UUID_FIELDS:
|
||||
if not isinstance(msg[field], str) or not _UUID_RE.match(msg[field]):
|
||||
raise InvalidMessage("bad " + field)
|
||||
for field in ("pipeline_version", "attempt"):
|
||||
if not _strict_int(msg[field]) or msg[field] < 1:
|
||||
raise InvalidMessage("bad " + field)
|
||||
created = msg["created_at"]
|
||||
if not isinstance(created, str) or not _DATETIME_RE.match(created):
|
||||
raise InvalidMessage("bad created_at")
|
||||
try:
|
||||
dt.datetime.fromisoformat(created.upper().replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
raise InvalidMessage("bad created_at")
|
||||
if "traceparent" in msg and (not isinstance(msg["traceparent"], str) or not _TRACEPARENT_RE.match(msg["traceparent"])):
|
||||
raise InvalidMessage("bad traceparent")
|
||||
if "tracestate" in msg and (not isinstance(msg["tracestate"], str) or len(msg["tracestate"]) > 512):
|
||||
raise InvalidMessage("bad tracestate")
|
||||
for field in ("schema_version", "pipeline_version", "attempt"):
|
||||
msg[field] = int(msg[field]) # 1.0 -> 1
|
||||
return msg
|
||||
|
||||
|
||||
def backoff_seconds(attempt, base, cap, rng=random):
|
||||
"""Экспоненциальный backoff с «equal jitter»: d = min(cap, base*2^(attempt-1)),
|
||||
задержка равномерно в [d/2, d]. Половина гарантирует паузу (не долбим упавший S3),
|
||||
случайная половина разносит повторы многих заданий во времени (нет «стада»)."""
|
||||
d = min(float(cap), float(base) * (2 ** max(0, attempt - 1)))
|
||||
return d / 2 + rng.uniform(0, d / 2)
|
||||
|
||||
|
||||
def add_event(conn, job_id, event, attempt=None, actor=None, detail=None):
|
||||
conn.execute(
|
||||
"INSERT INTO job_events (job_id, event, attempt, actor, detail) VALUES (%s, %s, %s, %s, %s)",
|
||||
(job_id, event, attempt, actor, json.dumps(detail, ensure_ascii=False) if detail is not None else None))
|
||||
|
||||
|
||||
def _previous_trace(conn, job_id):
|
||||
row = conn.execute(
|
||||
"""SELECT payload->>'traceparent' AS traceparent, payload->>'tracestate' AS tracestate FROM outbox
|
||||
WHERE job_id = %s AND payload ? 'traceparent' ORDER BY id DESC LIMIT 1""", (job_id,)).fetchone()
|
||||
if row is None:
|
||||
return {}
|
||||
row = row if isinstance(row, dict) else {"traceparent": row[0], "tracestate": row[1]}
|
||||
return {k: v for k, v in row.items() if v}
|
||||
|
||||
|
||||
def add_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds=0.0):
|
||||
if telemetry.has_active_span():
|
||||
attrs = {"messaging.system": "rabbitmq", "messaging.operation.type": "create",
|
||||
"messaging.operation.name": "create", "messaging.destination.name": "attachments",
|
||||
"messenger.job.id": str(job_id), "messenger.attachment.id": str(attachment_id),
|
||||
"messenger.job.attempt": int(attempt), "messenger.outbox.delay_s": round(float(delay_seconds), 3)}
|
||||
with telemetry.child_span(JOB_TYPE + " create", SpanKind.PRODUCER, attrs):
|
||||
return _insert_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds,
|
||||
telemetry.inject_dict())
|
||||
return _insert_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds,
|
||||
_previous_trace(conn, job_id))
|
||||
|
||||
|
||||
def _insert_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds, trace_fields):
|
||||
payload = make_payload(job_id, attachment_id, pipeline_version, attempt, trace_fields=trace_fields)
|
||||
conn.execute(
|
||||
"""INSERT INTO outbox (job_id, payload, available_at)
|
||||
VALUES (%s, %s, now() + make_interval(secs => %s))""",
|
||||
(job_id, json.dumps(payload), delay_seconds))
|
||||
return payload
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# API: постановка в очередь
|
||||
# ---------------------------------------------------------------------------
|
||||
@db_operation("jobs.enqueue")
|
||||
def enqueue(conn, attachment_id, pipeline_version, max_attempts):
|
||||
"""В ТЕКУЩЕЙ транзакции: pending -> queued, jobs, outbox, событие. job_id или None."""
|
||||
row = conn.execute(
|
||||
"""UPDATE attachments SET status = 'queued', updated_at = now()
|
||||
WHERE id = %s AND status = 'pending' RETURNING id""", (attachment_id,)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
job_id = uuid.uuid4()
|
||||
conn.execute(
|
||||
"""INSERT INTO jobs (id, attachment_id, pipeline_version, status, attempt, max_attempts,
|
||||
next_attempt_at, created_at, updated_at)
|
||||
VALUES (%s, %s, %s, 'queued', 0, %s, now(), now(), now())""",
|
||||
(job_id, attachment_id, pipeline_version, max_attempts))
|
||||
add_event(conn, job_id, "enqueued", 1, "api")
|
||||
add_outbox(conn, job_id, attachment_id, pipeline_version, 1)
|
||||
return job_id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Worker
|
||||
# ---------------------------------------------------------------------------
|
||||
JOB_COLUMNS = """j.id AS job_id, j.attachment_id, j.pipeline_version, j.status AS job_status, j.attempt,
|
||||
j.max_attempts, j.next_attempt_at, j.error_code, j.lease_owner, j.lease_token, j.lease_until, j.replay_count,
|
||||
j.lease_until > now() AS lease_alive, j.next_attempt_at > now() + interval '1 second' AS too_early,
|
||||
GREATEST(0, EXTRACT(EPOCH FROM now() - j.next_attempt_at))::float8 AS eligible_wait_s,
|
||||
EXTRACT(EPOCH FROM now() - j.created_at)::float8 AS job_age_s,
|
||||
a.status AS attachment_status, a.content_type, a.size_bytes, a.sha256, a.width, a.height,
|
||||
a.object_key, a.staging_key, a.filename, a.pipeline_version AS current_pipeline_version"""
|
||||
|
||||
|
||||
def load_job(conn, job_id, lock=False):
|
||||
return conn.execute(
|
||||
"SELECT " + JOB_COLUMNS + " FROM jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.id = %s"
|
||||
+ (" FOR UPDATE OF j" if lock else ""), (job_id,)).fetchone()
|
||||
|
||||
|
||||
def _owner_host(owner):
|
||||
return (owner or "").split(":", 1)[0]
|
||||
|
||||
|
||||
@db_operation("jobs.claim")
|
||||
def claim(conn, msg, owner, lease_seconds):
|
||||
"""Решение по сообщению. Возвращает (action, job):
|
||||
'process' — аренда взята (job со свежим lease_token), можно работать;
|
||||
'ack' — ничего делать не нужно (уже ready/failed, занято живой арендой, ранний дубль);
|
||||
'reject' — сообщение не соответствует заданию (в DLQ, разбирает оператор).
|
||||
Вызывается в транзакции; при 'process' коммит фиксирует processing ДО начала работы."""
|
||||
job = load_job(conn, msg["job_id"], lock=True)
|
||||
if job is None:
|
||||
return "reject", "unknown_job"
|
||||
if str(job["attachment_id"]) != msg["attachment_id"] or job["pipeline_version"] != msg["pipeline_version"]:
|
||||
return "reject", "job_mismatch"
|
||||
status = job["job_status"]
|
||||
if status == "ready":
|
||||
add_event(conn, job["job_id"], "duplicate_ignored", msg["attempt"], owner, {"status": "ready"})
|
||||
return "ack", job
|
||||
if status == "failed":
|
||||
add_event(conn, job["job_id"], "duplicate_ignored", msg["attempt"], owner, {"status": "failed"})
|
||||
return "ack", job
|
||||
if job["current_pipeline_version"] > job["pipeline_version"]:
|
||||
# Устаревшая job после новой версии pipeline: результат не публикуем.
|
||||
conn.execute("""UPDATE jobs SET status = 'failed', error_code = 'superseded', lease_owner = NULL,
|
||||
lease_token = NULL, lease_until = NULL, updated_at = now(), finished_at = now()
|
||||
WHERE id = %s""", (job["job_id"],))
|
||||
add_event(conn, job["job_id"], "superseded", msg["attempt"], owner)
|
||||
return "ack", job
|
||||
if status == "processing" and job["lease_alive"]:
|
||||
prev = job["lease_owner"] or ""
|
||||
# Тот же контейнер (hostname), но другой процесс (boot id): прежняя инкарнация этого
|
||||
# worker умерла (crash/restart) — два процесса одного контейнера одновременно не живут.
|
||||
if not (_owner_host(prev) == _owner_host(owner) and prev != owner):
|
||||
add_event(conn, job["job_id"], "busy_ignored", msg["attempt"], owner, {"lease_owner": prev})
|
||||
return "ack", job
|
||||
add_event(conn, job["job_id"], "lease_taken_over", job["attempt"], owner,
|
||||
{"previous_owner": prev, "reason": "previous process of this container died"})
|
||||
elif status == "processing":
|
||||
add_event(conn, job["job_id"], "lease_taken_over", job["attempt"], owner,
|
||||
{"previous_owner": job["lease_owner"], "reason": "lease expired"})
|
||||
elif job["too_early"]:
|
||||
# queued, но время следующей попытки ещё не пришло: это старый дубль, а запланированное
|
||||
# сообщение relay опубликует само (outbox.available_at).
|
||||
add_event(conn, job["job_id"], "early_duplicate_ignored", msg["attempt"], owner)
|
||||
return "ack", job
|
||||
if job["attempt"] >= job["max_attempts"]:
|
||||
_finish_failed(conn, job, "retry_exhausted", owner, "attempts exhausted before claim")
|
||||
return "ack", job
|
||||
token = uuid.uuid4()
|
||||
conn.execute(
|
||||
"""UPDATE jobs SET status = 'processing', attempt = attempt + 1, lease_owner = %s, lease_token = %s,
|
||||
lease_until = now() + make_interval(secs => %s), updated_at = now()
|
||||
WHERE id = %s""", (owner, token, lease_seconds, job["job_id"]))
|
||||
conn.execute("UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = %s",
|
||||
(job["attachment_id"],))
|
||||
job = dict(job, attempt=job["attempt"] + 1, lease_token=token, job_status="processing")
|
||||
add_event(conn, job["job_id"], "claimed", job["attempt"], owner,
|
||||
{"redelivered_message_attempt": msg["attempt"]})
|
||||
return "process", job
|
||||
|
||||
|
||||
@db_operation("jobs.heartbeat")
|
||||
def heartbeat(conn, job_id, token, lease_seconds):
|
||||
"""Продлить аренду. False — аренда потеряна (reaper/другой worker), работу надо бросить."""
|
||||
cur = conn.execute(
|
||||
"""UPDATE jobs SET lease_until = now() + make_interval(secs => %s)
|
||||
WHERE id = %s AND lease_token = %s AND status = 'processing'""", (lease_seconds, job_id, token))
|
||||
return cur.rowcount == 1
|
||||
|
||||
|
||||
@db_operation("jobs.complete")
|
||||
def complete(conn, job, variants, owner):
|
||||
"""processing -> ready атомарно с метаданными вариантов. Только владелец аренды (fencing по
|
||||
lease_token): опоздавший процесс, у которого аренду забрали, ничего не перезапишет.
|
||||
Возвращает 'ready' | 'already_ready' | 'lease_lost'."""
|
||||
cur = conn.execute(
|
||||
"""UPDATE jobs SET status = 'ready', lease_owner = NULL, lease_token = NULL, lease_until = NULL,
|
||||
error_code = NULL, last_error = NULL, updated_at = now(), finished_at = now()
|
||||
WHERE id = %s AND status = 'processing' AND lease_token = %s
|
||||
RETURNING EXTRACT(EPOCH FROM clock_timestamp() - created_at)::float8 AS time_to_ready_s""",
|
||||
(job["job_id"], job["lease_token"]))
|
||||
row = cur.fetchone() if cur.rowcount == 1 else None
|
||||
if row is not None:
|
||||
# От durable acceptance (COMMIT enqueue в API = jobs.created_at) до публикации ready.
|
||||
job["time_to_ready_s"] = row["time_to_ready_s"] if isinstance(row, dict) else row[0]
|
||||
if cur.rowcount != 1:
|
||||
now = load_job(conn, job["job_id"])
|
||||
add_event(conn, job["job_id"], "commit_rejected_lease_lost", job["attempt"], owner,
|
||||
{"current_status": now["job_status"]})
|
||||
return "already_ready" if now["job_status"] == "ready" else "lease_lost"
|
||||
with conn.cursor() as cur:
|
||||
# Ключ эффекта — PK (attachment_id, pipeline_version, name): второго набора не будет.
|
||||
cur.executemany(
|
||||
"""INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type,
|
||||
size_bytes, width, height, sha256, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, now())
|
||||
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET
|
||||
object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type,
|
||||
size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height,
|
||||
sha256 = EXCLUDED.sha256""",
|
||||
[(job["attachment_id"], job["pipeline_version"], v["name"], v["key"], v["content_type"],
|
||||
v["size_bytes"], v["width"], v["height"], v["sha256"]) for v in variants])
|
||||
# Не откатываем более новую версию pipeline (на случай нескольких версий, трек 5).
|
||||
conn.execute(
|
||||
"""UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = now()
|
||||
WHERE id = %s AND pipeline_version <= %s""", (job["attachment_id"], job["pipeline_version"]))
|
||||
add_event(conn, job["job_id"], "ready", job["attempt"], owner,
|
||||
{"variants": {v["name"]: [v["width"], v["height"]] for v in variants}})
|
||||
return "ready"
|
||||
|
||||
|
||||
def _finish_failed(conn, job, code, actor, detail):
|
||||
row = conn.execute(
|
||||
"""UPDATE jobs SET status = 'failed', error_code = %s, last_error = %s, lease_owner = NULL,
|
||||
lease_token = NULL, lease_until = NULL, updated_at = now(), finished_at = now()
|
||||
WHERE id = %s RETURNING EXTRACT(EPOCH FROM clock_timestamp() - created_at)::float8 AS t""",
|
||||
(code, (detail or "")[:500], job["job_id"])).fetchone()
|
||||
if row is not None and isinstance(job, dict):
|
||||
job["time_to_terminal_s"] = row["t"] if isinstance(row, dict) else row[0]
|
||||
conn.execute("UPDATE attachments SET status = 'failed', error_code = %s, updated_at = now() WHERE id = %s",
|
||||
(code, job["attachment_id"]))
|
||||
add_event(conn, job["job_id"], "failed", job["attempt"], actor, {"error_code": code, "detail": detail})
|
||||
|
||||
|
||||
@db_operation("jobs.fail_or_retry")
|
||||
def fail_or_retry(conn, job, code, detail, owner, base, cap, rng=random):
|
||||
"""Ошибка попытки. Постоянная -> failed(code); временная -> queued с backoff, пока есть
|
||||
попытки, иначе failed(retry_exhausted). Только владелец аренды.
|
||||
Возвращает 'failed' | 'retry' | 'lease_lost' и задержку."""
|
||||
cur = load_job(conn, job["job_id"], lock=True)
|
||||
if cur["job_status"] != "processing" or cur["lease_token"] != job["lease_token"]:
|
||||
add_event(conn, job["job_id"], "error_ignored_lease_lost", job["attempt"], owner, {"error_code": code})
|
||||
return "lease_lost", None
|
||||
if code in PERMANENT_ERRORS:
|
||||
_finish_failed(conn, job, code, owner, detail)
|
||||
return "failed", None
|
||||
if cur["attempt"] >= cur["max_attempts"]:
|
||||
_finish_failed(conn, job, "retry_exhausted", owner, "last error: %s %s" % (code, detail or ""))
|
||||
return "failed", None
|
||||
delay = backoff_seconds(cur["attempt"], base, cap, rng)
|
||||
_schedule_retry(conn, cur, delay, code, detail, owner, "retry_scheduled")
|
||||
return "retry", delay
|
||||
|
||||
|
||||
def _schedule_retry(conn, job, delay, code, detail, actor, event):
|
||||
conn.execute(
|
||||
"""UPDATE jobs SET status = 'queued', lease_owner = NULL, lease_token = NULL, lease_until = NULL,
|
||||
error_code = NULL, last_error = %s, next_attempt_at = now() + make_interval(secs => %s),
|
||||
updated_at = now()
|
||||
WHERE id = %s""", (("%s: %s" % (code, detail or ""))[:500], delay, job["job_id"]))
|
||||
conn.execute("UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = %s",
|
||||
(job["attachment_id"],))
|
||||
add_outbox(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1, delay)
|
||||
add_event(conn, job["job_id"], event, job["attempt"], actor,
|
||||
{"error_code": code, "delay_seconds": round(delay, 3), "next_attempt": job["attempt"] + 1})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reaper (в relay): зависшие processing и потерянные сообщения
|
||||
# ---------------------------------------------------------------------------
|
||||
@db_operation("jobs.reap_expired_leases")
|
||||
def reap_expired_leases(conn, base, cap, actor="reaper", limit=100):
|
||||
"""processing с истёкшей арендой (worker умер/завис и не продлевал lease) -> queued
|
||||
с backoff или failed(retry_exhausted). Возвращает число обработанных."""
|
||||
rows = conn.execute(
|
||||
"SELECT " + JOB_COLUMNS + """ FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.status = 'processing' AND j.lease_until < now()
|
||||
ORDER BY j.lease_until LIMIT %s FOR UPDATE OF j SKIP LOCKED""", (limit,)).fetchall()
|
||||
for job in rows:
|
||||
add_event(conn, job["job_id"], "lease_expired", job["attempt"], actor, {"lease_owner": job["lease_owner"]})
|
||||
if job["attempt"] >= job["max_attempts"]:
|
||||
_finish_failed(conn, job, "retry_exhausted", actor, "lease expired on last attempt")
|
||||
else:
|
||||
_schedule_retry(conn, job, backoff_seconds(job["attempt"], base, cap), "lease_expired",
|
||||
"worker did not renew lease", actor, "requeued_after_lease")
|
||||
return len(rows)
|
||||
|
||||
|
||||
@db_operation("jobs.redrive_stale_queued")
|
||||
def redrive_stale_queued(conn, after_seconds, actor="reaper", limit=100):
|
||||
"""queued-задание, по которому давно нет ни неопубликованного outbox, ни движения:
|
||||
сообщение могло потеряться в брокере (например, после потери его volume). Публикуем
|
||||
ещё раз — дубль безопасен, решение примет worker по строке jobs."""
|
||||
rows = conn.execute(
|
||||
"""SELECT j.id, j.attachment_id, j.pipeline_version, j.attempt FROM jobs j
|
||||
WHERE j.status = 'queued' AND j.updated_at < now() - make_interval(secs => %s)
|
||||
AND j.next_attempt_at < now() - make_interval(secs => %s)
|
||||
AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.id AND o.published_at IS NULL)
|
||||
ORDER BY j.updated_at LIMIT %s FOR UPDATE OF j SKIP LOCKED""",
|
||||
(after_seconds, after_seconds, limit)).fetchall()
|
||||
for r in rows:
|
||||
conn.execute("UPDATE jobs SET updated_at = now() WHERE id = %s", (r["id"],))
|
||||
add_outbox(conn, r["id"], r["attachment_id"], r["pipeline_version"], r["attempt"] + 1)
|
||||
add_event(conn, r["id"], "redriven", r["attempt"] + 1, actor, {"stale_after_seconds": after_seconds})
|
||||
return len(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Оператор: replay
|
||||
# ---------------------------------------------------------------------------
|
||||
@db_operation("jobs.replay")
|
||||
def replay(conn, attachment_id, actor, extra_attempts, reason, dry_run=False):
|
||||
"""failed -> queued. Новая попытка того же job_id (прежний ключ эффекта), max_attempts
|
||||
увеличивается на extra_attempts. ready/queued/processing НЕ трогаются: «повторить» не
|
||||
означает выполнить дубль успешной работы. Возвращает (result, job)."""
|
||||
job = conn.execute(
|
||||
"SELECT " + JOB_COLUMNS + """ FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.attachment_id = %s AND j.pipeline_version = a.pipeline_version FOR UPDATE OF j""",
|
||||
(attachment_id,)).fetchone()
|
||||
if job is None:
|
||||
return "not_found", None
|
||||
if job["job_status"] != "failed":
|
||||
return "refused_status_" + job["job_status"], job
|
||||
# Аудит F01: staging_key перечитывается ОТДЕЛЬНЫМ запросом под блокировкой строки вложения.
|
||||
# В READ COMMITTED «SELECT ... FOR UPDATE OF j» после ожидания блокировки перечитывает только
|
||||
# строку jobs, а колонки attachments из соединения могли остаться из старого снимка — и replay
|
||||
# принял бы работу, исходник которой janitor уже освободил.
|
||||
att = conn.execute("SELECT staging_key FROM attachments WHERE id = %s FOR UPDATE",
|
||||
(job["attachment_id"],)).fetchone()
|
||||
if att["staging_key"] is None:
|
||||
return "refused_staging_expired", job
|
||||
if dry_run:
|
||||
return "would_replay", job
|
||||
conn.execute(
|
||||
"""UPDATE jobs SET status = 'queued', max_attempts = attempt + %s, error_code = NULL,
|
||||
next_attempt_at = now(), replay_count = replay_count + 1, updated_at = now(), finished_at = NULL
|
||||
WHERE id = %s""", (extra_attempts, job["job_id"]))
|
||||
conn.execute("UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = %s",
|
||||
(job["attachment_id"],))
|
||||
add_outbox(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1)
|
||||
add_event(conn, job["job_id"], "replayed", job["attempt"] + 1, actor,
|
||||
{"reason": reason, "previous_error": job.get("error_code"), "replay_count": job["replay_count"] + 1})
|
||||
return "replayed", job
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Пробное декодирование JPEG в ОТДЕЛЬНОМ процессе с лимитами (аудит F02).
|
||||
|
||||
python jpeg_probe.py <max_pixels> <width> <height> < файл на stdin (обычный файл, seekable)
|
||||
|
||||
API раньше декодировал JPEG в своём процессе, рассчитывая, что draft(1/8) уменьшает
|
||||
память в ~64 раза. Для progressive JPEG это неверно: декодеру нужен буфер DCT-
|
||||
коэффициентов ВСЕГО кадра. Замер на Pillow 13, 6324x6324 (~40 Мпикс): baseline — 23 MiB,
|
||||
progressive 4:2:0 — 137 MiB, progressive 4:4:4 — 252 MiB на одно декодирование, а лимит
|
||||
реплики был 256 MiB. Поэтому проверка вынесена в подпроцесс:
|
||||
* RLIMIT_AS / RLIMIT_CPU ставятся ДО импорта Pillow;
|
||||
* oom_score_adj=1000: если памяти контейнера всё же не хватит, ядро убьёт пробу, а не API;
|
||||
* код выхода: 0 — корректный JPEG; 3 — повреждён/не тот формат; 5 — не хватило памяти/CPU.
|
||||
"""
|
||||
import os
|
||||
import resource
|
||||
import sys
|
||||
|
||||
EXIT_OK, EXIT_INVALID, EXIT_RESOURCE = 0, 3, 5
|
||||
|
||||
|
||||
def main():
|
||||
max_pixels, width, height = (int(x) for x in sys.argv[1:4])
|
||||
limit = int(os.environ.get("JPEG_PROBE_MEMORY_MB", "384")) * 1024 * 1024
|
||||
cpu = int(os.environ.get("JPEG_PROBE_CPU_SECONDS", "10"))
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu + 1))
|
||||
try:
|
||||
with open("/proc/self/oom_score_adj", "w") as f:
|
||||
f.write("1000")
|
||||
except OSError:
|
||||
pass
|
||||
import warnings
|
||||
from PIL import Image
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
src = os.fdopen(0, "rb", closefd=False)
|
||||
try:
|
||||
with Image.open(src, formats=("JPEG",)) as im:
|
||||
if im.size != (width, height):
|
||||
return EXIT_INVALID
|
||||
im.draft("RGB", (max(1, width // 8), max(1, height // 8)))
|
||||
im.load() # обрезанные/битые энтропийные данные -> исключение
|
||||
except MemoryError:
|
||||
return EXIT_RESOURCE
|
||||
except Exception:
|
||||
return EXIT_INVALID
|
||||
return EXIT_OK
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Однократное применение миграций и прав (compose-сервис `migrate`).
|
||||
|
||||
Запускается ОДИН раз до старта/замены API-реплик, а не каждой репликой. Миграции — под
|
||||
pg_advisory_lock: параллельный повторный запуск не устроит гонку; каждый файл в своей транзакции.
|
||||
|
||||
Lab7:
|
||||
* job подключается как суперпользователь postgres по TLS verify-full; пароль — из OpenBao
|
||||
(kv/messenger/migrate, cert auth identity `migrate`), не из файла;
|
||||
* создаёт/обновляет сервисные роли api_svc, worker_svc, relay_svc, janitor_svc, ops_svc
|
||||
(LOGIN, пароль из того же KV; NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT,
|
||||
ограничение числа соединений) — повторный запуск синхронизирует пароль (ротация);
|
||||
* применяет migrations/security/grants.sql (REVOKE ALL -> точные GRANT).
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from psycopg import sql
|
||||
|
||||
import telemetry
|
||||
import vault
|
||||
from server import MIGRATIONS_DIR, STORE
|
||||
|
||||
log = logging.getLogger("messenger.migrate")
|
||||
|
||||
ROLES = { # роль -> (поле KV с паролем, CONNECTION LIMIT)
|
||||
"api_svc": ("DB_API_PASSWORD", 40),
|
||||
"worker_svc": ("DB_WORKER_PASSWORD", 30),
|
||||
"relay_svc": ("DB_RELAY_PASSWORD", 10),
|
||||
"janitor_svc": ("DB_JANITOR_PASSWORD", 5),
|
||||
"ops_svc": ("DB_OPS_PASSWORD", 3),
|
||||
}
|
||||
|
||||
|
||||
def ensure_roles(conn):
|
||||
for role, (field, limit) in ROLES.items():
|
||||
password = vault.secret(field)
|
||||
exists = conn.execute("SELECT 1 FROM pg_roles WHERE rolname = %s", (role,)).fetchone()
|
||||
verb = "ALTER" if exists else "CREATE"
|
||||
conn.execute(sql.SQL("{} ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION "
|
||||
"NOBYPASSRLS CONNECTION LIMIT {} PASSWORD {}").format(
|
||||
sql.SQL(verb), sql.Identifier(role), sql.Literal(limit), sql.Literal(password)))
|
||||
# Без лишних параметров сессии, которые могла бы выставить роль сама.
|
||||
conn.execute(sql.SQL("ALTER ROLE {} SET statement_timeout = '5s'").format(sql.Identifier(role)))
|
||||
log.info("db role %s %s", role, "updated" if exists else "created", extra={"event": "db.role"})
|
||||
|
||||
|
||||
def main():
|
||||
telemetry.configure_logging() # короткоживущий job: только JSON-лог в stdout, без экспорта
|
||||
STORE.open()
|
||||
try:
|
||||
before = STORE.pending_migrations(MIGRATIONS_DIR)
|
||||
STORE.migrate(MIGRATIONS_DIR)
|
||||
grants = (Path(MIGRATIONS_DIR) / "security" / "grants.sql").read_text(encoding="utf-8")
|
||||
with STORE.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
ensure_roles(conn)
|
||||
conn.execute(grants)
|
||||
log.info("migrations done; applied now: %s; roles and grants synced", ", ".join(before) or "nothing")
|
||||
finally:
|
||||
STORE.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
"""Доступ к S3-совместимому хранилищу (SeaweedFS) через клиент minio-py.
|
||||
|
||||
API работает с bucket под ОТДЕЛЬНЫМИ credentials с правами только Read+Write на этот
|
||||
bucket (без List, без создания/удаления bucket, без политик и IAM) — см.
|
||||
scripts/init-secrets.sh и REPORT.md. Публичных URL/redirect нет: байты всегда идут
|
||||
через авторизованный API.
|
||||
|
||||
Lab6: каждый запрос к S3 — CLIENT span «s3 <Операция>» (внутри запроса/задания) и гистограмма
|
||||
messenger.s3.operation.duration{messenger.s3.operation, outcome}. В span — bucket и ключ объекта
|
||||
(ключи назначает сервер: staging/<uuid>, attachments/<id>/v1/<variant>; filename в ключ не входит),
|
||||
без credentials и подписанных URL.
|
||||
"""
|
||||
import contextlib
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import urllib3
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
|
||||
import telemetry
|
||||
import tlsutil
|
||||
import vault
|
||||
from telemetry import SpanKind
|
||||
|
||||
log = logging.getLogger("messenger.s3")
|
||||
|
||||
# minio-py для объектов больше part_size делает multipart и держит в памяти
|
||||
# один part. 5 MiB — минимум S3: файл 10 MiB -> 2 части по 5 MiB.
|
||||
PART_SIZE = 5 * 1024 * 1024
|
||||
STREAM_CHUNK = 64 * 1024
|
||||
# Служебные объекты S3Health: health/<реплика> (вне prefix originals/, janitor их не трогает).
|
||||
HEALTH_PREFIX = "health/"
|
||||
|
||||
|
||||
class StorageUnavailable(Exception):
|
||||
"""S3 недоступен/таймаут/ошибка сервера -> 503."""
|
||||
|
||||
|
||||
class ObjectMissing(Exception):
|
||||
"""Метаданные есть, объекта нет (рассогласование) -> 503 + лог."""
|
||||
|
||||
|
||||
def _secret(name):
|
||||
# S3_CLIENT_REQUIRED=0 — только job migrate (импортирует server.py, к S3 не обращается).
|
||||
return vault.secret(name, required=os.environ.get("S3_CLIENT_REQUIRED", "1") == "1")
|
||||
|
||||
|
||||
def make_client(access_env="S3_ACCESS_KEY_ID", secret_env="S3_SECRET_ACCESS_KEY",
|
||||
connect_timeout=None, read_timeout=None):
|
||||
endpoint = urlsplit(os.environ.get("S3_ENDPOINT", "https://s3:8333"))
|
||||
connect_timeout = connect_timeout or float(os.environ.get("S3_CONNECT_TIMEOUT_SECONDS", "2"))
|
||||
read_timeout = read_timeout or float(os.environ.get("S3_READ_TIMEOUT_SECONDS", "5"))
|
||||
# Короткие таймауты и без собственных повторов: зависший S3 не держит поток
|
||||
# дольше таймаута LB, повтор решает клиент (для upload — новым запросом).
|
||||
# Lab7: HTTPS к S3 с проверкой CA и hostname; plaintext endpoint запрещён.
|
||||
if endpoint.scheme != "https":
|
||||
raise SystemExit("S3_ENDPOINT must be https:// in lab7")
|
||||
http = urllib3.PoolManager(
|
||||
cert_reqs="CERT_REQUIRED", ca_certs=tlsutil.CA_FILE,
|
||||
timeout=urllib3.Timeout(connect=connect_timeout, read=read_timeout),
|
||||
retries=urllib3.Retry(total=0, connect=0, read=0, redirect=0, status=0),
|
||||
maxsize=int(os.environ.get("S3_POOL_SIZE", "16")),
|
||||
block=False)
|
||||
return Minio(endpoint.netloc, access_key=_secret(access_env), secret_key=_secret(secret_env),
|
||||
secure=endpoint.scheme == "https", region=os.environ.get("S3_REGION", "us-east-1"),
|
||||
http_client=http)
|
||||
|
||||
|
||||
def _is_transport_error(exc):
|
||||
return isinstance(exc, (urllib3.exceptions.HTTPError, OSError))
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _s3_op(operation, bucket, key):
|
||||
started = time.perf_counter()
|
||||
outcome = "ok"
|
||||
attrs = {"rpc.system": "aws-api", "rpc.service": "S3", "rpc.method": operation,
|
||||
"aws.s3.bucket": bucket, "server.address": "s3"}
|
||||
if key and not key.startswith(HEALTH_PREFIX):
|
||||
attrs["aws.s3.key"] = key
|
||||
try:
|
||||
with telemetry.child_span("s3 " + operation, SpanKind.CLIENT, attrs):
|
||||
yield
|
||||
except ObjectMissing:
|
||||
outcome = "not_found"
|
||||
raise
|
||||
except BaseException:
|
||||
outcome = "error"
|
||||
raise
|
||||
finally:
|
||||
telemetry.s3_duration.record(time.perf_counter() - started,
|
||||
{"messenger.s3.operation": operation, "outcome": outcome})
|
||||
|
||||
|
||||
class ObjectStore:
|
||||
def __init__(self, client, bucket):
|
||||
self.client = client
|
||||
self.bucket = bucket
|
||||
|
||||
def put(self, key, fileobj, length, content_type):
|
||||
with _s3_op("PutObject", self.bucket, key):
|
||||
self._put(key, fileobj, length, content_type)
|
||||
|
||||
def _put(self, key, fileobj, length, content_type):
|
||||
try:
|
||||
self.client.put_object(self.bucket, key, fileobj, length, content_type=content_type,
|
||||
part_size=PART_SIZE)
|
||||
except S3Error as exc:
|
||||
log.warning("s3 put failed: %s", exc.code)
|
||||
raise StorageUnavailable()
|
||||
except Exception as exc:
|
||||
if _is_transport_error(exc):
|
||||
log.warning("s3 put failed: %s", type(exc).__name__)
|
||||
raise StorageUnavailable()
|
||||
raise
|
||||
|
||||
def open(self, key):
|
||||
"""Поток объекта (urllib3 response). Закрывать: resp.close(); resp.release_conn()."""
|
||||
with _s3_op("GetObject", self.bucket, key):
|
||||
return self._open(key)
|
||||
|
||||
def _open(self, key):
|
||||
try:
|
||||
return self.client.get_object(self.bucket, key)
|
||||
except S3Error as exc:
|
||||
if exc.code in ("NoSuchKey", "NoSuchObject"):
|
||||
raise ObjectMissing()
|
||||
log.warning("s3 get failed: %s", exc.code)
|
||||
raise StorageUnavailable()
|
||||
except Exception as exc:
|
||||
if _is_transport_error(exc):
|
||||
log.warning("s3 get failed: %s", type(exc).__name__)
|
||||
raise StorageUnavailable()
|
||||
raise
|
||||
|
||||
def delete(self, key):
|
||||
"""Идемпотентно: отсутствие объекта — не ошибка (S3 DELETE так и работает)."""
|
||||
with _s3_op("DeleteObject", self.bucket, key):
|
||||
self._delete(key)
|
||||
|
||||
def _delete(self, key):
|
||||
try:
|
||||
self.client.remove_object(self.bucket, key)
|
||||
except S3Error as exc:
|
||||
if exc.code in ("NoSuchKey", "NoSuchObject"):
|
||||
return
|
||||
raise StorageUnavailable()
|
||||
except Exception as exc:
|
||||
if _is_transport_error(exc):
|
||||
raise StorageUnavailable()
|
||||
raise
|
||||
|
||||
def ping(self, probe_key):
|
||||
"""PUT + GET маленького служебного объекта health/<реплика>: проверяет S3,
|
||||
credentials и РЕАЛЬНЫЕ пути записи и чтения. HEAD bucket/healthz для этого мало:
|
||||
у SeaweedFS после рестарта они успешны, а первая запись ещё ~5 с висит
|
||||
(выбор raft-лидера master, выдача volume под запись)."""
|
||||
import io
|
||||
with _s3_op("HealthProbe", self.bucket, None):
|
||||
return self._ping(probe_key, io)
|
||||
|
||||
def _ping(self, probe_key, io):
|
||||
self.client.put_object(self.bucket, probe_key, io.BytesIO(b"ok"), 2, content_type="text/plain")
|
||||
resp = self.client.get_object(self.bucket, probe_key)
|
||||
try:
|
||||
if resp.read() != b"ok":
|
||||
raise RuntimeError("probe mismatch")
|
||||
finally:
|
||||
resp.close()
|
||||
resp.release_conn()
|
||||
return True
|
||||
|
||||
|
||||
class S3Health:
|
||||
"""Фоновая проверка S3, как DbHealth для PostgreSQL.
|
||||
|
||||
S3 НЕ входит в /health/ready: он общий для всех реплик, и его отказ не лечится
|
||||
исключением реплики из LB, а текстовые сообщения без него работают. Флаг нужен,
|
||||
чтобы upload при известном отказе S3 сразу получал 503, не принимая 10 MiB."""
|
||||
|
||||
def __init__(self, store, interval, stale_after, instance_id):
|
||||
self.store = store
|
||||
self.probe_key = HEALTH_PREFIX + instance_id
|
||||
self.interval = interval
|
||||
self.stale_after = stale_after
|
||||
self.last_ok = None
|
||||
self._stop = threading.Event()
|
||||
self._ok_event = threading.Event() # выставлен, пока последняя проверка успешна
|
||||
|
||||
def start(self):
|
||||
threading.Thread(target=self._loop, name="s3-health", daemon=True).start()
|
||||
|
||||
def stop(self):
|
||||
self._stop.set()
|
||||
|
||||
def ok(self):
|
||||
last = self.last_ok
|
||||
return last is not None and time.monotonic() - last <= self.stale_after
|
||||
|
||||
def wait_startup(self, timeout):
|
||||
"""Только на старте реплики (успешной проверки ещё не было): подождать до timeout,
|
||||
пока S3 станет доступен для записи. При подтверждённом отказе — не ждать."""
|
||||
if self.last_ok is None:
|
||||
self._ok_event.wait(timeout)
|
||||
return self.ok()
|
||||
|
||||
def known_down(self):
|
||||
"""S3 был доступен и перестал отвечать. На старте реплики (успешной проверки ещё
|
||||
не было) — False: чтение может работать раньше, чем прогреется запись."""
|
||||
last = self.last_ok
|
||||
return last is not None and time.monotonic() - last > self.stale_after
|
||||
|
||||
def _loop(self):
|
||||
healthy = None
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
self.store.ping(self.probe_key)
|
||||
self.last_ok = time.monotonic()
|
||||
self._ok_event.set()
|
||||
if healthy is not True:
|
||||
log.info("s3 health: ok", extra={"event": "s3.health.ok"})
|
||||
healthy = True
|
||||
except Exception as exc:
|
||||
self._ok_event.clear()
|
||||
if healthy is not False:
|
||||
log.warning("s3 health: failing (%s)", type(exc).__name__,
|
||||
extra={"event": "s3.health.failing", "error.type": type(exc).__name__})
|
||||
healthy = False
|
||||
self._stop.wait(self.interval)
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Операторский CLI (compose-сервис `ops`, profile tools). Вывод — JSON без секретов.
|
||||
|
||||
ops inspect <attachment_id> состояние: attachment, job, события, варианты, outbox, объекты S3
|
||||
ops failed [--limit N] реестр failed-заданий (DLQ на стороне БД)
|
||||
ops replay <attachment_id>... [--all-failed] [--error-code C] [--dry-run] [--reason TEXT]
|
||||
явный replay failed -> queued (ready/queued/processing не трогаются)
|
||||
ops dlq [--replay] [--purge-invalid]
|
||||
сообщения в RabbitMQ DLQ: показать; --replay — разобрать каждое
|
||||
по состоянию jobs (failed -> replay, остальное -> отбросить с audit)
|
||||
ops publish-raw <json> учебное: опубликовать произвольное тело (проверка DLQ)
|
||||
|
||||
Replay всегда проходит через строку jobs под FOR UPDATE: повтор ready-задания отклоняется,
|
||||
поэтому «повторить» не означает исполнить дубль уже успешной работы.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
import common
|
||||
import telemetry
|
||||
import jobs
|
||||
import objstore
|
||||
|
||||
EXTRA_ATTEMPTS = common.env_int("JOB_MAX_ATTEMPTS", 5)
|
||||
|
||||
|
||||
def db():
|
||||
return psycopg.connect(common.database_conninfo(), row_factory=dict_row)
|
||||
|
||||
|
||||
def jsonable(value):
|
||||
if isinstance(value, dict):
|
||||
return {k: jsonable(v) for k, v in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [jsonable(v) for v in value]
|
||||
if isinstance(value, (str, int, float, bool)) or value is None:
|
||||
return value
|
||||
if hasattr(value, "isoformat"):
|
||||
return value.isoformat().replace("+00:00", "Z")
|
||||
return str(value)
|
||||
|
||||
|
||||
def out(data):
|
||||
print(json.dumps(jsonable(data), ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
def s3_objects(prefix):
|
||||
"""Только имена/размеры (ключ janitor: List, без чтения содержимого)."""
|
||||
store = objstore.ObjectStore(objstore.make_client(), os.environ.get("S3_BUCKET", "messenger-attachments"))
|
||||
try:
|
||||
return sorted((o.object_name, o.size) for o in store.client.list_objects(store.bucket, prefix=prefix, recursive=True))
|
||||
except Exception as exc:
|
||||
return [("error", type(exc).__name__)]
|
||||
|
||||
|
||||
def cmd_inspect(args):
|
||||
with db() as conn:
|
||||
att = conn.execute(
|
||||
"""SELECT id, chat_id, status, error_code, content_type, size_bytes, sha256, width, height,
|
||||
object_key, staging_key, pipeline_version, created_at, updated_at
|
||||
FROM attachments WHERE id = %s""", (args.attachment_id,)).fetchone()
|
||||
if att is None:
|
||||
out({"error": "not_found"})
|
||||
return 1
|
||||
job = conn.execute(
|
||||
"""SELECT id, pipeline_version, status, attempt, max_attempts, next_attempt_at, lease_owner,
|
||||
lease_until, error_code, last_error, replay_count, created_at, updated_at, finished_at
|
||||
FROM jobs WHERE attachment_id = %s ORDER BY pipeline_version""", (args.attachment_id,)).fetchall()
|
||||
job_ids = [j["id"] for j in job]
|
||||
events = conn.execute(
|
||||
"SELECT job_id, at, event, attempt, actor, detail FROM job_events WHERE job_id = ANY(%s) ORDER BY id",
|
||||
(job_ids,)).fetchall()
|
||||
outbox = conn.execute(
|
||||
"""SELECT id, payload->>'attempt' AS attempt, available_at, created_at, published_at, publish_count,
|
||||
payload->>'traceparent' AS traceparent
|
||||
FROM outbox WHERE job_id = ANY(%s) ORDER BY id""", (job_ids,)).fetchall()
|
||||
variants = conn.execute(
|
||||
"""SELECT pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256
|
||||
FROM attachment_variants WHERE attachment_id = %s ORDER BY pipeline_version, name""",
|
||||
(args.attachment_id,)).fetchall()
|
||||
objects = s3_objects("attachments/%s/" % args.attachment_id)
|
||||
staging = s3_objects(att["staging_key"]) if att["staging_key"] else []
|
||||
out({"attachment": att, "jobs": job, "events": events, "outbox": outbox, "variants": variants,
|
||||
"s3_final_objects": objects, "s3_staging_objects": staging})
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_failed(args):
|
||||
with db() as conn:
|
||||
rows = conn.execute(
|
||||
"""SELECT j.attachment_id, j.id AS job_id, j.error_code, j.attempt, j.max_attempts, j.replay_count,
|
||||
j.last_error, j.updated_at, a.staging_key IS NOT NULL AS replayable
|
||||
FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.status = 'failed' ORDER BY j.updated_at DESC LIMIT %s""", (args.limit,)).fetchall()
|
||||
out({"failed": rows, "count": len(rows)})
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_replay(args):
|
||||
results = []
|
||||
with db() as conn:
|
||||
ids = list(args.attachment_ids)
|
||||
if args.all_failed:
|
||||
q = "SELECT attachment_id FROM jobs WHERE status = 'failed'"
|
||||
params = []
|
||||
if args.error_code:
|
||||
q += " AND error_code = %s"
|
||||
params.append(args.error_code)
|
||||
ids += [str(r["attachment_id"]) for r in conn.execute(q, params)]
|
||||
for att_id in ids:
|
||||
with conn.transaction():
|
||||
result, job = jobs.replay(conn, att_id, "ops:" + common.HOSTNAME, EXTRA_ATTEMPTS,
|
||||
args.reason, dry_run=args.dry_run)
|
||||
results.append({"attachment_id": att_id, "result": result,
|
||||
"job_id": str(job["job_id"]) if job else None})
|
||||
out({"replay": results})
|
||||
return 0 if all(r["result"] in ("replayed", "would_replay") for r in results) else 3
|
||||
|
||||
|
||||
def broker_channel():
|
||||
conn = pika.BlockingConnection(common.broker_parameters())
|
||||
return conn, conn.channel()
|
||||
|
||||
|
||||
def cmd_dlq(args):
|
||||
conn, ch = broker_channel()
|
||||
seen = []
|
||||
tags = []
|
||||
try:
|
||||
with db() as dbc:
|
||||
while True:
|
||||
method, props, body = ch.basic_get(common.DLQ, auto_ack=False)
|
||||
if method is None:
|
||||
break
|
||||
deaths = (props.headers or {}).get("x-death") or []
|
||||
reason = deaths[0].get("reason") if deaths else None
|
||||
item = {"reason": reason.decode() if isinstance(reason, bytes) else reason,
|
||||
"delivery_count": (props.headers or {}).get("x-delivery-count"), "action": "kept"}
|
||||
try:
|
||||
msg = jobs.parse_message(body)
|
||||
item["job_id"] = msg["job_id"]
|
||||
if args.replay:
|
||||
with dbc.transaction():
|
||||
job = jobs.load_job(dbc, msg["job_id"], lock=True)
|
||||
if job is None:
|
||||
item["action"] = "kept_unknown_job"
|
||||
elif job["job_status"] == "failed":
|
||||
result, _ = jobs.replay(dbc, str(job["attachment_id"]), "ops-dlq", EXTRA_ATTEMPTS,
|
||||
"dlq replay")
|
||||
item["action"] = result
|
||||
else:
|
||||
# queued/processing/ready: состояние уже ведёт БД, дубль не нужен.
|
||||
jobs.add_event(dbc, job["job_id"], "dlq_message_dropped", msg["attempt"], "ops-dlq",
|
||||
{"job_status": job["job_status"], "reason": item["reason"]})
|
||||
item["action"] = "dropped_job_" + job["job_status"]
|
||||
except jobs.InvalidMessage as exc:
|
||||
item["invalid"] = str(exc)
|
||||
if args.purge_invalid:
|
||||
item["action"] = "purged_invalid"
|
||||
seen.append(item)
|
||||
if item["action"].startswith("kept"):
|
||||
tags.append(method.delivery_tag) # вернём в DLQ после обхода
|
||||
else:
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
for tag in tags:
|
||||
ch.basic_nack(tag, requeue=True)
|
||||
finally:
|
||||
conn.close()
|
||||
out({"dlq_messages": seen, "count": len(seen)})
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_publish_raw(args):
|
||||
conn, ch = broker_channel()
|
||||
try:
|
||||
ch.confirm_delivery()
|
||||
ch.basic_publish(common.EXCHANGE, common.ROUTING_KEY, args.body.encode(),
|
||||
pika.BasicProperties(delivery_mode=2, content_type="application/json"), mandatory=True)
|
||||
finally:
|
||||
conn.close()
|
||||
out({"published": True})
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
telemetry.configure_logging(stream=sys.stderr) # stdout — только JSON-результат команды
|
||||
p = argparse.ArgumentParser(prog="ops")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
s = sub.add_parser("inspect")
|
||||
s.add_argument("attachment_id")
|
||||
s.set_defaults(func=cmd_inspect)
|
||||
s = sub.add_parser("failed")
|
||||
s.add_argument("--limit", type=int, default=50)
|
||||
s.set_defaults(func=cmd_failed)
|
||||
s = sub.add_parser("replay")
|
||||
s.add_argument("attachment_ids", nargs="*")
|
||||
s.add_argument("--all-failed", action="store_true")
|
||||
s.add_argument("--error-code")
|
||||
s.add_argument("--dry-run", action="store_true")
|
||||
s.add_argument("--reason", default="operator replay")
|
||||
s.set_defaults(func=cmd_replay)
|
||||
s = sub.add_parser("dlq")
|
||||
s.add_argument("--replay", action="store_true")
|
||||
s.add_argument("--purge-invalid", action="store_true")
|
||||
s.set_defaults(func=cmd_dlq)
|
||||
s = sub.add_parser("publish-raw")
|
||||
s.add_argument("body")
|
||||
s.set_defaults(func=cmd_publish_raw)
|
||||
args = p.parse_args()
|
||||
return args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Outbox relay + reaper (compose-сервис `relay`).
|
||||
|
||||
Закрывает разрыв PostgreSQL <-> broker (transactional outbox):
|
||||
API в ОДНОЙ транзакции пишет queued-вложение, jobs и outbox. Relay берёт неопубликованные
|
||||
строки (FOR UPDATE SKIP LOCKED — несколько relay не мешают друг другу), публикует каждую
|
||||
в RabbitMQ с publisher confirm (persistent, mandatory) и только ПОСЛЕ подтверждения
|
||||
брокера ставит published_at в той же транзакции. Крах между COMMIT API и publish, между
|
||||
publish и confirm или между confirm и UPDATE outbox -> строка остаётся неопубликованной и
|
||||
будет опубликована снова: возможен дубль сообщения (at-least-once), его гасит worker по
|
||||
состоянию jobs.
|
||||
|
||||
Будит relay NOTIFY из триггера outbox; без уведомления — опрос раз в RELAY_POLL_SECONDS.
|
||||
Строки с available_at в будущем (retry с backoff) публикуются, когда наступит срок.
|
||||
|
||||
Reaper (раз в REAPER_INTERVAL_SECONDS, под advisory-блокировкой — один на всех):
|
||||
* processing с истёкшей арендой -> queued (backoff) или failed(retry_exhausted);
|
||||
* queued без движения дольше JOB_REDRIVE_AFTER_SECONDS и без неопубликованного outbox
|
||||
-> ещё одна публикация (сообщение могло потеряться вместе с volume брокера);
|
||||
* опубликованные строки outbox старше OUTBOX_RETENTION_SECONDS удаляются.
|
||||
|
||||
Учебная инъекция отказа: RELAY_FAULT=crash-before-publish | crash-after-publish —
|
||||
один раз за жизнь контейнера (маркер в /tmp) процесс делает os._exit посреди батча.
|
||||
|
||||
Lab6:
|
||||
* каждое сообщение публикуется в PRODUCER span «attachments send» — child контекста из
|
||||
payload.traceparent (span «create» API/worker). Контекст send записывается и в тело
|
||||
(traceparent/tracestate, по jobs.schema.json), и в AMQP headers — worker продолжает трассу;
|
||||
* метрики: messenger.outbox.published{outcome}, messenger.outbox.publish_delay (s, от
|
||||
available_at до publisher confirm), и наблюдаемые gauges очереди по источнику истины
|
||||
(PostgreSQL): messenger.jobs.count{status}, messenger.jobs.oldest_age{status} (s, возраст
|
||||
старейшего незавершённого job от durable acceptance), messenger.jobs.ready_lag (s, сколько
|
||||
ждёт самый старый job, которому уже пора выполняться), messenger.outbox.pending и
|
||||
messenger.outbox.oldest_age (не опубликовано relay). Gauges считает отдельное соединение
|
||||
со statement_timeout 2 с раз в интервал экспорта метрик.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
import common
|
||||
import jobs
|
||||
import telemetry
|
||||
from telemetry import SpanKind, Status, StatusCode
|
||||
|
||||
log = logging.getLogger("relay")
|
||||
POLL_SECONDS = common.env_float("RELAY_POLL_SECONDS", 1)
|
||||
BATCH = common.env_int("RELAY_BATCH", 100)
|
||||
REAPER_INTERVAL = common.env_float("REAPER_INTERVAL_SECONDS", 5)
|
||||
REDRIVE_AFTER = common.env_int("JOB_REDRIVE_AFTER_SECONDS", 900)
|
||||
OUTBOX_RETENTION = common.env_int("OUTBOX_RETENTION_SECONDS", 86400)
|
||||
RETRY_BASE = common.env_float("JOB_RETRY_BASE_SECONDS", 2)
|
||||
RETRY_MAX = common.env_float("JOB_RETRY_MAX_SECONDS", 60)
|
||||
FAULT = os.environ.get("RELAY_FAULT", "")
|
||||
FAULT_MARKER = "/tmp/relay-fault.done"
|
||||
HEARTBEAT = "/tmp/relay.heartbeat"
|
||||
REAPER_LOCK_ID = 727003
|
||||
|
||||
PUBLISHED = telemetry.meter.create_counter(
|
||||
"messenger.outbox.published", unit="{message}", description="Outbox rows published to the broker")
|
||||
PUBLISH_DELAY = telemetry.meter.create_histogram(
|
||||
"messenger.outbox.publish_delay", unit="s",
|
||||
description="Delay from outbox available_at to broker publisher confirm")
|
||||
|
||||
|
||||
class QueueGauges:
|
||||
"""Глубина очереди и возраст заданий по PostgreSQL (источник истины), не по брокеру."""
|
||||
QUERY = """
|
||||
SELECT
|
||||
(SELECT json_object_agg(status, n) FROM (SELECT status, count(*) AS n FROM jobs GROUP BY status) c) AS counts,
|
||||
(SELECT json_object_agg(status, age) FROM (
|
||||
SELECT status, EXTRACT(EPOCH FROM now() - min(created_at))::float8 AS age FROM jobs
|
||||
WHERE status IN ('queued', 'processing') GROUP BY status) a) AS ages,
|
||||
(SELECT COALESCE(EXTRACT(EPOCH FROM now() - min(next_attempt_at)), 0)::float8 FROM jobs
|
||||
WHERE status = 'queued' AND next_attempt_at <= now()) AS ready_lag,
|
||||
(SELECT count(*) FROM outbox WHERE published_at IS NULL AND available_at <= now()) AS outbox_pending,
|
||||
(SELECT COALESCE(EXTRACT(EPOCH FROM now() - min(available_at)), 0)::float8 FROM outbox
|
||||
WHERE published_at IS NULL AND available_at <= now()) AS outbox_age"""
|
||||
STATUSES = ("queued", "processing", "ready", "failed")
|
||||
|
||||
def __init__(self, conninfo):
|
||||
self.conninfo = conninfo
|
||||
self.conn = None
|
||||
self.lock = threading.Lock()
|
||||
self.cache = (0.0, None)
|
||||
|
||||
def snapshot(self):
|
||||
# Несколько callbacks за один сбор метрик -> один SQL-запрос (кэш на 2 с).
|
||||
with self.lock:
|
||||
at, data = self.cache
|
||||
if data is not None and time.monotonic() - at < 2:
|
||||
return data
|
||||
try:
|
||||
if self.conn is None or self.conn.closed:
|
||||
self.conn = psycopg.connect(self.conninfo, autocommit=True, row_factory=dict_row,
|
||||
options="-c statement_timeout=2000")
|
||||
data = self.conn.execute(self.QUERY).fetchone()
|
||||
except psycopg.Error:
|
||||
try:
|
||||
if self.conn is not None:
|
||||
self.conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.conn, data = None, None
|
||||
self.cache = (time.monotonic(), data)
|
||||
return data
|
||||
|
||||
def register(self):
|
||||
def counts(options):
|
||||
d = self.snapshot()
|
||||
if d is not None:
|
||||
got = d["counts"] or {}
|
||||
for st in self.STATUSES:
|
||||
yield telemetry.metrics.Observation(int(got.get(st, 0)), {"messenger.job.status": st})
|
||||
|
||||
def ages(options):
|
||||
d = self.snapshot()
|
||||
if d is not None:
|
||||
got = d["ages"] or {}
|
||||
for st in ("queued", "processing"):
|
||||
yield telemetry.metrics.Observation(float(got.get(st) or 0.0), {"messenger.job.status": st})
|
||||
|
||||
def ready_lag(options):
|
||||
d = self.snapshot()
|
||||
if d is not None:
|
||||
yield telemetry.metrics.Observation(float(d["ready_lag"] or 0.0))
|
||||
|
||||
def outbox_pending(options):
|
||||
d = self.snapshot()
|
||||
if d is not None:
|
||||
yield telemetry.metrics.Observation(int(d["outbox_pending"] or 0))
|
||||
|
||||
def outbox_age(options):
|
||||
d = self.snapshot()
|
||||
if d is not None:
|
||||
yield telemetry.metrics.Observation(float(d["outbox_age"] or 0.0))
|
||||
|
||||
m = telemetry.meter
|
||||
m.create_observable_gauge("messenger.jobs.count", [counts], unit="{job}",
|
||||
description="Jobs by status (PostgreSQL jobs table)")
|
||||
m.create_observable_gauge("messenger.jobs.oldest_age", [ages], unit="s",
|
||||
description="Age of the oldest unfinished job since durable acceptance")
|
||||
m.create_observable_gauge("messenger.jobs.ready_lag", [ready_lag], unit="s",
|
||||
description="How long the oldest due queued job has been waiting for a worker")
|
||||
m.create_observable_gauge("messenger.outbox.pending", [outbox_pending], unit="{message}",
|
||||
description="Due outbox rows not yet published to the broker")
|
||||
m.create_observable_gauge("messenger.outbox.oldest_age", [outbox_age], unit="s",
|
||||
description="Age of the oldest due unpublished outbox row")
|
||||
|
||||
|
||||
def fault(point):
|
||||
if FAULT != point or os.path.exists(FAULT_MARKER):
|
||||
return
|
||||
with open(FAULT_MARKER, "w") as f:
|
||||
f.write(point)
|
||||
log.warning("FAULT INJECTION %s: exiting without finishing the batch", point,
|
||||
extra={"event": "fault.injected", "fault.point": point})
|
||||
os._exit(86)
|
||||
|
||||
|
||||
class Relay:
|
||||
def __init__(self):
|
||||
self.conninfo = common.database_conninfo()
|
||||
self.db = None
|
||||
self.listen = None
|
||||
self.broker = None
|
||||
self.channel = None
|
||||
self.next_reap = 0.0
|
||||
self.stop = threading.Event()
|
||||
|
||||
# --- соединения ---
|
||||
def ensure_db(self):
|
||||
if self.db is None or self.db.closed:
|
||||
self.db = psycopg.connect(self.conninfo, row_factory=dict_row)
|
||||
if self.listen is None or self.listen.closed:
|
||||
self.listen = psycopg.connect(self.conninfo, autocommit=True)
|
||||
self.listen.execute("LISTEN outbox")
|
||||
|
||||
def ensure_broker(self):
|
||||
if self.broker is None or self.broker.is_closed or self.channel is None or self.channel.is_closed:
|
||||
self.close_broker()
|
||||
self.broker = common.connect_broker(log, self.stop)
|
||||
if self.broker is None:
|
||||
return
|
||||
self.channel = self.broker.channel()
|
||||
# Publisher confirms: basic_publish ждёт ack брокера (сообщение записано в
|
||||
# quorum-очередь) и бросает NackError/UnroutableError при отказе.
|
||||
self.channel.confirm_delivery()
|
||||
log.info("connected to broker", extra={"event": "broker.connected"})
|
||||
|
||||
def close_broker(self):
|
||||
try:
|
||||
if self.broker is not None and not self.broker.is_closed:
|
||||
self.broker.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.broker = self.channel = None
|
||||
|
||||
def close_db(self):
|
||||
for conn in (self.db, self.listen):
|
||||
try:
|
||||
if conn is not None:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.db = self.listen = None
|
||||
|
||||
# --- публикация ---
|
||||
def publish_batch(self):
|
||||
"""Один батч в одной транзакции. Возвращает число опубликованных строк."""
|
||||
spans = []
|
||||
try:
|
||||
with self.db.transaction():
|
||||
rows = self.db.execute(
|
||||
"""SELECT id, job_id, payload, EXTRACT(EPOCH FROM now() - available_at)::float8 AS delay_s
|
||||
FROM outbox WHERE published_at IS NULL AND available_at <= now()
|
||||
ORDER BY available_at, id LIMIT %s FOR UPDATE SKIP LOCKED""", (BATCH,)).fetchall()
|
||||
if not rows:
|
||||
return 0
|
||||
fault("crash-before-publish") # COMMIT задания есть, publish ещё нет
|
||||
for row in rows:
|
||||
payload = dict(row["payload"])
|
||||
parent = telemetry.extract({k: payload[k] for k in ("traceparent", "tracestate") if k in payload})
|
||||
span = telemetry.tracer.start_span(
|
||||
"attachments send", kind=SpanKind.PRODUCER, context=parent,
|
||||
attributes={"messaging.system": "rabbitmq", "messaging.operation.type": "send",
|
||||
"messaging.operation.name": "publish",
|
||||
"messaging.destination.name": common.EXCHANGE,
|
||||
"messaging.rabbitmq.destination.routing_key": common.ROUTING_KEY,
|
||||
"messaging.message.id": "%s:%s" % (payload["job_id"], payload["attempt"]),
|
||||
"messenger.job.id": payload["job_id"],
|
||||
"messenger.attachment.id": payload["attachment_id"],
|
||||
"messenger.job.attempt": payload["attempt"],
|
||||
"messenger.outbox.id": row["id"],
|
||||
"messenger.outbox.publish_delay_s": round(row["delay_s"] or 0.0, 3)})
|
||||
spans.append((span, row["delay_s"] or 0.0))
|
||||
with telemetry.trace.use_span(span, end_on_exit=False):
|
||||
carrier = telemetry.inject_dict()
|
||||
payload.pop("tracestate", None)
|
||||
payload.update(carrier)
|
||||
self.channel.basic_publish(
|
||||
exchange=common.EXCHANGE, routing_key=common.ROUTING_KEY,
|
||||
body=json.dumps(payload, separators=(",", ":")).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
content_type="application/json", delivery_mode=pika.DeliveryMode.Persistent,
|
||||
message_id="%s:%s" % (payload["job_id"], payload["attempt"]), type=jobs.JOB_TYPE,
|
||||
headers=dict({"x-outbox-id": row["id"]}, **carrier)),
|
||||
mandatory=True)
|
||||
fault("crash-after-publish") # confirm получен, published_at не записан -> дубль
|
||||
self.db.execute(
|
||||
"UPDATE outbox SET published_at = now(), publish_count = publish_count + 1 WHERE id = ANY(%s)",
|
||||
([r["id"] for r in rows],))
|
||||
except BaseException as exc:
|
||||
# Транзакция откатилась: строки останутся неопубликованными и уйдут следующим батчем.
|
||||
for span, _delay in spans:
|
||||
span.set_attribute("error.type", type(exc).__name__)
|
||||
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
span.end()
|
||||
if spans:
|
||||
PUBLISHED.add(len(spans), {"outcome": "failed", "error.type": type(exc).__name__})
|
||||
raise
|
||||
for span, delay in spans:
|
||||
PUBLISH_DELAY.record(delay)
|
||||
span.end()
|
||||
PUBLISHED.add(len(rows), {"outcome": "ok"})
|
||||
log.info("published %d job message(s)", len(rows), extra={"event": "outbox.published", "count": len(rows)})
|
||||
return len(rows)
|
||||
|
||||
def reap(self):
|
||||
with self.db.transaction():
|
||||
if not self.db.execute("SELECT pg_try_advisory_xact_lock(%s) AS ok", (REAPER_LOCK_ID,)).fetchone()["ok"]:
|
||||
return
|
||||
expired = jobs.reap_expired_leases(self.db, RETRY_BASE, RETRY_MAX, actor="reaper:" + common.OWNER)
|
||||
redriven = jobs.redrive_stale_queued(self.db, REDRIVE_AFTER, actor="reaper:" + common.OWNER)
|
||||
purged = self.db.execute(
|
||||
"DELETE FROM outbox WHERE published_at < now() - make_interval(secs => %s)",
|
||||
(OUTBOX_RETENTION,)).rowcount
|
||||
if expired or redriven or purged:
|
||||
log.info("reaper: expired_leases=%d redriven=%d outbox_purged=%d", expired, redriven, purged,
|
||||
extra={"event": "reaper.pass", "expired_leases": expired, "redriven": redriven,
|
||||
"outbox_purged": purged})
|
||||
|
||||
def wait_notify(self, timeout):
|
||||
"""Ждём NOTIFY outbox не дольше timeout; параллельно обслуживаем heartbeat брокера."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if self.broker is not None:
|
||||
self.broker.process_data_events(time_limit=0)
|
||||
for _ in self.listen.notifies(timeout=min(0.25, max(0.01, deadline - time.monotonic())), stop_after=1):
|
||||
return
|
||||
|
||||
def run(self):
|
||||
log.info("relay started owner=%s fault=%s", common.OWNER, FAULT or "-", extra={"event": "relay.started"})
|
||||
delay = 0.5
|
||||
while not self.stop.is_set():
|
||||
common.touch(HEARTBEAT)
|
||||
try:
|
||||
self.ensure_db()
|
||||
self.ensure_broker()
|
||||
if self.broker is None:
|
||||
continue
|
||||
while self.publish_batch() == BATCH:
|
||||
pass
|
||||
if time.monotonic() >= self.next_reap:
|
||||
self.reap()
|
||||
self.next_reap = time.monotonic() + REAPER_INTERVAL
|
||||
self.wait_notify(POLL_SECONDS)
|
||||
delay = 0.5
|
||||
except (pika.exceptions.AMQPError, pika.exceptions.UnroutableError, pika.exceptions.NackError) as exc:
|
||||
# Транзакция батча откатилась: строки остались неопубликованными.
|
||||
log.warning("broker publish failed (%s), retry in %.1fs", type(exc).__name__, delay,
|
||||
extra={"event": "broker.publish_failed", "error.type": type(exc).__name__})
|
||||
self.close_broker()
|
||||
self.stop.wait(delay)
|
||||
delay = min(5.0, delay * 2)
|
||||
except psycopg.Error as exc:
|
||||
log.warning("database error (%s), retry in %.1fs", type(exc).__name__, delay,
|
||||
extra={"event": "db.error", "error.type": type(exc).__name__})
|
||||
self.close_db()
|
||||
self.stop.wait(delay)
|
||||
delay = min(5.0, delay * 2)
|
||||
self.close_broker()
|
||||
self.close_db()
|
||||
|
||||
|
||||
def main():
|
||||
import signal
|
||||
telemetry.setup("messenger-relay")
|
||||
relay = Relay()
|
||||
QueueGauges(relay.conninfo).register()
|
||||
signal.signal(signal.SIGTERM, lambda *_: relay.stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: relay.stop.set())
|
||||
relay.run()
|
||||
log.info("relay stopped", extra={"event": "relay.stopped"})
|
||||
telemetry.shutdown()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Идемпотентный bootstrap S3 (однократный compose-job `s3-init`).
|
||||
|
||||
Работает под admin-credentials, которые есть ТОЛЬКО у этого job (API и janitor их не
|
||||
получают). Повторный запуск ничего не ломает:
|
||||
1. ждёт доступности S3 (до 60 с);
|
||||
2. создаёт bucket, если его нет (уже существующий — не ошибка);
|
||||
3. проверяет приватность: анонимные GET объекта и ListBucket должны получить 403.
|
||||
Если bucket вдруг публичен — exit 1, и API не стартует (depends_on).
|
||||
Права пользователей (api: Read+Write, janitor: List+Write) задаются декларативно в
|
||||
secrets/s3_identities.json (генерирует scripts/init-secrets.sh).
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from minio.error import S3Error
|
||||
|
||||
import objstore
|
||||
import tlsutil
|
||||
import telemetry
|
||||
|
||||
telemetry.configure_logging()
|
||||
log = logging.getLogger("messenger.s3-init")
|
||||
|
||||
|
||||
def anonymous_status(url):
|
||||
try:
|
||||
# Lab7: анонимная проверка тоже по HTTPS с проверкой CA (без client cert и без ключей).
|
||||
with urllib.request.urlopen(url, timeout=3, context=tlsutil.client_context(with_identity=False)) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main():
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:8333").rstrip("/")
|
||||
# Первый PUT в новый bucket ждёт, пока SeaweedFS выделит volume-ы коллекции: таймаут больше.
|
||||
client = objstore.make_client(read_timeout=30)
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
exists = client.bucket_exists(bucket)
|
||||
break
|
||||
except Exception as exc:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
log.info("s3 not ready (%s), retrying", type(exc).__name__)
|
||||
time.sleep(1)
|
||||
created = False
|
||||
if not exists:
|
||||
try:
|
||||
client.make_bucket(bucket)
|
||||
created = True
|
||||
except S3Error as exc:
|
||||
if exc.code not in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
|
||||
raise
|
||||
# Контрольный объект: на нём проверяем, что анонимный GET не проходит.
|
||||
probe = "bootstrap/probe"
|
||||
for attempt in range(1, 6):
|
||||
try:
|
||||
client.put_object(bucket, probe, io.BytesIO(b"private"), 7, content_type="text/plain")
|
||||
break
|
||||
except Exception as exc:
|
||||
if attempt == 5:
|
||||
raise
|
||||
log.info("probe put failed (%s), retry %d", type(exc).__name__, attempt)
|
||||
time.sleep(2)
|
||||
checks = {
|
||||
"anonymous_get_object": anonymous_status("%s/%s/%s" % (endpoint, bucket, probe)),
|
||||
"anonymous_list_bucket": anonymous_status("%s/%s?list-type=2" % (endpoint, bucket)),
|
||||
}
|
||||
client.remove_object(bucket, probe)
|
||||
private = all(code in (401, 403) for code in checks.values())
|
||||
print(json.dumps({"bucket": bucket, "created": created, "already_existed": exists,
|
||||
"anonymous_http_status": checks, "private": private}), flush=True)
|
||||
return 0 if private else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Lab7: пароли — Argon2id (argon2-cffi), сессионные токены — случайные 256 бит.
|
||||
|
||||
Формат хеша — стандартная PHC-строка `$argon2id$v=19$m=<KiB>,t=<iter>,p=<lanes>$<salt>$<hash>`:
|
||||
соль (16 байт, случайная на каждый хеш) и параметры хранятся вместе с хешем, поэтому смена
|
||||
параметров не ломает старые записи. Параметры по умолчанию — базовый профиль OWASP
|
||||
(m=19 MiB, t=2, p=1); выбор обоснован замером на стенде (student-tests/argon2_bench.py,
|
||||
evidence/argon2-bench.json) и задаётся ARGON2_MEMORY_KIB / ARGON2_ITERATIONS / ARGON2_PARALLELISM.
|
||||
|
||||
Rehash: при успешном входе хеш со старыми параметрами или старой схемой (scrypt из lab2–6)
|
||||
пересчитывается Argon2id с текущими параметрами — plaintext для этого есть только в момент входа.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
|
||||
ARGON2_MEMORY_KIB = int(os.environ.get("ARGON2_MEMORY_KIB", "19456"))
|
||||
ARGON2_ITERATIONS = int(os.environ.get("ARGON2_ITERATIONS", "2"))
|
||||
ARGON2_PARALLELISM = int(os.environ.get("ARGON2_PARALLELISM", "1"))
|
||||
# Нижняя граница задания: не ниже 19 MiB, t=2, p=1 — более слабый профиль процесс не примет.
|
||||
if ARGON2_MEMORY_KIB < 19456 or ARGON2_ITERATIONS < 2 or ARGON2_PARALLELISM < 1:
|
||||
raise SystemExit("Argon2id parameters below the lab7 baseline (m>=19456 KiB, t>=2, p>=1)")
|
||||
|
||||
HASHER = PasswordHasher(time_cost=ARGON2_ITERATIONS, memory_cost=ARGON2_MEMORY_KIB,
|
||||
parallelism=ARGON2_PARALLELISM, hash_len=32, salt_len=16, type=Type.ID)
|
||||
|
||||
# Устаревшая схема lab2–6 (только проверка + rehash, новые хеши не создаются).
|
||||
_SCRYPT_MAXMEM = 128 * 1024 * 1024
|
||||
|
||||
|
||||
def params():
|
||||
return {"algorithm": "argon2id", "memory_kib": ARGON2_MEMORY_KIB, "iterations": ARGON2_ITERATIONS,
|
||||
"parallelism": ARGON2_PARALLELISM, "salt_bytes": 16, "hash_bytes": 32}
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
return HASHER.hash(password)
|
||||
|
||||
|
||||
def _verify_scrypt(password, stored):
|
||||
try:
|
||||
scheme, log_n, r, p, salt, digest = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
actual = hashlib.scrypt(password.encode("utf-8"), salt=base64.b64decode(salt), n=2 ** int(log_n),
|
||||
r=int(r), p=int(p), maxmem=_SCRYPT_MAXMEM, dklen=32)
|
||||
return hmac.compare_digest(actual, base64.b64decode(digest))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def verify_password(password, stored):
|
||||
"""-> (ok, needs_rehash). Сравнение внутри libargon2 — за постоянное время."""
|
||||
if stored.startswith("$argon2"):
|
||||
try:
|
||||
HASHER.verify(stored, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False, False
|
||||
return True, HASHER.check_needs_rehash(stored)
|
||||
ok = _verify_scrypt(password, stored)
|
||||
return ok, ok
|
||||
|
||||
|
||||
# Хеш несуществующего пользователя: неверный логин тратит столько же времени (тот же Argon2id),
|
||||
# сколько неверный пароль, и не выдаёт, существует ли username.
|
||||
DUMMY_HASH = hash_password(secrets.token_urlsafe(16))
|
||||
|
||||
|
||||
def new_token():
|
||||
"""Непрозрачный случайный токен: 32 байта = 256 бит энтропии."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
"""В БД лежит только SHA-256 токена (у токена 256 бит энтропии — перебор невозможен,
|
||||
медленный KDF не нужен): утечка таблицы sessions не даёт готовых сессий."""
|
||||
return hashlib.sha256(token.encode("utf-8")).digest()
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab7: самопроверка least privilege ИЗНУТРИ контейнера сервиса (под его собственной identity).
|
||||
|
||||
docker compose exec -T api python /app/src/selfcheck.py
|
||||
docker compose exec -T worker python /app/src/selfcheck.py
|
||||
|
||||
Ничего секретного не печатает: только HTTP-статусы, имена полей KV, SHA-256-префиксы (8 hex)
|
||||
значений ключей доступа (чтобы тест сравнил «чей это ключ» без раскрытия), коды ошибок SQL.
|
||||
Вывод — один JSON в stdout.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import psycopg # noqa: E402
|
||||
|
||||
import vault # noqa: E402
|
||||
|
||||
ROLE = vault.BAO_AUTH_ROLE
|
||||
OTHER = {"api": "worker", "worker": "api", "relay": "worker", "janitor": "api"}.get(ROLE, "api")
|
||||
|
||||
|
||||
def fp(value):
|
||||
return hashlib.sha256(str(value).encode()).hexdigest()[:8]
|
||||
|
||||
|
||||
def bao_checks():
|
||||
c = vault.Client()
|
||||
c.login()
|
||||
token = c._token
|
||||
out = {"login": {"policies": c.lease_info["policies"], "ttl": c.lease_info["ttl"],
|
||||
"renewable": c.lease_info["renewable"]}}
|
||||
st, data = vault.request("GET", "kv/data/messenger/%s" % ROLE, token=token)
|
||||
values = data.get("data", {}).get("data", {}) if st == 200 else {}
|
||||
out["read_own"] = st
|
||||
out["own_fields"] = sorted(values)
|
||||
out["own_fingerprints"] = {k: fp(v) for k, v in values.items() if k in ("S3_ACCESS_KEY_ID",)}
|
||||
probes = {
|
||||
"read_other_service": ("GET", "kv/data/messenger/%s" % OTHER, None),
|
||||
"read_migrate_admin": ("GET", "kv/data/messenger/migrate", None),
|
||||
"list_metadata": ("LIST", "kv/metadata/messenger", None),
|
||||
"write_own_secret": ("POST", "kv/data/messenger/%s" % ROLE, {"data": {"x": "y"}}),
|
||||
"write_policy": ("PUT", "sys/policies/acl/evil", {"policy": 'path "*" {capabilities=["sudo"]}'}),
|
||||
"create_token": ("POST", "auth/token/create", {"policies": ["root"]}),
|
||||
"seal": ("PUT", "sys/seal", {}),
|
||||
"list_auth_roles": ("LIST", "auth/cert/certs", None),
|
||||
}
|
||||
for name, (method, path, body) in probes.items():
|
||||
st, _ = vault.request(method, path, token=token, body=body)
|
||||
out[name] = st
|
||||
st, data = vault.request("GET", "auth/token/lookup-self", token=token)
|
||||
d = data.get("data", {})
|
||||
out["lookup_self"] = {"status": st, "policies": d.get("policies"), "ttl": d.get("ttl"),
|
||||
"explicit_max_ttl": d.get("explicit_max_ttl"), "renewable": d.get("renewable"),
|
||||
"display_name": d.get("display_name")}
|
||||
st, data = vault.request("POST", "auth/token/renew-self", token=token, body={})
|
||||
out["renew_self"] = st
|
||||
# Отзыв своего токена: следующий запрос с ним -> 403 (проверка, что отзыв действует сразу).
|
||||
vault.request("POST", "auth/token/revoke-self", token=token, body={})
|
||||
st, _ = vault.request("GET", "kv/data/messenger/%s" % ROLE, token=token)
|
||||
out["read_after_revoke"] = st
|
||||
return out, values
|
||||
|
||||
|
||||
def db_checks(values):
|
||||
if "POSTGRES_PASSWORD" not in values:
|
||||
return None
|
||||
from psycopg.conninfo import make_conninfo
|
||||
info = make_conninfo(host=os.environ.get("POSTGRES_HOST", "db"), dbname=os.environ.get("POSTGRES_DB", "messenger"),
|
||||
user=os.environ["POSTGRES_USER"], password=values["POSTGRES_PASSWORD"],
|
||||
sslmode="verify-full", sslrootcert=os.environ.get("DB_SSLROOTCERT", "/run/secrets/internal-ca.crt"),
|
||||
connect_timeout=3)
|
||||
out = {"user": os.environ["POSTGRES_USER"]}
|
||||
with psycopg.connect(info, autocommit=True) as conn:
|
||||
row = conn.execute("SELECT ssl, version, cipher FROM pg_stat_ssl WHERE pid = pg_backend_pid()").fetchone()
|
||||
out["ssl"] = {"ssl": row[0], "version": row[1], "cipher": row[2]}
|
||||
r = conn.execute("SELECT rolsuper, rolcreaterole, rolcreatedb, rolbypassrls FROM pg_roles WHERE rolname = current_user").fetchone()
|
||||
out["role_flags"] = dict(zip(("super", "createrole", "createdb", "bypassrls"), r))
|
||||
tests = {
|
||||
"select_users": "SELECT count(*) FROM users",
|
||||
"select_sessions": "SELECT count(*) FROM sessions",
|
||||
"select_messages": "SELECT count(*) FROM messages",
|
||||
"select_attachments": "SELECT count(*) FROM attachments",
|
||||
"select_jobs": "SELECT count(*) FROM jobs",
|
||||
"update_chat_title": "UPDATE chats SET title = title WHERE false",
|
||||
"delete_messages": "DELETE FROM messages WHERE false",
|
||||
"truncate_outbox": "TRUNCATE outbox",
|
||||
"create_table": "CREATE TABLE lab7_probe (x int)",
|
||||
"drop_users": "DROP TABLE users",
|
||||
}
|
||||
for name, q in tests.items():
|
||||
try:
|
||||
with conn.transaction():
|
||||
conn.execute(q)
|
||||
raise _Rollback()
|
||||
except _Rollback:
|
||||
out[name] = "allowed"
|
||||
except psycopg.Error as exc:
|
||||
out[name] = "denied" if getattr(exc, "sqlstate", "") in ("42501",) else "error:%s" % exc.sqlstate
|
||||
return out
|
||||
|
||||
|
||||
class _Rollback(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
result = {"role": ROLE, "kv_path": vault.BAO_KV_PATH}
|
||||
try:
|
||||
result["openbao"], values = bao_checks()
|
||||
except Exception as exc:
|
||||
result["openbao_error"] = type(exc).__name__
|
||||
values = {}
|
||||
try:
|
||||
result["db"] = db_checks(values)
|
||||
except Exception as exc:
|
||||
result["db_error"] = "%s: %s" % (type(exc).__name__, str(exc)[:120])
|
||||
env_names = sorted(os.environ)
|
||||
result["env_has_token"] = [n for n in env_names if n in ("BAO_TOKEN", "VAULT_TOKEN") or n.endswith("_SECRET_ID")]
|
||||
result["env_secret_like"] = [n for n in env_names if any(x in n for x in ("PASSWORD", "SECRET_ACCESS_KEY"))
|
||||
and not n.endswith("_FILE")]
|
||||
result["mounted_secrets"] = sorted(os.listdir("/run/secrets")) if os.path.isdir("/run/secrets") else []
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+1401
File diff suppressed because it is too large
Load Diff
+470
@@ -0,0 +1,470 @@
|
||||
"""Работа с PostgreSQL: пользователи, чаты, сообщения, сессии, метаданные вложений.
|
||||
|
||||
Lab5: вложение создаётся как pending (скрыто), после записи оригинала в staging одной
|
||||
транзакцией становится queued вместе с заданием и записью outbox (src/jobs.py).
|
||||
|
||||
Источник истины — база данных. В памяти процесса состояния нет, поэтому
|
||||
перезапуск API (и самой БД с сохранённым volume) не теряет данные.
|
||||
|
||||
Lab6: каждая публичная операция — CLIENT span «db <операция>» и гистограмма
|
||||
db.client.operation.duration{db.operation.name}; ожидание соединения пула — отдельная
|
||||
гистограмма db.client.connection.wait_time и атрибут span. По ним медленная/заблокированная БД
|
||||
отличается от медленного кода обработчика (spans db длинные vs короткие).
|
||||
"""
|
||||
import contextlib
|
||||
import datetime as dt
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
import jobs
|
||||
import telemetry
|
||||
from psycopg_pool import ConnectionPool
|
||||
from telemetry import db_operation
|
||||
|
||||
log = logging.getLogger("messenger.store")
|
||||
|
||||
EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)
|
||||
MIGRATIONS_LOCK_ID = 727001 # произвольный номер advisory-блокировки для миграций
|
||||
|
||||
|
||||
class Conflict(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnknownMember(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotFound(Exception):
|
||||
"""Вложение неизвестно, не принято (pending) или принадлежит другому чату -> 404."""
|
||||
|
||||
|
||||
class AttachmentFailed(Exception):
|
||||
"""Вложение в состоянии failed: прикреплять нельзя -> 409."""
|
||||
|
||||
|
||||
def format_ts(value):
|
||||
"""datetime -> RFC 3339 UTC с микросекундами и суффиксом Z."""
|
||||
return value.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def to_micros(value):
|
||||
delta = value - EPOCH
|
||||
return (delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds
|
||||
|
||||
|
||||
def from_micros(micros):
|
||||
return EPOCH + dt.timedelta(microseconds=micros)
|
||||
|
||||
|
||||
def _user(row):
|
||||
# Пароль/hash и сессионные данные никогда не входят в User.
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _chat(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(m) for m in row["member_ids"]],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _message(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
"attachment_ids": [str(a) for a in (row["attachment_ids"] or [])],
|
||||
}
|
||||
|
||||
|
||||
def _attachment(row):
|
||||
# Наружу не отдаются object_key, bucket и внутренние адреса.
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"owner_id": str(row["owner_id"]),
|
||||
"filename": row["filename"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"],
|
||||
"status": row["status"],
|
||||
# Варианты показываются только у ready (их наличие = готовность уровня).
|
||||
"variants": list(row["variants"] or []) if row["status"] == "ready" else [],
|
||||
"error_code": row["error_code"] if row["status"] == "failed" else None,
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
"updated_at": format_ts(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
ATTACHMENT_COLUMNS = """a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.status, a.error_code, a.object_key, a.created_at, a.updated_at,
|
||||
(SELECT json_agg(json_build_object('name', v.name, 'content_type', v.content_type,
|
||||
'size_bytes', v.size_bytes, 'width', v.width, 'height', v.height, 'sha256', v.sha256)
|
||||
ORDER BY array_position(ARRAY['thumbnail','crop','optimized'], v.name))
|
||||
FROM attachment_variants v
|
||||
WHERE v.attachment_id = a.id AND v.pipeline_version = a.pipeline_version) AS variants"""
|
||||
|
||||
|
||||
MESSAGE_COLUMNS = """m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
(SELECT array_agg(ma.attachment_id ORDER BY ma.position) FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id) AS attachment_ids"""
|
||||
|
||||
CHAT_COLUMNS = """c.id, c.title, c.created_at,
|
||||
(SELECT array_agg(m.user_id ORDER BY m.position) FROM chat_members m WHERE m.chat_id = c.id) AS member_ids"""
|
||||
|
||||
|
||||
class InstrumentedPool(ConnectionPool):
|
||||
"""ConnectionPool, который измеряет ожидание соединения (насыщение пула видно в метриках)."""
|
||||
|
||||
@contextlib.contextmanager
|
||||
def connection(self, timeout=None):
|
||||
started = time.perf_counter()
|
||||
outcome = {}
|
||||
try:
|
||||
conn = self.getconn(timeout=timeout)
|
||||
except Exception as exc:
|
||||
outcome["error.type"] = type(exc).__name__
|
||||
raise
|
||||
finally:
|
||||
waited = time.perf_counter() - started
|
||||
telemetry.db_wait.record(waited, dict({"db.client.connection.pool.name": "api",
|
||||
"db.system.name": telemetry.DB_SYSTEM}, **outcome))
|
||||
span = telemetry.trace.get_current_span()
|
||||
if span.is_recording():
|
||||
span.set_attribute("db.client.connection.wait_time_ms", round(waited * 1000, 3))
|
||||
try:
|
||||
with conn:
|
||||
yield conn
|
||||
finally:
|
||||
self.putconn(conn)
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, conninfo, pool_size=10, pool_timeout=3):
|
||||
# check: перед выдачей соединение проверяется. После перезапуска PostgreSQL
|
||||
# «мёртвые» соединения отбрасываются, и запрос не получает ложный 503.
|
||||
self.pool = InstrumentedPool(
|
||||
conninfo, min_size=1, max_size=pool_size, timeout=pool_timeout,
|
||||
kwargs={"row_factory": dict_row}, open=False,
|
||||
check=ConnectionPool.check_connection)
|
||||
|
||||
# --- запуск ---
|
||||
def open(self, wait_seconds=60):
|
||||
"""Ждём готовности БД (она может стартовать дольше API) и открываем пул."""
|
||||
self.pool.open()
|
||||
deadline = time.monotonic() + wait_seconds
|
||||
while True:
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return
|
||||
except Exception as exc:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
log.info("database is not ready yet (%s), retrying", type(exc).__name__)
|
||||
time.sleep(1)
|
||||
|
||||
def close(self):
|
||||
self.pool.close()
|
||||
|
||||
def migrate(self, directory):
|
||||
"""Применяет *.sql по порядку имён; каждая миграция — одна транзакция, один раз."""
|
||||
files = sorted(Path(directory).glob("*.sql"))
|
||||
with self.pool.connection() as conn:
|
||||
# Advisory-блокировка (сессионная): параллельный повторный запуск job не устроит гонку.
|
||||
conn.autocommit = True
|
||||
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATIONS_LOCK_ID,))
|
||||
try:
|
||||
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())""")
|
||||
done = {r["version"] for r in conn.execute("SELECT version FROM schema_migrations")}
|
||||
for path in files:
|
||||
if path.name in done:
|
||||
continue
|
||||
# Миграция и её отметка — одна транзакция: либо целиком, либо никак.
|
||||
with conn.transaction():
|
||||
conn.execute(path.read_text(encoding="utf-8"))
|
||||
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (path.name,))
|
||||
log.info("migration applied: %s", path.name)
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATIONS_LOCK_ID,))
|
||||
conn.autocommit = False
|
||||
|
||||
def pending_migrations(self, directory):
|
||||
"""Миграции из каталога образа, ещё не применённые к БД (API их НЕ применяет)."""
|
||||
files = sorted(p.name for p in Path(directory).glob("*.sql"))
|
||||
with self.pool.connection() as conn:
|
||||
exists = conn.execute("SELECT to_regclass('schema_migrations') IS NOT NULL AS ok").fetchone()["ok"]
|
||||
done = {r["version"] for r in conn.execute("SELECT version FROM schema_migrations")} if exists else set()
|
||||
return [f for f in files if f not in done]
|
||||
|
||||
@db_operation("ping")
|
||||
def ping(self):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
|
||||
# --- пользователи ---
|
||||
@db_operation("create_user")
|
||||
def create_user(self, username, display_name, password_hash):
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp())
|
||||
RETURNING id, username, display_name, created_at""",
|
||||
(uuid.uuid4(), username, display_name, password_hash)).fetchone()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
# Уникальность гарантирует сама БД — гонка двух регистраций безопасна.
|
||||
raise Conflict()
|
||||
return _user(row)
|
||||
|
||||
@db_operation("get_credentials")
|
||||
def get_credentials(self, username):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
|
||||
(username,)).fetchone()
|
||||
if row is None:
|
||||
return None, None
|
||||
return _user(row), row["password_hash"]
|
||||
|
||||
@db_operation("rehash_password")
|
||||
def update_password_hash(self, user_id, old_hash, new_hash):
|
||||
"""Lab7 rehash: заменяем только тот хеш, который проверяли (гонка двух входов безопасна)."""
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("UPDATE users SET password_hash = %s WHERE id = %s AND password_hash = %s",
|
||||
(new_hash, user_id, old_hash))
|
||||
|
||||
# --- сессии ---
|
||||
@db_operation("create_session")
|
||||
def create_session(self, user_id, token_hash, ttl_seconds):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""INSERT INTO sessions (token_hash, user_id, created_at, expires_at)
|
||||
VALUES (%s, %s, now(), now() + make_interval(secs => %s))
|
||||
RETURNING expires_at""",
|
||||
(token_hash, user_id, ttl_seconds)).fetchone()
|
||||
return format_ts(row["expires_at"])
|
||||
|
||||
@db_operation("get_session_user")
|
||||
def get_session_user(self, token_hash):
|
||||
"""Пользователь действующей сессии или None (неизвестна/истекла/отозвана)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""SELECT u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now()""",
|
||||
(token_hash,)).fetchone()
|
||||
return _user(row) if row else None
|
||||
|
||||
@db_operation("revoke_session")
|
||||
def revoke_session(self, token_hash):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
||||
(token_hash,))
|
||||
|
||||
# --- чаты ---
|
||||
@db_operation("create_chat")
|
||||
def create_chat(self, title, member_ids):
|
||||
"""Чат и его участники создаются в одной транзакции (атомарно)."""
|
||||
chat_id = uuid.uuid4()
|
||||
with self.pool.connection() as conn:
|
||||
found = conn.execute(
|
||||
"SELECT count(*) AS n FROM users WHERE id = ANY(%s::uuid[])", (member_ids,)).fetchone()["n"]
|
||||
if found != len(member_ids):
|
||||
raise UnknownMember()
|
||||
conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, clock_timestamp())",
|
||||
(chat_id, title))
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id, position) VALUES (%s, %s, %s)",
|
||||
[(chat_id, m, i) for i, m in enumerate(member_ids)])
|
||||
row = conn.execute("SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id = %s", (chat_id,)).fetchone()
|
||||
return _chat(row)
|
||||
|
||||
@db_operation("get_chat_for")
|
||||
def get_chat_for(self, user_id, chat_id):
|
||||
"""Чат, если пользователь — участник; иначе None (чужой и несуществующий неразличимы)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + """ FROM chats c
|
||||
WHERE c.id = %s AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)""",
|
||||
(chat_id, user_id)).fetchone()
|
||||
return _chat(row) if row else None
|
||||
|
||||
@db_operation("list_chats")
|
||||
def list_chats(self, user_id, after, limit):
|
||||
params = [user_id]
|
||||
where = ""
|
||||
if after:
|
||||
where = "AND (c.created_at, c.id) > (%s, %s::uuid)"
|
||||
params += [from_micros(after[0]), after[1]]
|
||||
params.append(limit + 1) # +1 запись: узнаём, есть ли следующая страница
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + """ FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s
|
||||
WHERE true """ + where + " ORDER BY c.created_at, c.id LIMIT %s", params).fetchall()
|
||||
return self._page(rows, limit, _chat)
|
||||
|
||||
# --- сообщения ---
|
||||
@db_operation("add_message")
|
||||
def add_message(self, user_id, chat_id, text, attachment_ids, idem_key, request_hash, idem_ttl_seconds):
|
||||
"""Идемпотентная отправка. Возвращает (message, replayed) или None, если чата нет/он чужой.
|
||||
|
||||
Всё в ОДНОЙ транзакции: проверка доступа, поиск ключа, вставка сообщения и запись
|
||||
ключа. Либо фиксируется и сообщение, и ключ, либо ничего (транзиентная ошибка
|
||||
не запоминается как результат — клиент повторит с тем же ключом).
|
||||
Конкурентные запросы с одним ключом через разные реплики сериализуются
|
||||
блокировкой строки чата (FOR UPDATE), второй после COMMIT первого видит ключ.
|
||||
PK таблицы ключей — страховка: даже без блокировки дубль не зафиксируется.
|
||||
Lab4: в той же транзакции проверяется, что все attachment_ids — ready-вложения
|
||||
ЭТОГО чата (FOR SHARE: строка не исчезнет до COMMIT), и пишутся ссылки.
|
||||
"""
|
||||
with self.pool.connection() as conn:
|
||||
# FOR UPDATE по строке чата: вставки в один чат идут по очереди, поэтому
|
||||
# created_at растёт в порядке фиксации и keyset-курсор не пропускает записи.
|
||||
allowed = conn.execute(
|
||||
"""SELECT 1 FROM chats c WHERE c.id = %s AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)
|
||||
FOR UPDATE OF c""", (chat_id, user_id)).fetchone()
|
||||
if allowed is None:
|
||||
return None
|
||||
existing = conn.execute(
|
||||
"""SELECT k.request_hash, k.expires_at > now() AS alive, """ + MESSAGE_COLUMNS + """
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = %s AND k.chat_id = %s AND k.idem_key = %s""",
|
||||
(user_id, chat_id, idem_key)).fetchone()
|
||||
if existing is not None:
|
||||
if existing["alive"]:
|
||||
if bytes(existing["request_hash"]) != request_hash:
|
||||
raise Conflict()
|
||||
return _message(existing), True
|
||||
# Ключ старше TTL (24 ч) — освобождаем его и обрабатываем как новый.
|
||||
conn.execute(
|
||||
"DELETE FROM idempotency_keys WHERE user_id = %s AND chat_id = %s AND idem_key = %s",
|
||||
(user_id, chat_id, idem_key))
|
||||
if attachment_ids:
|
||||
# Lab5: queued/processing/ready можно прикреплять; failed — 409;
|
||||
# pending (upload ещё не принят) — как неизвестное.
|
||||
found = conn.execute(
|
||||
"""SELECT id, status FROM attachments
|
||||
WHERE id = ANY(%s::uuid[]) AND chat_id = %s AND status <> 'pending'
|
||||
FOR SHARE""", (attachment_ids, chat_id)).fetchall()
|
||||
if len(found) != len(attachment_ids):
|
||||
# Чужой чат, неизвестный или непринятый id — одинаково 404.
|
||||
raise AttachmentNotFound()
|
||||
if any(r["status"] == "failed" for r in found):
|
||||
raise AttachmentFailed()
|
||||
row = conn.execute(
|
||||
"""INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp())
|
||||
RETURNING id, chat_id, sender_id, text, created_at""",
|
||||
(uuid.uuid4(), chat_id, user_id, text)).fetchone()
|
||||
if attachment_ids:
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"""INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES (%s, %s, %s)""",
|
||||
[(row["id"], a, i) for i, a in enumerate(attachment_ids)])
|
||||
row = dict(row, attachment_ids=list(attachment_ids))
|
||||
conn.execute(
|
||||
"""INSERT INTO idempotency_keys (user_id, chat_id, idem_key, request_hash, message_id, expires_at)
|
||||
VALUES (%s, %s, %s, %s, %s, now() + make_interval(secs => %s))""",
|
||||
(user_id, chat_id, idem_key, request_hash, row["id"], idem_ttl_seconds))
|
||||
return _message(row), False
|
||||
|
||||
@db_operation("list_messages")
|
||||
def list_messages(self, chat_id, after, limit):
|
||||
params = [chat_id]
|
||||
where = ""
|
||||
if after:
|
||||
where = "AND (m.created_at, m.id) > (%s, %s::uuid)"
|
||||
params += [from_micros(after[0]), after[1]]
|
||||
params.append(limit + 1)
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT " + MESSAGE_COLUMNS + " FROM messages m WHERE m.chat_id = %s "
|
||||
+ where + " ORDER BY m.created_at, m.id LIMIT %s", params).fetchall()
|
||||
return self._page(rows, limit, _message)
|
||||
|
||||
# --- вложения ---
|
||||
@db_operation("create_pending_attachment")
|
||||
def create_pending_attachment(self, att_id, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, width, height, object_key, staging_key, pipeline_version):
|
||||
"""Шаг 1: намерение фиксируется ДО PUT в staging (как в lab4). Строка pending
|
||||
API не показывает; брошенную (крах до постановки в очередь) убирает janitor."""
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, width, height, object_key, staging_key, pipeline_version, status, created_at, updated_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'pending', now(), now())""",
|
||||
(att_id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
width, height, object_key, staging_key, pipeline_version))
|
||||
|
||||
@db_operation("enqueue_attachment")
|
||||
def enqueue_attachment(self, att_id, pipeline_version, max_attempts, before_commit=None):
|
||||
"""Шаг 3 (после PUT в staging): ОДНА транзакция pending -> queued + jobs + outbox.
|
||||
После COMMIT работа принята: даже если API сразу упадёт, relay опубликует задание.
|
||||
None — строку уже убрал janitor (ответ 503)."""
|
||||
with self.pool.connection() as conn:
|
||||
job_id = jobs.enqueue(conn, att_id, pipeline_version, max_attempts)
|
||||
if job_id is None:
|
||||
return None
|
||||
if before_commit:
|
||||
before_commit()
|
||||
row = conn.execute("SELECT " + ATTACHMENT_COLUMNS + " FROM attachments a WHERE a.id = %s",
|
||||
(att_id,)).fetchone()
|
||||
return _attachment(row)
|
||||
|
||||
@db_operation("delete_pending_attachment")
|
||||
def delete_pending_attachment(self, att_id):
|
||||
"""Компенсация: убрать непринятое намерение (staging-объект удалён/не создан)."""
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("DELETE FROM attachments WHERE id = %s AND status = 'pending'", (att_id,))
|
||||
|
||||
@db_operation("get_attachment_for")
|
||||
def get_attachment_for(self, user_id, att_id):
|
||||
"""(attachment, object_key) для участника чата; иначе None. Pending не виден."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT " + ATTACHMENT_COLUMNS + """ FROM attachments a
|
||||
WHERE a.id = %s AND a.status <> 'pending' AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = %s)""",
|
||||
(att_id, user_id)).fetchone()
|
||||
return (_attachment(row), row["object_key"]) if row else None
|
||||
|
||||
@db_operation("get_variant_key")
|
||||
def get_variant_key(self, att_id, name):
|
||||
"""object_key варианта текущей версии pipeline (или None)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""SELECT v.object_key FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id
|
||||
WHERE v.attachment_id = %s AND v.name = %s AND v.pipeline_version = a.pipeline_version""",
|
||||
(att_id, name)).fetchone()
|
||||
return row["object_key"] if row else None
|
||||
|
||||
@staticmethod
|
||||
def _page(rows, limit, convert):
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
last = (to_micros(rows[-1]["created_at"]), str(rows[-1]["id"])) if rows and has_more else None
|
||||
return [convert(r) for r in rows], last
|
||||
@@ -0,0 +1,492 @@
|
||||
"""Lab6: наблюдаемость всех процессов (API, relay, worker, janitor) через OpenTelemetry SDK.
|
||||
|
||||
Три сигнала уходят по OTLP/HTTP (protobuf) в OTel Collector (OTEL_EXPORTER_OTLP_ENDPOINT):
|
||||
traces -> BatchSpanProcessor (ограниченная очередь, сброс раз в 1 с) -> Collector -> Tempo
|
||||
metrics -> PeriodicExportingMetricReader (раз в OTEL_METRIC_EXPORT_INTERVAL) -> Collector -> Prometheus
|
||||
logs -> logging.Handler -> BatchLogRecordProcessor -> Collector -> Loki
|
||||
и параллельно — структурный JSON в stdout (`docker compose logs`), с trace_id/span_id.
|
||||
|
||||
Принципы:
|
||||
* телеметрия никогда не ломает бизнес-путь: все очереди SDK ограничены (max_queue_size),
|
||||
экспорт — с таймаутом в фоновых потоках; недоступный Collector = потерянная телеметрия,
|
||||
а не ошибка запроса. Потери считает сам SDK: otel.sdk.processor.*.processed{error.type}
|
||||
и otel.sdk.exporter.*.exported{error.type} (meter_provider передаётся процессорам/экспортёрам);
|
||||
* в атрибуты МЕТРИК идут только низкокардинальные значения (метод, шаблон маршрута, класс
|
||||
статуса, тип/исход задания, имя операции). ID пользователей/чатов/сообщений/вложений,
|
||||
request_id, raw URL, filename и тексты — никогда;
|
||||
* в трассы/логи допускаются технические ID синтетических учебных данных (job_id,
|
||||
attachment_id, request_id) — по ним upload связывается с заданием. Пароли, Authorization,
|
||||
токены, тела сообщений, байты изображений, URL с паролями — запрещены (см. redact());
|
||||
* OTEL_SDK_DISABLED=true выключает экспорт полностью (no-op провайдеры), stdout-логи остаются.
|
||||
|
||||
Resource: service.name (messenger-api | -worker | -relay | -janitor), service.version
|
||||
(= APP_VERSION образа), service.instance.id (= hostname контейнера = X-Instance-Id),
|
||||
deployment.environment.name (из OTEL_RESOURCE_ATTRIBUTES, по умолчанию lab).
|
||||
"""
|
||||
import contextlib
|
||||
import datetime as dt
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from opentelemetry import metrics, propagate, trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
SERVICE_NAME = os.environ.get("OTEL_SERVICE_NAME", "messenger-app")
|
||||
SERVICE_VERSION = os.environ.get("APP_VERSION", "dev")
|
||||
from instance import INSTANCE_ID # lab7: случайный alias, не hostname
|
||||
ENABLED = os.environ.get("OTEL_SDK_DISABLED", "false").strip().lower() != "true"
|
||||
|
||||
tracer = trace.get_tracer("messenger", SERVICE_VERSION)
|
||||
meter = metrics.get_meter("messenger", SERVICE_VERSION)
|
||||
|
||||
_setup_done = False
|
||||
_setup_lock = threading.Lock()
|
||||
_providers = []
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Гистограммы: границы под ожидаемые задержки (секунды). p50/p95/p99 считаются в Prometheus
|
||||
# из buckets (histogram_quantile), а не из средних.
|
||||
# --------------------------------------------------------------------------
|
||||
# 3.5 и 5.5 с — рядом с PoolTimeout (3 с) и statement_timeout (5 с): без них ответы по таймауту
|
||||
# попадали в (5, 10] и p95 линейной интерполяцией показывал ~9.75 с вместо ~5 с.
|
||||
HTTP_BUCKETS = (0.002, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.25, 0.35, 0.5, 0.75, 1.0,
|
||||
1.5, 2.5, 3.5, 5.0, 5.5, 7.5, 10.0, 30.0, 60.0)
|
||||
DB_BUCKETS = (0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 3.5, 5.0, 5.5,
|
||||
7.5, 10.0)
|
||||
JOB_BUCKETS = (0.05, 0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 20.0, 30.0, 60.0, 120.0)
|
||||
READY_BUCKETS = (0.25, 0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 20.0, 30.0, 60.0, 120.0, 300.0,
|
||||
600.0, 1800.0, 3600.0)
|
||||
|
||||
|
||||
def _env_float(name, default):
|
||||
try:
|
||||
return float(os.environ.get(name, str(default)))
|
||||
except ValueError:
|
||||
return float(default)
|
||||
|
||||
|
||||
def _env_int(name, default):
|
||||
try:
|
||||
return int(os.environ.get(name, str(default)))
|
||||
except ValueError:
|
||||
return int(default)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Защита от утечек в логах (defense in depth: код и так не логирует секреты/тела).
|
||||
# --------------------------------------------------------------------------
|
||||
_REDACT = [
|
||||
(re.compile(r"(?i)\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{6,}"), r"\1 [REDACTED]"),
|
||||
(re.compile(r"(?i)(authorization\s*[:=]\s*)\S+"), r"\1[REDACTED]"),
|
||||
(re.compile(r"([a-z][a-z0-9+.-]*://)[^/\s:@]+:[^@\s/]+@"), r"\1[REDACTED]@"),
|
||||
(re.compile(r"(?i)(password|passwd|secret|token)(\"?\s*[:=]\s*\"?)[^\s\",}]+"), r"\1\2[REDACTED]"),
|
||||
(re.compile(r"(?i)(X-Amz-Signature|X-Amz-Credential|Signature)=[^&\s]+"), r"\1=[REDACTED]"),
|
||||
]
|
||||
|
||||
|
||||
def redact(text):
|
||||
if not isinstance(text, str):
|
||||
return text
|
||||
for pattern, repl in _REDACT:
|
||||
text = pattern.sub(repl, text)
|
||||
return text
|
||||
|
||||
|
||||
_STD_ATTRS = set(vars(logging.LogRecord("", 0, "", 0, "", None, None))) | {"message", "asctime", "taskName"}
|
||||
|
||||
|
||||
class EventFilter(logging.Filter):
|
||||
"""У каждой записи есть поле event (стабильное имя события) и отредактированный текст."""
|
||||
|
||||
def filter(self, record):
|
||||
if not getattr(record, "event", None):
|
||||
record.event = "log"
|
||||
if record.args:
|
||||
try:
|
||||
record.msg = record.getMessage()
|
||||
record.args = None
|
||||
except Exception:
|
||||
pass
|
||||
record.msg = redact(record.msg)
|
||||
return True
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
"""Структурный лог в stdout: timestamp, severity, service.name, event, trace_id, span_id."""
|
||||
|
||||
def format(self, record):
|
||||
out = {
|
||||
"timestamp": dt.datetime.fromtimestamp(record.created, dt.timezone.utc).isoformat(timespec="milliseconds"),
|
||||
"severity": record.levelname,
|
||||
"service.name": SERVICE_NAME,
|
||||
"service.instance.id": INSTANCE_ID,
|
||||
"logger": record.name,
|
||||
"event": getattr(record, "event", "log"),
|
||||
"message": record.getMessage(),
|
||||
}
|
||||
ctx = trace.get_current_span().get_span_context()
|
||||
if ctx.is_valid:
|
||||
out["trace_id"] = format(ctx.trace_id, "032x")
|
||||
out["span_id"] = format(ctx.span_id, "016x")
|
||||
for key, value in vars(record).items():
|
||||
if key not in _STD_ATTRS and key not in out and not key.startswith("_") and key != "event":
|
||||
out[key] = value if isinstance(value, (int, float, bool)) or value is None else redact(str(value))
|
||||
if record.exc_info:
|
||||
out["exception.type"] = record.exc_info[0].__name__ if record.exc_info[0] else None
|
||||
out["exception.stacktrace"] = redact(self.formatException(record.exc_info))
|
||||
return json.dumps(out, ensure_ascii=False)
|
||||
|
||||
|
||||
class _NotOtelInternals(logging.Filter):
|
||||
"""Логи самого SDK/экспортёра не отправляем через тот же экспортёр (иначе при недоступном
|
||||
Collector каждая ошибка экспорта порождала бы новую запись в очереди экспорта)."""
|
||||
|
||||
def filter(self, record):
|
||||
return not (record.name.startswith("opentelemetry") or record.name.startswith("urllib3.connectionpool"))
|
||||
|
||||
|
||||
def configure_logging(stream=None):
|
||||
root = logging.getLogger()
|
||||
for h in list(root.handlers):
|
||||
root.removeHandler(h)
|
||||
handler = logging.StreamHandler(stream or sys.stdout)
|
||||
handler.setFormatter(JsonFormatter())
|
||||
handler.addFilter(EventFilter())
|
||||
root.addHandler(handler)
|
||||
root.setLevel(logging.INFO)
|
||||
logging.getLogger("pika").setLevel(logging.WARNING)
|
||||
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
||||
return handler
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Настройка SDK
|
||||
# --------------------------------------------------------------------------
|
||||
def setup(service_name=None):
|
||||
"""Идемпотентно: логирование (stdout JSON), затем — если не выключено — провайдеры OTel."""
|
||||
global _setup_done, SERVICE_NAME
|
||||
with _setup_lock:
|
||||
if _setup_done:
|
||||
return
|
||||
_setup_done = True
|
||||
if service_name and not os.environ.get("OTEL_SERVICE_NAME"):
|
||||
SERVICE_NAME = service_name
|
||||
configure_logging()
|
||||
if not ENABLED:
|
||||
logging.getLogger("telemetry").info("OpenTelemetry export disabled (OTEL_SDK_DISABLED=true)",
|
||||
extra={"event": "telemetry.disabled"})
|
||||
return
|
||||
_setup_sdk()
|
||||
|
||||
|
||||
def _setup_sdk():
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import Histogram, MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
|
||||
# Resource.create() добавляет OTEL_RESOURCE_ATTRIBUTES (deployment.environment.name=lab)
|
||||
# и атрибуты telemetry.sdk.*; явные значения ниже важнее.
|
||||
resource = Resource.create({
|
||||
"service.name": SERVICE_NAME,
|
||||
"service.version": SERVICE_VERSION,
|
||||
"service.instance.id": INSTANCE_ID,
|
||||
})
|
||||
if "deployment.environment.name" not in resource.attributes:
|
||||
resource = resource.merge(Resource({"deployment.environment.name": os.environ.get("APP_ENV", "lab")}))
|
||||
timeout = _env_float("OTEL_EXPORTER_OTLP_TIMEOUT_SECONDS", 5)
|
||||
|
||||
def views():
|
||||
out = []
|
||||
for name, buckets in (("http.server.request.duration", HTTP_BUCKETS),
|
||||
("db.client.operation.duration", DB_BUCKETS),
|
||||
("db.client.connection.wait_time", DB_BUCKETS),
|
||||
("messenger.s3.operation.duration", DB_BUCKETS),
|
||||
("messenger.job.duration", JOB_BUCKETS),
|
||||
("messenger.job.queue_wait", READY_BUCKETS),
|
||||
("messenger.attachment.time_to_ready", READY_BUCKETS),
|
||||
("messenger.outbox.publish_delay", READY_BUCKETS)):
|
||||
out.append(View(instrument_type=Histogram, instrument_name=name,
|
||||
aggregation=ExplicitBucketHistogramAggregation(buckets)))
|
||||
return out
|
||||
|
||||
# 1) Метрики первыми: их meter_provider получают процессоры/экспортёры других сигналов
|
||||
# и считают собственные потери (queue_full, ошибки экспорта).
|
||||
metric_exporter = OTLPMetricExporter(timeout=timeout)
|
||||
reader = PeriodicExportingMetricReader(
|
||||
metric_exporter,
|
||||
export_interval_millis=_env_int("OTEL_METRIC_EXPORT_INTERVAL", 10000),
|
||||
export_timeout_millis=_env_int("OTEL_METRIC_EXPORT_TIMEOUT", 5000))
|
||||
meter_provider = MeterProvider(resource=resource, metric_readers=[reader], views=views())
|
||||
metrics.set_meter_provider(meter_provider)
|
||||
|
||||
# 2) Трассы. Сэмплер по умолчанию parentbased_always_on; меняется OTEL_TRACES_SAMPLER(_ARG).
|
||||
tracer_provider = TracerProvider(resource=resource)
|
||||
tracer_provider.add_span_processor(BatchSpanProcessor(
|
||||
OTLPSpanExporter(timeout=timeout, meter_provider=meter_provider),
|
||||
max_queue_size=_env_int("OTEL_BSP_MAX_QUEUE_SIZE", 2048),
|
||||
schedule_delay_millis=_env_int("OTEL_BSP_SCHEDULE_DELAY", 1000),
|
||||
max_export_batch_size=_env_int("OTEL_BSP_MAX_EXPORT_BATCH_SIZE", 512),
|
||||
export_timeout_millis=_env_int("OTEL_BSP_EXPORT_TIMEOUT", 5000),
|
||||
meter_provider=meter_provider))
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
|
||||
# 3) Логи: тот же формат событий (event, request_id, ...) как атрибуты записи; trace_id/span_id
|
||||
# берутся из текущего контекста автоматически.
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
logger_provider.add_log_record_processor(BatchLogRecordProcessor(
|
||||
OTLPLogExporter(timeout=timeout, meter_provider=meter_provider),
|
||||
max_queue_size=_env_int("OTEL_BLRP_MAX_QUEUE_SIZE", 2048),
|
||||
schedule_delay_millis=_env_int("OTEL_BLRP_SCHEDULE_DELAY", 1000),
|
||||
max_export_batch_size=_env_int("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE", 512),
|
||||
export_timeout_millis=_env_int("OTEL_BLRP_EXPORT_TIMEOUT", 5000),
|
||||
meter_provider=meter_provider))
|
||||
set_logger_provider(logger_provider)
|
||||
otel_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||
otel_handler.addFilter(EventFilter())
|
||||
otel_handler.addFilter(_NotOtelInternals())
|
||||
logging.getLogger().addHandler(otel_handler)
|
||||
|
||||
_providers.extend([tracer_provider, logger_provider, meter_provider])
|
||||
_register_resource_gauges()
|
||||
logging.getLogger("telemetry").info(
|
||||
"OpenTelemetry enabled endpoint=%s protocol=%s", os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "-"),
|
||||
os.environ.get("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf"), extra={"event": "telemetry.enabled"})
|
||||
|
||||
|
||||
def shutdown(timeout_millis=3000):
|
||||
"""Сбросить буферы при штатной остановке. Общий срок timeout_millis на ВСЕ провайдеры:
|
||||
при недоступном Collector экспортёр повторяет попытки, и без срока остановка API
|
||||
затянулась бы дольше stop_grace_period (замер: ~14 с без ограничения)."""
|
||||
providers = list(_providers)
|
||||
_providers.clear()
|
||||
threads = []
|
||||
for p in providers:
|
||||
t = threading.Thread(target=_quiet_shutdown, args=(p,), daemon=True)
|
||||
t.start()
|
||||
threads.append(t)
|
||||
deadline = time.monotonic() + timeout_millis / 1000.0
|
||||
for t in threads:
|
||||
t.join(max(0.0, deadline - time.monotonic()))
|
||||
|
||||
|
||||
def _quiet_shutdown(provider):
|
||||
try:
|
||||
provider.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Ресурсы контейнера/процесса (cgroup v2 своего контейнера, /proc/self): saturation CPU/RAM.
|
||||
# Включают подпроцессы (проба JPEG в API, transform в worker).
|
||||
# --------------------------------------------------------------------------
|
||||
def _read(path):
|
||||
try:
|
||||
with open(path, encoding="ascii") as f:
|
||||
return f.read().strip()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _cgroup_cpu_seconds():
|
||||
raw = _read("/sys/fs/cgroup/cpu.stat")
|
||||
if not raw:
|
||||
return None
|
||||
for line in raw.splitlines():
|
||||
k, _, v = line.partition(" ")
|
||||
if k == "usage_usec":
|
||||
return int(v) / 1e6
|
||||
return None
|
||||
|
||||
|
||||
def _cgroup_cpu_limit():
|
||||
raw = _read("/sys/fs/cgroup/cpu.max")
|
||||
if not raw:
|
||||
return None
|
||||
quota, _, period = raw.partition(" ")
|
||||
if quota == "max":
|
||||
return float(os.cpu_count() or 1)
|
||||
return int(quota) / int(period or 100000)
|
||||
|
||||
|
||||
def _process_rss_bytes():
|
||||
raw = _read("/proc/self/status")
|
||||
if raw:
|
||||
for line in raw.splitlines():
|
||||
if line.startswith("VmRSS:"):
|
||||
return int(line.split()[1]) * 1024
|
||||
return None
|
||||
|
||||
|
||||
def _register_resource_gauges():
|
||||
def cpu_time(options):
|
||||
v = _cgroup_cpu_seconds()
|
||||
if v is not None:
|
||||
yield metrics.Observation(v)
|
||||
|
||||
def mem_usage(options):
|
||||
v = _read("/sys/fs/cgroup/memory.current")
|
||||
if v and v.isdigit():
|
||||
yield metrics.Observation(int(v))
|
||||
|
||||
def mem_limit(options):
|
||||
v = _read("/sys/fs/cgroup/memory.max")
|
||||
if v and v.isdigit():
|
||||
yield metrics.Observation(int(v))
|
||||
|
||||
def cpu_limit(options):
|
||||
v = _cgroup_cpu_limit()
|
||||
if v is not None:
|
||||
yield metrics.Observation(v)
|
||||
|
||||
def rss(options):
|
||||
v = _process_rss_bytes()
|
||||
if v is not None:
|
||||
yield metrics.Observation(v)
|
||||
|
||||
def threads(options):
|
||||
yield metrics.Observation(threading.active_count())
|
||||
|
||||
meter.create_observable_counter("container.cpu.time", [cpu_time], unit="s",
|
||||
description="CPU time of this container (cgroup v2 cpu.stat usage_usec)")
|
||||
meter.create_observable_gauge("container.memory.usage", [mem_usage], unit="By",
|
||||
description="Memory of this container (cgroup v2 memory.current)")
|
||||
meter.create_observable_gauge("container.memory.limit", [mem_limit], unit="By",
|
||||
description="Memory limit of this container (cgroup v2 memory.max)")
|
||||
meter.create_observable_gauge("container.cpu.limit", [cpu_limit], unit="{cpu}",
|
||||
description="CPU quota of this container in cores (cgroup v2 cpu.max)")
|
||||
meter.create_observable_gauge("process.memory.usage", [rss], unit="By",
|
||||
description="Resident memory of the main process (VmRSS)")
|
||||
meter.create_observable_gauge("process.thread.count", [threads], unit="{thread}",
|
||||
description="Python threads of the main process")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Общие инструменты
|
||||
# --------------------------------------------------------------------------
|
||||
DB_SYSTEM = "postgresql"
|
||||
DB_NAMESPACE = os.environ.get("POSTGRES_DB", "messenger")
|
||||
|
||||
db_duration = meter.create_histogram(
|
||||
"db.client.operation.duration", unit="s",
|
||||
description="Duration of a logical database operation (pool wait included)")
|
||||
db_wait = meter.create_histogram(
|
||||
"db.client.connection.wait_time", unit="s",
|
||||
description="Time spent waiting for a connection from the pool")
|
||||
s3_duration = meter.create_histogram(
|
||||
"messenger.s3.operation.duration", unit="s", description="Duration of an S3 request")
|
||||
|
||||
|
||||
def current_trace_ids():
|
||||
ctx = trace.get_current_span().get_span_context()
|
||||
if not ctx.is_valid:
|
||||
return None, None
|
||||
return format(ctx.trace_id, "032x"), format(ctx.span_id, "016x")
|
||||
|
||||
|
||||
def has_active_span():
|
||||
return trace.get_current_span().get_span_context().is_valid
|
||||
|
||||
|
||||
def error_type_of(exc):
|
||||
return type(exc).__name__
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def child_span(name, kind=SpanKind.INTERNAL, attributes=None, root=False):
|
||||
"""Span только внутри уже начатой трассы (запрос/задание). Фоновые циклы (health-пинги,
|
||||
heartbeat аренды, опрос outbox) без родителя трасс не порождают — только метрики."""
|
||||
if not root and not has_active_span():
|
||||
yield None
|
||||
return
|
||||
with tracer.start_as_current_span(name, kind=kind, attributes=attributes or {},
|
||||
record_exception=False, set_status_on_exception=False) as span:
|
||||
try:
|
||||
yield span
|
||||
except BaseException as exc:
|
||||
span.set_attribute("error.type", error_type_of(exc))
|
||||
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
raise
|
||||
|
||||
|
||||
def db_operation(op):
|
||||
"""Декоратор логической операции БД: CLIENT span «db <op>» (если есть родитель) и
|
||||
гистограмма db.client.operation.duration{db.operation.name, error.type}."""
|
||||
def wrap(func):
|
||||
@functools.wraps(func)
|
||||
def inner(*args, **kwargs):
|
||||
started = time.perf_counter()
|
||||
attrs = {"db.system.name": DB_SYSTEM, "db.operation.name": op}
|
||||
err = None
|
||||
try:
|
||||
with child_span("db " + op, SpanKind.CLIENT,
|
||||
dict(attrs, **{"db.namespace": DB_NAMESPACE, "server.address": "db"})):
|
||||
return func(*args, **kwargs)
|
||||
except BaseException as exc:
|
||||
err = error_type_of(exc)
|
||||
raise
|
||||
finally:
|
||||
if err:
|
||||
attrs["error.type"] = err
|
||||
db_duration.record(time.perf_counter() - started, attrs)
|
||||
return inner
|
||||
return wrap
|
||||
|
||||
|
||||
def observe_pool(pool, pool_name):
|
||||
"""Наблюдаемые метрики пула psycopg_pool (semantic conventions db.client.connection.*)."""
|
||||
base = {"db.client.connection.pool.name": pool_name, "db.system.name": DB_SYSTEM}
|
||||
|
||||
def count(options):
|
||||
s = pool.get_stats()
|
||||
size, available = s.get("pool_size", 0), s.get("pool_available", 0)
|
||||
yield metrics.Observation(max(0, size - available), dict(base, **{"db.client.connection.state": "used"}))
|
||||
yield metrics.Observation(available, dict(base, **{"db.client.connection.state": "idle"}))
|
||||
|
||||
def maximum(options):
|
||||
yield metrics.Observation(pool.get_stats().get("pool_max", 0), base)
|
||||
|
||||
def pending(options):
|
||||
yield metrics.Observation(pool.get_stats().get("requests_waiting", 0), base)
|
||||
|
||||
def timeouts(options):
|
||||
yield metrics.Observation(pool.get_stats().get("requests_errors", 0), base)
|
||||
|
||||
meter.create_observable_up_down_counter("db.client.connection.count", [count], unit="{connection}",
|
||||
description="Connections in the pool by state (used/idle)")
|
||||
meter.create_observable_up_down_counter("db.client.connection.max", [maximum], unit="{connection}",
|
||||
description="Pool max size")
|
||||
meter.create_observable_up_down_counter("db.client.connection.pending_requests", [pending],
|
||||
unit="{request}", description="Requests waiting for a connection")
|
||||
meter.create_observable_counter("db.client.connection.timeouts", [timeouts], unit="{timeout}",
|
||||
description="Pool requests that failed (timeout waiting for a connection)")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# W3C Trace Context: перенос через outbox/AMQP
|
||||
# --------------------------------------------------------------------------
|
||||
def inject_dict():
|
||||
"""{'traceparent': ..., 'tracestate': ...} текущего контекста (пусто, если span нет)."""
|
||||
carrier = {}
|
||||
propagate.inject(carrier)
|
||||
return {k: v for k, v in carrier.items() if k in ("traceparent", "tracestate") and v}
|
||||
|
||||
|
||||
def extract(carrier):
|
||||
return propagate.extract(carrier or {})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user