ЛР 7 — БВТ2302 — Боданюк — на 3 #66

Open
wfa wants to merge 16 commits from wfa/mtusi2026lab7:solution/bvt2302-bodanyuk into main
143 changed files with 22059 additions and 44 deletions
+5
View File
@@ -0,0 +1,5 @@
# LF everywhere: identical files on Windows/Linux and inside `git archive | docker build -`.
* text=auto eol=lf
*.png binary
# cmd.exe expects CRLF in batch files.
*.cmd text eol=crlf
+41
View File
@@ -0,0 +1,41 @@
name: Application (lab7)
on: [push, pull_request]
permissions:
contents: read
jobs:
app:
runs-on: ubuntu-latest
timeout-minutes: 75
env:
PYTHONUTF8: "1"
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.13'
- name: Test/tooling dependencies (cryptography for the local PKI)
run: |
python -m pip install --require-hashes --no-deps -r requirements.txt
python -m pip install -r requirements-test.txt
- name: Synthetic secrets + PKI (CI only, never committed; operator dir outside the checkout)
run: python scripts/init_secrets.py
- name: OpenBao (sealed) -> operator init/unseal/configure -> whole stand over TLS/mTLS
run: make up PYTHON=python
- name: Contract and public smoke over HTTPS (public CA)
run: make check test test-security PYTHON=python CA_FILE="$PWD/secrets/pki/public-ca.crt"
- name: Persistence across restart of every process incl. OpenBao (unsealed by the hook)
run: make test-persistence ACTION_SCRIPT=scripts/restart.sh PYTHON=python CA_FILE="$PWD/secrets/pki/public-ca.crt"
- name: Failover of the replica that served the test, then restore it
run: |
make test-failover ACTION_SCRIPT=scripts/stop-one.sh PYTHON=python CA_FILE="$PWD/secrets/pki/public-ca.crt"
sh scripts/restore-api.sh && python scripts/lbctl.py wait-up 2
- name: Lab 7 defense steps 3-4 - mTLS LB->API and OpenBao allow/deny
run: make mtls-check bao-check PYTHON=python
- name: Own tests (unit + stand; every failure is restored in finally)
run: make student-test PYTHON=python
- name: Logs
if: always()
run: docker compose logs --tail 100 api lb s3 s3-init broker relay worker openbao otel-collector prometheus loki tempo grafana
- name: Remove CI stand and its synthetic data
if: always()
run: docker compose down -v
+67
View File
@@ -0,0 +1,67 @@
# syntax=docker/dockerfile:1
# Messenger, lab 5 (API replicas behind HAProxy, PostgreSQL + Valkey + S3 + RabbitMQ). Built by
# compose.yaml (services api, migrate, s3-init, relay, worker, auditor, jobctl: one image, different
# commands; only the worker imports Pillow).
#
# Python is interpreted, so there is no separate compile stage; the image
# contains only the interpreter, locked dependencies and the source code.
# Base image is pinned by version AND digest (python 3.13.16, Debian 12 bookworm).
FROM python:3.13.16-slim-bookworm@sha256:a1165e272e578941b84abc79e4ab38a0305cd12803a5c4247979ac7655f4d641
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /app
# 1. Dependencies first (layer cache survives source edits). Every package,
# including transitive ones, is pinned with sha256 hashes in requirements.txt;
# --no-deps guarantees nothing outside the lock file is installed.
COPY requirements.txt ./
RUN pip install --root-user-action=ignore --require-hashes --no-deps -r requirements.txt
# 2. JPEG integrity check: libjpeg-turbo's djpeg (strict mode, see src/messenger/images.py).
# Version pinned to the Debian 12 package; apt lists are removed in the same layer.
RUN apt-get update \
&& apt-get install -y --no-install-recommends libjpeg-turbo-progs=1:2.1.5-2 \
&& rm -rf /var/lib/apt/lists/*
# 3. Unprivileged runtime user. Code stays owned by root, so the process
# cannot modify its own code.
RUN groupadd --system --gid 10001 app \
&& useradd --system --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
COPY src/ ./src/
# Versioned SQL migrations, applied by `python -m messenger.migrate` (compose service migrate).
COPY migrations/ ./migrations/
# Course contract, served read-only at /openapi.json for Swagger UI (/docs).
COPY contracts/openapi.json ./contracts/openapi.json
# Non-secret defaults; compose.yaml passes the rest. Passwords come only as files
# (DATABASE_URL_FILE / CACHE_URL_FILE -> Docker secrets), never as ENV or COPY.
ENV PYTHONPATH=/app/src \
APP_HOST=0.0.0.0 \
APP_PORT=8080 \
APP_ENV=lab \
LOG_LEVEL=info \
SHUTDOWN_TIMEOUT_SECONDS=8 \
DOCS_ENABLED=true \
SESSION_TTL_SECONDS=3600 \
DATABASE_URL_FILE=/run/secrets/database_url
# Build revision (scripts/rolling-update.sh passes git commit + time): makes every rolled-out
# image distinguishable in `docker inspect` and in the "starting" log line of each replica.
ARG BUILD_REVISION=dev
LABEL org.opencontainers.image.revision=$BUILD_REVISION
ENV APP_REVISION=$BUILD_REVISION
USER app:app
EXPOSE 8080
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD ["python", "-m", "messenger.healthcheck"]
# Exec form: the Python server is PID 1 and receives SIGTERM directly (no shell in between).
CMD ["python", "-m", "messenger"]
+115
View File
@@ -31,3 +31,118 @@ test-failover:
test-security: test-security:
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
# ---------------------------------------------------------------------------
# Student solution (lab 7, Python). On Windows: Git Bash `sh` in PATH (C:\Program Files\Git\usr\bin),
# PYTHONUTF8=1, PYTHON=.venv/Scripts/python; the hooks are started through scripts/*.cmd.
# Full first start from a clean clone (docs/OPERATOR.md): make secrets && make up
CA ?= secrets/pki/public-ca.crt
.PHONY: secrets up bao-bootstrap bao-unseal bao-status down logs ps migrate lb-status restore rolling-update worker-stop worker-start jobs failed audit student-test unit-test security-test mtls-check bao-check argon2-bench explain grafana alerts trace-demo dashboard dashboard-check obs-test
# Local synthetic credentials + PKI (two CAs, service certificates) into ./secrets (git-ignored).
secrets:
$(PYTHON) scripts/init_secrets.py
# OpenBao first (it starts sealed), operator init/unseal/configuration, then the whole stand.
up:
docker compose up -d openbao
$(PYTHON) scripts/bao_operator.py bootstrap
docker compose up -d --build --wait
bao-bootstrap:
$(PYTHON) scripts/bao_operator.py bootstrap
# After every restart of OpenBao (it comes back sealed).
bao-unseal:
$(PYTHON) scripts/bao_operator.py unseal
bao-status:
$(PYTHON) scripts/bao_operator.py status
# Safe stop: containers stop, named volumes (data, queue, secrets storage) stay.
down:
docker compose down
logs:
docker compose logs --tail 50 api lb relay worker openbao
ps:
docker compose ps -a
migrate:
docker compose run --rm migrate
# HAProxy view of the replicas (UP/DOWN) mapped to containers and X-Instance-Id aliases.
lb-status:
$(PYTHON) scripts/lbctl.py status
$(PYTHON) scripts/lbctl.py replicas
# Start replicas stopped by scripts/stop-one.sh again and wait until the LB has them all UP.
restore:
sh scripts/restore-api.sh
$(PYTHON) scripts/lbctl.py wait-up $${API_REPLICAS:-2}
# Replace every API replica one by one with a freshly built image (no downtime).
rolling-update:
sh scripts/rolling-update.sh
worker-stop:
docker compose stop worker
worker-start:
docker compose start worker
jobs:
docker compose run --rm --no-deps jobctl stats
failed:
docker compose run --rm --no-deps jobctl list-failed
audit:
docker compose run --rm --no-deps auditor
# Own tests: unit + black-box against the running stand (needs requirements*.txt in a venv).
student-test:
$(PYTHON) -m pytest student-tests -v
unit-test:
$(PYTHON) -m pytest student-tests -m "not stack" -q
# Lab 7: the trust matrix proofs only (TLS, mTLS, roles/ACL, OpenBao, rate limit, hardening).
security-test:
$(PYTHON) -m pytest student-tests/test_security.py -v
# Lab 7 defense step 3: LB -> API mTLS (no cert / foreign CA / wrong identity / lb).
mtls-check:
sh scripts/mtls_check.sh
# Lab 7 defense step 4: OpenBao allow/deny for api/relay/worker + no root credential in the apps.
bao-check:
sh scripts/bao_check.sh
# Lab 7: Argon2id parameter measurement inside an API replica (its CPU/RAM limits).
argon2-bench:
docker compose exec -T api python - < bench/argon2_bench.py > evidence/argon2/bench.json
explain:
$(PYTHON) scripts/explain_history.py --output evidence/explain-history.txt
# Lab 6: observability (docs/OBSERVABILITY.md, docs/SLO.md, docs/RUNBOOK.md)
grafana:
@echo "Grafana: https://localhost:3000 (CA $(CA)), user admin, password in secrets/grafana_admin_password"
alerts:
$(PYTHON) scripts/obs.py alerts
# Controlled request with our own traceparent -> its trace in Tempo + its logs in Loki.
trace-demo:
$(PYTHON) scripts/trace_demo.py --output evidence/trace-demo.txt
dashboard:
$(PYTHON) scripts/build_dashboard.py
dashboard-check:
$(PYTHON) scripts/check_dashboard.py --output evidence/dashboard-check.txt
obs-test:
$(PYTHON) -m pytest student-tests/test_observability.py -v
+232 -15
View File
@@ -1,37 +1,254 @@
# Отчёт — лабораторная 7 # Отчёт — лабораторная 7
- Автор, группа: TODO - Автор, группа: Боданюк Алексей, БВТ2302
- Целевая оценка; выбранный трек 5, если нужен: TODO - Целевая оценка; выбранный трек 5: **3** (трек не заявлен)
- Commit/PR: TODO после публикации - Commit/PR: ветка `solution/bvt2302-bodanyuk`; PR «ЛР 7 — БВТ2302 — Боданюк — на 3» (ссылка после публикации)
- Использованные источники, библиотеки и помощь ИИ: TODO - Использованные источники, библиотеки и помощь ИИ:
- всё из ЛР 2–6: Python 3.13, Starlette, uvicorn, psycopg 3, redis-py, argon2-cffi, aiobotocore, aio-pika, Pillow, OpenTelemetry SDK 1.45.2;
- новые образы: **OpenBao 2.7.3**; новая библиотека на хосте — **cryptography 50.0.2** (только для `scripts/init_pki.py`);
- документация: [OpenBao AppRole](https://openbao.org/docs/auth/approle/), [policies](https://openbao.org/docs/concepts/policies/), [production hardening](https://openbao.org/docs/internals/security/), [OWASP Password Storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html), HAProxy `ssl`/`verifyhost`, PostgreSQL SSL и `pg_hba.conf`, Valkey TLS и ACL, RabbitMQ TLS, OpenTelemetry Collector `confighttp` TLS, Prometheus `web-config` (`client_allowed_sans`), Grafana provisioning `$__file{}`;
- код, тесты, конфигурации и документы написаны с помощью ИИ-ассистента Claude (Anthropic); решения разобраны и объяснимы автором ([docs/DEFENSE.md](docs/DEFENSE.md)).
## Запуск из чистого clone ## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. Версии (все образы закреплены по тегу **и** digest, см. [compose.yaml](compose.yaml)):
| Компонент | Версия |
| --- | --- |
| образ приложения | python 3.13.16-slim-bookworm |
| PostgreSQL | 18.6 |
| Valkey | 8.1.3 |
| SeaweedFS | 4.46 |
| RabbitMQ | 4.3.7 |
| HAProxy | 3.2.26 |
| OpenTelemetry Collector contrib | 0.165.0 |
| Prometheus | 3.16.0 |
| Loki | 3.7.10 |
| Tempo | 2.10.10 |
| Grafana | 13.2.6 |
| **OpenBao** | **2.7.3** (`@sha256:b9418c63…`, платформа linux/amd64) |
Python-пакеты приложения — `requirements.txt` с sha256 (`pip install --require-hashes --no-deps`).
Prerequisites: Docker с Compose v2, Python 3.12+, Git. Для Windows — [docs/WINDOWS.md](docs/WINDOWS.md). Действия оператора (init/unseal OpenBao, где лежат ключи, что делать после рестарта) — [docs/OPERATOR.md](docs/OPERATOR.md).
```sh
git clone <fork> mtusi2026lab7 && cd mtusi2026lab7 && git checkout solution/bvt2302-bodanyuk
python3 -m venv .venv
.venv/bin/python -m pip install --require-hashes --no-deps -r requirements.txt
.venv/bin/python -m pip install -r requirements-test.txt # pytest, httpx2, jsonschema, pillow, cryptography
.venv/bin/python scripts/init_secrets.py # ./secrets: пароли (по одному на сервис/роль) + PKI (2 CA, сертификаты сервисов)
docker compose up -d openbao # OpenBao стартует ЗАПЕЧАТАННЫМ (не dev)
.venv/bin/python scripts/bao_operator.py bootstrap # ОПЕРАТОР: init 3/2, unseal, KV, AppRole, политики, секреты
docker compose up -d --build --wait # migrate (0001-0007) и s3-init - один раз, exit 0
make check test test-security CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/bin/python
make mtls-check bao-check PYTHON=.venv/bin/python
make test-persistence ACTION_SCRIPT=scripts/restart.sh CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/bin/python
make test-failover ACTION_SCRIPT=scripts/stop-one.sh CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/bin/python && make restore
.venv/bin/python -m pytest student-tests -v # свои тесты, ~30-60 мин на этом ПК
```
То же самое для чистого стенда: `make secrets up`, затем `python scripts/collect_evidence.py` (вывод — в `evidence/`).
* **Действия оператора:** `bootstrap` один раз; `python scripts/bao_operator.py unseal` после **каждого** рестарта OpenBao (хук `scripts/restart.sh` делает это сам).
* Root token и доли unseal создаются в `~/.mtusi-lab7-operator/<project>/`, вне репозитория. В отчёте и в выводе скриптов значений нет.
* Grafana: `https://localhost:3000`, `admin` / `secrets/grafana_admin_password`.
* **Безопасная остановка:** `docker compose down` — volumes, включая хранилище OpenBao, остаются. После запуска: `up -d openbao` → `unseal` → `up -d --wait`.
* **Намеренное удаление учебных данных:** `docker compose down -v`, затем удалить `./secrets` и `~/.mtusi-lab7-operator/<project>`.
## Архитектура и решения ## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. ```text
public-ca internal-ca: mTLS, allowlist SAN "lb"
client --HTTPS 127.0.0.1:8443--> lb (HAProxy) ------------------------------------> api x2 (8443; health 127.0.0.1:8081)
api --TLS verify-full--> postgres (messenger_api) | --rediss--> valkey (ACL api) | --HTTPS--> s3 (messenger-api)
relay --TLS--> postgres (messenger_relay) | --AMQPS 5671--> broker (user relay: publish)
worker --TLS--> postgres (messenger_worker) | --AMQPS--> broker (user worker: consume) | --HTTPS--> s3 (messenger-worker)
api/relay/worker --HTTPS--> openbao (AppRole <svc>, read messenger/data/<svc>, revoke-self) [vault, internal]
api/relay/worker --OTLP/HTTPS + client cert--> otel-collector --mTLS--> prometheus / loki / tempo [telemetry]
grafana (HTTPS 127.0.0.1:3000, public-ca) --mTLS--> prometheus / loki / tempo
operator --docker compose exec--> openbao (root token и доли unseal через stdin, из ~/.mtusi-lab7-operator)
```
**Что перенесено из lab6** (коммит `6435b6a`, без изменений): весь API, relay, worker, outbox/lease, SeaweedFS, RabbitMQ, телеметрия, миграции 0001–0006, тесты, docs. Бизнес-API и источник истины (PostgreSQL) не менялись.
**Убрано как лишнее для lab7:**
* нагрузочные и исследовательские скрипты ЛР 3–6 (`bench/*` трека 1, инциденты, демо по HTTP);
* overlay tail-sampling Collector;
* открытые порты 8080 и 8404.
**Что изменено и добавлено** (коммиты по шагам, `git log`):
| Шаг | Что | Где |
| --- | --- | --- |
| PKI | 2 CA + leaf на сервис, SAN = имя compose, ECDSA P-256, 365 дней; ключи CA не монтируются нигде | `scripts/init_pki.py` |
| Внешний HTTPS | HAProxy `bind :8443 ssl crt ingress.pem ssl-min-ver TLSv1.2`; только loopback | `infra/haproxy/haproxy.cfg` |
| mTLS LB → API | uvicorn с `CERT_REQUIRED` + CA `internal-ca`; подкласс протокола сверяет SAN клиента с `MTLS_ALLOWED_CLIENTS=lb` и делает `abort()` до HTTP; health — отдельный listener на loopback | `src/messenger/tls.py`, `__main__.py` |
| TLS к зависимостям | PostgreSQL `ssl=on` + `pg_hba` только `hostssl`; Valkey `port 0`/`tls-port`; RabbitMQ `listeners.tcp = none`/5671; S3 HTTPS; OTLP HTTPS + client cert; Prometheus/Loki/Tempo — `RequireAndVerifyClientCert`; Grafana datasources — mTLS | `infra/*`, `compose.yaml`, `sessions.py`, `storage.py`, `broker.py` |
| Раздельные права | 6 ролей PostgreSQL, GRANT по коду; ACL Valkey; пользователи RabbitMQ; identities S3 (admin только у `s3-init`) | `infra/postgres/`, `migrations/0007_least_privilege.sql`, `infra/valkey/start.sh` |
| OpenBao | raft на volume `baodata`, TLS, audit в stdout; AppRole + policy на сервис; KV v2 `messenger/`; приложение читает секреты из OpenBao, файлов с паролями у api/relay/worker нет | `infra/openbao/`, `scripts/bao_operator.py`, `src/messenger/bao.py`, `config._secret` |
| Argon2id | параметры из env (не ниже m=19456, t=2, p=1), PHC; замер в контейнере API | `passwords.py`, `bench/argon2_bench.py` |
| Лимит входа | неудачи в Valkey, 5/60 с на имя и 50/300 с на IP; 429 + `Retry-After`; проверка до Argon2 | `ratelimit.py`, `app.create_session` |
| Hardening | `cap_drop: [ALL]` + `no-new-privileges` у всех 16 сервисов (у 4 хранилищ ещё CHOWN/DAC_OVERRIDE/FOWNER/SETGID/SETUID для chown и drop to user); app/worker uid 10001, CapEff 0 | `compose.yaml` |
| `X-Instance-Id` | случайный alias `i-<12 hex>` на процесс, без hostname/IP; для оператора лежит в `/tmp/instance_id` контейнера | `config._instance_id`, `scripts/stop-one.sh` |
Почему так, а не иначе (подробно — [docs/DEFENSE.md](docs/DEFENSE.md)):
* **Проверка SAN в приложении, а не sidecar.** Реплики масштабируются через `deploy.replicas`, и sidecar к каждой не привязать без отдельных сервисов `api1`/`api2`. Отдельный CA для LB хуже: identity держится на дисциплине выпуска, а не на явном allowlist.
* **OpenBao raft.** В 2.7 backend `file` удалён (`unknown storage type file`). Raft с одним узлом — тоже persistent storage на volume.
* **Токен сервиса отзывается сразу после чтения.** Статические KV на уровне 3 нужны только при старте. Живой токен в памяти ничего не даёт, а только расширяет окно утечки.
* **`CACHE_TIMEOUT_SECONDS` 0,5 → 1,0 с.** В бюджет теперь входит TLS-рукопожатие холодного соединения (см. «Дефекты»).
### Соответствие `.env.example` реальной конфигурации
| Переменная `.env.example` | Как в решении |
| --- | --- |
| `APP_HOST`, `APP_PORT` | `0.0.0.0`, **8443** (mTLS); health — `APP_HEALTH_PORT=8081` на loopback |
| `SESSION_TTL_SECONDS`, `IDEMPOTENCY_TTL_SECONDS`, `API_REPLICAS` | как есть (3600, 86400, 2) |
| `DATABASE_URL_FILE`, `CACHE_URL_FILE` | **нет у api/relay/worker**: `database_url`, `cache_url` читаются из OpenBao (`messenger/data/<svc>`); `DATABASE_URL_FILE` есть только у `migrate`, `jobctl`, `auditor` |
| `SESSION_STORE` | `valkey`; плюс `CACHE_TIMEOUT_SECONDS=1.0` (TLS-рукопожатие) и `CACHE_POOL_SIZE=8` (пул, прогретый до readiness) |
| `S3_ENDPOINT` | `https://s3:8333` |
| `S3_REGION`, `S3_BUCKET`, `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS`, `WORKER_CONCURRENCY`, `JOB_MAX_ATTEMPTS`, `JOB_TIMEOUT_SECONDS`, `STAGING_RETENTION_SECONDS` | как в lab6 (+ `S3_STAGING_BUCKET`) |
| `S3_*_FILE` | у api/worker — из OpenBao; файлы только у `s3`, `s3-init`, `auditor` |
| `BROKER_URL_FILE` | из OpenBao (`amqps://...:5671`) |
| `OTEL_SERVICE_NAME` | `messenger-api` / `-relay` / `-worker` |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `https://otel-collector:4318`, плюс `OTEL_EXPORTER_OTLP_CERTIFICATE`, `..._CLIENT_CERTIFICATE`, `..._CLIENT_KEY` |
| `PUBLIC_BASE_URL` | `https://localhost:8443` (используют тесты) |
| `TLS_CA_FILE` | internal CA для исходящих TLS (S3, Valkey, RabbitMQ) |
| `TLS_CERT_FILE`, `TLS_KEY_FILE` | сертификат и ключ сервиса (`/run/secrets/service.crt/.key`); у API ещё `TLS_CLIENT_CA_FILE` и `MTLS_ALLOWED_CLIENTS` |
| `BAO_ADDR`, `BAO_CACERT` | `https://openbao:8200`, internal CA; плюс `BAO_ROLE_ID_FILE`, `BAO_SECRET_ID_FILE`, `BAO_SECRET_PATH`, `BAO_STARTUP_TIMEOUT_SECONDS` |
| `ARGON2_MEMORY_KIB`, `ARGON2_ITERATIONS`, `ARGON2_PARALLELISM` | 19456, 2, 1 (по замеру) |
| (новое) `LOGIN_RATE_LIMIT_USER[_WINDOW_SECONDS]`, `LOGIN_RATE_LIMIT_IP[_WINDOW_SECONDS]` | 5/60 с, 50/300 с |
**Критичные зависимости readiness.** PostgreSQL, Valkey и S3, как в lab6. OpenBao в readiness не входит: работающей реплике он не нужен, а новая без него не стартует. Телеметрия и Grafana на readiness не влияют.
## Доказательства критериев ## Доказательства критериев
Все файлы — в [evidence/](evidence/), сводка — [evidence/SUMMARY.md](evidence/SUMMARY.md). Прогон из **чистого clone** в отдельной папке: новые secrets и сертификаты, пустые volumes, `COMPOSE_PROJECT_NAME=mtusi-lab7-clean`. Commit и окружение — в [evidence/stand.md](evidence/stand.md).
Прогон: commit `f2bd580`, 2026-11-28. Все 12 шагов сборщика — код 0.
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO | | Публичный smoke по HTTPS с проверяемым CA и hostname | `make test BASE_URL=https://localhost:8443 CA_FILE=<abs>/secrets/pki/public-ca.crt` | `PASS: lab7 public API scenario` (полный сценарий ЛР 1–6: пользователи, чаты, идемпотентность, файл → thumbnail, logout) | [smoke.txt](evidence/smoke.txt) |
| Остальные пункты уровня 3 | TODO | TODO | TODO | | Недоверенный CA отклоняется | `make test-security` | `PASS: trusted HTTPS works; untrusted CA rejected` | [test-security.txt](evidence/test-security.txt) |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | | Чужой hostname, внутренний CA снаружи, нет открытого входа | `pytest student-tests/test_security.py -k "ingress or plaintext"` | Hostname mismatch → ошибка проверки; порты 8080/8404/5432/6379/5671/8200/8333/… закрыты | [student-tests.txt](evidence/student-tests.txt) |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO | | Сертификаты создаются локально документированным bootstrap | `scripts/init_secrets.py` → `init_pki.py` в чистом clone | 2 CA + leaf на сервис созданы на хосте; в Git и образе ключей нет (`test_no_secret_in_git_or_in_the_image`) | [stand.md](evidence/stand.md), [student-tests.txt](evidence/student-tests.txt) |
| LB → **каждая** API-реплика: обязательное mTLS, отказ без cert / чужой CA / неверная identity | `make mtls-check` (`scripts/mtls_check.sh`) | по 2 репликам × TLS 1.3/1.2: без cert, `foreign-ca SAN=lb`, `internal-ca SAN=worker` → refused; `SAN=lb` → 200; открытый HTTP на 8443 и порт 8081 снаружи → нет; в логе API `mtls_identity_rejected "client_san": ["worker"]` | [mtls-check.txt](evidence/mtls-check.txt) |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. | Прямого обхода публичным портом API нет | `test_api_has_no_published_port_and_answers_only_mtls`, `test_compose_policy_limits_ports_secrets_images` | у API нет PortBindings; опубликованы только lb 8443 и grafana 3000 на 127.0.0.1/::1 | [student-tests.txt](evidence/student-tests.txt), [stand.md](evidence/stand.md) |
| TLS с проверкой сервера к DB, Valkey, S3, broker, Collector, backends; раздельные права | `pytest student-tests/test_security.py -k "postgres or valkey or broker or s3 or telemetry"` | PG: `ssl=on`, `sslmode=disable` → отказ, superuser по сети → отказ, 15 запрещённых запросов → `permission denied`; Valkey: NOPERM на FLUSHALL/CONFIG/KEYS/ACL/EVAL; RabbitMQ: relay не читает очередь, 5672 закрыт; S3: `api: write final: refused`; Collector без cert → отказ; worker с cert того же CA в Prometheus → отказ | [student-tests.txt](evidence/student-tests.txt), матрица — [contracts/trust-matrix.md](contracts/trust-matrix.md) |
| Телеметрия работает через mTLS | `scripts/trace_demo.py`, `scripts/check_dashboard.py` | trace API → relay → worker → S3/DB и логи с trace_id: 7/7 PASS; все запросы dashboard: `queries failed: 0` | [trace-demo.txt](evidence/trace-demo.txt), [dashboard-check.txt](evidence/dashboard-check.txt) |
| OpenBao в стенде, не dev, persistent storage | `bao_operator.py status`, `test_openbao_not_dev_and_persistent` | `initialized=True sealed=False storage=raft version=2.7.3`; команда без `-dev`; после рестарта данные на месте (persistence PASS) | [bao-check.txt](evidence/bao-check.txt) |
| api/relay/worker: сервисная аутентификация + scoped policy; нет root token / unseal / всемогущего токена | `make bao-check` | 3 × 16 проверок allow/deny: свой путь — 200, чужие пути, запись, `sys/*`, `auth/token/create` → 403, отозванный токен → 403; root token и 3 доли не найдены в `/run/secrets`, `/app`, `/tmp`, окружении PID 1 (положительный контроль находит свой role_id); env без `*TOKEN*`. Итого 66 PASS, 0 FAIL | [bao-check.txt](evidence/bao-check.txt) |
| Sealed OpenBao: работающие реплики живут, новые ждут unseal | `test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones` | PASS | [student-tests.txt](evidence/student-tests.txt) |
| Argon2id: соль и параметры в хеше, ≥ 19 MiB / t=2 / p=1, обосновано замером | `test_argon2id_hash_carries_salt_and_parameters`; `make argon2-bench` | `$argon2id$v=19$m=19456,t=2,p=1$<соль>$<хеш>`, разные соли у одинаковых паролей; замер — раздел «Эксперименты» | [argon2/bench.json](evidence/argon2/bench.json), [bench-run1-dev.json](evidence/argon2/bench-run1-dev.json) |
| Ограничение частоты входа 429 + Retry-After | `test_failed_logins_are_rate_limited_with_retry_after` | 5 × 401 → 429 `rate_limited`, `Retry-After` 1–60; верный пароль во время блокировки тоже 429; другой аккаунт — 201 | [student-tests.txt](evidence/student-tests.txt) |
| Ограничение размера запросов | `test_api.py::test_oversized_body_and_wrong_content_type`, `test_attachments.py::test_size_limit_through_the_load_balancer` | 413 до чтения тела; 10 MiB проходит через LB | [student-tests.txt](evidence/student-tests.txt) |
| Посторонний, logout/expiry, X-User-Id | `test_api.py`, `test_sessions.py`, `test_idempotency.py::test_outsider_and_revoked_session_never_see_the_stored_result` | чужое → 404; после logout и истечения TTL → 401; X-User-Id игнорируется | [student-tests.txt](evidence/student-tests.txt) |
| Контейнеры без privileged/host network/docker.sock; app и worker non-root, без capabilities, с лимитами | `test_running_containers_are_hardened`, `test_compose_policy…`, `stand.md` | у всех `CapDrop=[ALL]`, `no-new-privileges`, лимиты CPU/RAM; api/relay/worker uid 10001, `CapEff=0` | [stand.md](evidence/stand.md), [student-tests.txt](evidence/student-tests.txt) |
| Секреты не в Git, образе, телеметрии | `test_no_secret_in_git_or_in_the_image`, `test_observability.py::test_no_secrets_or_message_text_in_logs_and_traces` | значения секретов не найдены `git grep` и в файловой системе образа; в Loki/Tempo нет пароля, токена и текста | [student-tests.txt](evidence/student-tests.txt) |
| `X-Instance-Id` без hostname/IP | `test_x_instance_id_is_a_random_alias_without_hostname_or_ip` | `i-<12 hex>`, не совпадает с hostname/IP контейнеров | [student-tests.txt](evidence/student-tests.txt) |
| Рестарт с сохранением данных (шаг 4 защиты) | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS за 65 с: рестарт LB, API ×2, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ, OpenBao + unseal; `docker compose ps` до и после | [persistence.txt](evidence/persistence.txt) |
| Последовательный отказ API-реплик (шаг 4 защиты) | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` × 2 + `make restore` | остановлены обе реплики по очереди (`17c5883f5d19`, `87d05ecea97d`): 117 и 120 записей, 0 неудачных, восстановление 1,75 и 1,79 с | [failover.txt](evidence/failover.txt) |
| Всё из ЛР 2–6 сохранено | `pytest student-tests` (unit + стенд) | **425 passed, 4 skipped** (djpeg не установлен на Windows-хосте), 32 мин; в том числе 17 тестов `test_security.py` | [student-tests.txt](evidence/student-tests.txt) |
## Эксперименты и отказы ## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. ### Argon2id: выбор параметров замером
Замер на стенде: `bench/argon2_bench.py` внутри реплики API, с её лимитами (cgroup `cpu.max = 100000 100000` = 1 CPU, 512 MiB), argon2-cffi 25.1.0, p = 1. Сырые данные — [evidence/argon2/bench-run1-dev.json](evidence/argon2/bench-run1-dev.json) и [evidence/argon2/bench.json](evidence/argon2/bench.json).
Последовательно, по одному хешу (N = 15 на точку; мс):
| m, KiB (MiB) | t | замер 1 (dev): медиана / p95 | замер 2 (чистый clone): медиана / p95 | CPU на хеш, мс (1 / 2) |
| --- | --- | --- | --- | --- |
| 19456 (19) | 2 **выбрано** | 30.6 / 47.4 | 50.6 / 64.9 | 30.4 / 47.8 |
| 19456 (19) | 3 | 47.4 / 54.7 | 106.1 / 172.3 | 45.1 / 57.4 |
| 19456 (19) | 4 | 102.3 / 175.4 | 87.9 / 152.6 | 62.3 / 78.5 |
| 32768 (32) | 2 | 72.9 / 82.4 | 109.9 / 277.4 | 69.8 / 82.5 |
| 32768 (32) | 3 | 144.5 / 284.0 | 144.1 / 371.5 | 116.3 / 126.9 |
| 32768 (32) | 4 | 144.6 / 378.7 | 165.8 / 294.4 | 135.4 / 143.4 |
| 47104 (46) | 2 | 119.1 / 291.2 | 167.8 / 249.6 | 114.6 / 140.0 |
| 47104 (46) | 3 | 144.3 / 384.1 | 166.3 / 516.5 | 141.7 / 157.7 |
| 47104 (46) | 4 | 246.7 / 485.3 | 210.6 / 586.1 | 215.5 / 209.4 |
| 65536 (64) | 2 | 162.8 / 368.5 | 162.0 / 379.4 | 157.4 / 157.2 |
| 65536 (64) | 3 | 233.3 / 669.8 | 264.1 / 601.4 | 222.1 / 233.3 |
| 65536 (64) | 4 | 319.5 / 711.3 | 301.6 / 1100.1 | 261.4 / 279.5 |
Параллельно (K потоков хешируют одновременно, по 6 хешей на поток). Пропускная способность одной реплики = сколько входов в секунду она может проверить:
| m, KiB | t | K | хешей/с (1 / 2) | медиана, мс (1 / 2) | p95, мс (1 / 2) | RAM на хеши, MiB |
| --- | --- | --- | --- | --- | --- | --- |
| 19456 | 2 | 1 | 26.8 / 32.0 | 33.6 / 29.7 | 61.0 / 40.7 | 19.0 |
| 19456 | 2 | 2 | 30.6 / 28.8 | 74.3 / 83.0 | 89.3 / 89.6 | 38.0 |
| 19456 | 2 | 4 | 17.4 / 17.4 | 204.1 / 205.0 | 289.0 / 291.6 | 76.0 |
| 47104 | 2 | 1 | 4.3 / 5.5 | 206.5 / 176.9 | 369.1 / 309.5 | 46.0 |
| 47104 | 2 | 2 | 7.4 / 8.2 | 286.2 / 224.2 | 295.9 / 305.3 | 92.0 |
| 47104 | 2 | 4 | 5.4 / 5.0 | 703.6 / 799.9 | 988.7 / 980.1 | 184.0 |
| 19456 | 3 | 1 | 8.8 / 22.1 | 101.2 / 43.9 | 165.8 / 53.1 | 19.0 |
| 19456 | 3 | 2 | 14.3 / 19.0 | 114.2 / 106.5 | 201.5 / 156.0 | 38.0 |
| 19456 | 3 | 4 | 12.2 / 11.5 | 304.6 / 385.3 | 409.3 / 407.5 | 76.0 |
Замер 1: 2026-11-27T13:50:01Z, dev-стенд; замер 2: 2026-11-28T14:18:18Z, чистый стенд. Оба — в контейнере API: cgroup `cpu.max` 100000 100000, `memory.max` 536870912; argon2-cffi 25.1.0, Python 3.13.16.
Ещё один промежуточный замер на чистом стенде шёл, пока хост был загружен посторонним процессом на 85–100 % CPU. Там медиана m=19 MiB / t=2 была 154 мс; его сырой файл перезаписан финальным замером. Абсолютные числа меняются в 2–5 раз от фоновой нагрузки хоста, **соотношения между точками сохраняются**.
**Вывод.** Реплика имеет 1 CPU и разрешает 2 хеша одновременно (`PASSWORD_HASH_CONCURRENCY=2`, это 2 × m RAM). Цель — вход не дольше ~100 мс при двух параллельных хешах. Её выполняет только базовая конфигурация OWASP m=19 MiB, t=2, p=1.
* Следующий шаг по памяти (32 MiB) или по итерациям (t=3) даёт заметно более медленный вход.
* Вариант 46 MiB / t=2 даёт всего несколько хешей в секунду на реплику: вход становится дешёвой DoS-целью.
* Поэтому параметры не повышены. Защита от перебора дополнена лимитом неудачных входов, который срабатывает до Argon2.
* Числа шумные: Docker Desktop, рядом работает стенд. Выбор держится на порядке величин, а не на отдельных миллисекундах.
### Отказы
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | | `restart.sh`: рестарт LB, API ×2, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ, **OpenBao** (+ unseal оператором) | данные и сессия сохранены | PASS за 65 с, тот же токен, сообщения и файл на месте (`evidence/persistence.txt`) | 0 потерь |
| `stop-one.sh` по очереди для обеих реплик | запросы идут через оставшуюся, повтор без дублей | обе реплики по очереди: 117 и 120 записей, 0 неудачных попыток, первая успешная запись после отказа через 1,75 и 1,79 с (`evidence/failover.txt`) | 0 потерь подтверждённых |
| OpenBao запечатан (`docker compose restart openbao`) | работающие реплики обслуживают; новая не стартует до unseal | `test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones` PASS: запросы 200, новая реплика пишет `openbao_unavailable` и не становится healthy, после unseal поднимается | до unseal оператором |
| 5 неудачных входов одного пользователя | 429 + `Retry-After`, CPU не тратится | `test_failed_logins_are_rate_limited_with_retry_after` PASS | окно 60 с |
### Дефекты, найденные при проверке (честно)
1. **`pg_hba.conf` read-only.** Тест ЛР 3 «реплика жива, но не готова» добавляет временную строку `reject` в `pg_hba.conf`. После переноса hba в read-only файл тест падал. Исправлено: postgres при старте копирует `pg_hba.conf` из Git в tmpfs и использует копию. Источник правды остался в Git.
2. **Чтение отметки сбоя.** Внедрение сбоев (`FAULT_POINTS`, только для экспериментов) читает свою отметку из `job_events`, а у сервисов было только INSERT. Тесты конвейера с падением worker висели в `queued`. Исправлено: `GRANT SELECT ON job_events` для api/relay/worker. Это журнал заданий без пользовательских данных; записано в матрице.
3. **Таймаут Valkey 0,5 с мал для TLS.** Только что запущенная реплика один раз не уложилась в 0,5 с на холодном TLS-соединении к Valkey (568 мс, 503 в тесте мягкой остановки). Исправлено: `CACHE_TIMEOUT_SECONDS=1.0`, граница теста отказа Valkey 2,6 с.
4. **`redis-py incr()` = `INCRBY`.** Лимит входа отвечал 503 из-за `NOPERM`. Исправлено: в ACL добавлен `+incrby`. Теперь любая ошибка ACL видна тестом.
5. **`X-Instance-Id` перезаписывался вспомогательным процессом.** Отладочный `docker compose exec api python …` генерировал новый alias и переписывал `/tmp/instance_id`, и `stop-one` не находил реплику. Исправлено: файл пишет только главный процесс сервиса.
6. **CRLF в stdin на Windows.** Тесты, передающие пароль через stdin, на Windows посылали `\r\n`. Исправлено: stdin передаётся байтами.
Ещё шесть дефектов нашёл первый прогон из чистого clone (13 падений из 425). Часть совпала с перегрузкой хоста посторонним процессом на 85–100 % CPU, поэтому прогон был повторён полностью. В итоговом прогоне — 0 падений.
7. **Всплеск TLS-соединений к Valkey.**
* Что было: 24 параллельных запроса на свежей реплике открывали 24 новых TLS-соединения, часть рукопожатий не укладывалась в таймаут → 503 (`test_concurrent_same_key…`, требование ЛР 3 «все 201»).
* Исправлено: ограниченный пул (`CACHE_POOL_SIZE=8`), прогретый до readiness (`sessions.warm`).
8. **`restart.sh` дольше 90 с.** Три отдельных `docker compose start` ждали healthcheck по ~23 с каждый. Исправлено: один `start api relay worker lb` (80 → 65 с).
9. **`stop-one.sh` дольше 10 с.**
* Что было: `docker exec` на Windows стоит ~1,8 с на реплику, плюс синхронный `docker stop` с drain.
* Исправлено: alias реплик читаются параллельно, `docker stop` запускается в фоне. Docker сразу помечает контейнер остановленным пользователем, поэтому restart policy его не поднимет.
10. **Healthcheck и `start_period` API.**
* Что было: под нагрузкой старт Python-пробы занимал > 2 с, и здоровая реплика оставалась `unhealthy`; после холодного старта Docker `up --wait` сдавался раньше, чем API успевал войти в OpenBao.
* Исправлено: `timeout: 5s`, `start_period: 30s`. Обнаружение упавшей реплики после старта осталось 3 × 2 с.
11. **`check_dashboard.py` без нашего CA.** Скрипт обращался к Grafana без публичного CA. Исправлено: `context=obs.TLS`.
12. **Хрупкие тесты.**
* Время «реплика не замерла» включало `docker exec` → теперь меряется внутри контейнера.
* Ручной upload по TLS читал только первую TLS-запись → теперь дочитывает ответ.
* Grace уборщика 3 с был короче самих проверок через `docker exec` → 15 с.
* Сборщик доказательств ронял одну и ту же реплику из-за положения round-robin → теперь сдвигает его между прогонами.
## Ограничения и следующие шаги ## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. * **Уровень 4 не заявлен:**
* нет ротации и отзыва leaf/secret, CRL/OCSP;
* SecretID живёт 30 дней, нет wrapping;
* нет mTLS к брокеру;
* Loki/Tempo проверяют только цепочку CA, без allowlist SAN;
* Grafana в Prometheus может и писать;
* нет read_only/seccomp и сканирования образов;
* лимит входа не защищает от распределённого перебора с многих IP.
* **Root token не отзывается после настройки**, а хранится у оператора. Доли unseal лежат в одной папке, а не у трёх людей. Это учебное упрощение, оно описано.
* **Четыре stateful-образа стартуют от root** ради `chown` и сразу понижают права; оставлен минимальный набор capabilities.
* **Plaintext-hop'ы есть только на loopback** контейнеров (SeaweedFS master/volume/filer, gRPC Loki/Tempo, health 8081). Из сети они недоступны, это проверено тестами.
* **Один Docker-host.** Отказ хоста, единственной БД, LB или OpenBao не переживается.
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Argon2id parameter measurement ON THIS STAND (README grade 3: "параметры обоснованы измерением").
Runs INSIDE an API replica, i.e. with exactly the CPU/RAM limits of production (compose: 1 CPU,
512 MiB) and the same argon2-cffi build:
docker compose exec -T api python - < bench/argon2_bench.py > evidence/argon2/bench.json
For every (m, t) of the grid (p = 1): N sequential hashes -> median / p95 latency and CPU time per
hash; then, for the candidate parameters, K threads hashing at once (K = 1, 2, 4) -> latency
under contention and hashes/s of the replica = the most logins/s one replica can verify
(the cost of a password guessing / login DoS attempt). Prints one JSON document (no passwords:
a fixed synthetic one is hashed).
"""
import json
import os
import platform
import statistics
import threading
import time
import importlib.metadata
from argon2 import PasswordHasher, Type
PASSWORD = "synthetic-benchmark-password"
GRID_M = [19456, 32768, 47104, 65536] # KiB: 19 MiB (OWASP minimum), 32, 46, 64 MiB
GRID_T = [2, 3, 4]
N = int(os.environ.get("BENCH_N", "15"))
THREADS = [1, 2, 4]
PER_THREAD = int(os.environ.get("BENCH_PER_THREAD", "6"))
def cgroup_limits() -> dict:
out = {}
for name, path in (("cpu_max", "/sys/fs/cgroup/cpu.max"), ("memory_max", "/sys/fs/cgroup/memory.max")):
try:
with open(path) as f:
out[name] = f.read().strip()
except OSError:
out[name] = None
return out
def sequential(m: int, t: int) -> dict:
ph = PasswordHasher(time_cost=t, memory_cost=m, parallelism=1, hash_len=32, salt_len=16, type=Type.ID)
ph.hash(PASSWORD) # warm-up (allocator, first-touch of the pages)
wall, cpu = [], []
for _ in range(N):
w0, c0 = time.perf_counter(), time.thread_time()
ph.hash(PASSWORD)
wall.append((time.perf_counter() - w0) * 1000)
cpu.append((time.thread_time() - c0) * 1000)
wall.sort()
return {"m_kib": m, "t": t, "p": 1, "n": N, "median_ms": round(statistics.median(wall), 1),
"p95_ms": round(wall[min(len(wall) - 1, int(0.95 * len(wall)))], 1),
"cpu_ms_per_hash": round(statistics.median(cpu), 1),
"hash_example_prefix": ph.hash(PASSWORD).split("$")[1:4]}
def concurrent(m: int, t: int, threads: int) -> dict:
ph = PasswordHasher(time_cost=t, memory_cost=m, parallelism=1, hash_len=32, salt_len=16, type=Type.ID)
lat: list[float] = []
lock = threading.Lock()
def work():
for _ in range(PER_THREAD):
w0 = time.perf_counter()
ph.hash(PASSWORD)
with lock:
lat.append((time.perf_counter() - w0) * 1000)
c0, w0 = time.process_time(), time.perf_counter()
pool = [threading.Thread(target=work) for _ in range(threads)]
for th in pool:
th.start()
for th in pool:
th.join()
wall = time.perf_counter() - w0
lat.sort()
return {"m_kib": m, "t": t, "threads": threads, "hashes": len(lat), "wall_s": round(wall, 2),
"hashes_per_s": round(len(lat) / wall, 1), "median_ms": round(statistics.median(lat), 1),
"p95_ms": round(lat[min(len(lat) - 1, int(0.95 * len(lat)))], 1),
"cpu_utilisation": round((time.process_time() - c0) / wall, 2),
"ram_mib_hashing": round(m * threads / 1024, 1)}
def main() -> None:
report = {"when": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "python": platform.python_version(),
"argon2_cffi": importlib.metadata.version("argon2-cffi"), "cpus_visible": os.cpu_count(), "cgroup": cgroup_limits(),
"sequential": [sequential(m, t) for m in GRID_M for t in GRID_T]}
report["concurrent"] = [concurrent(m, t, k) for (m, t) in ((19456, 2), (47104, 2), (19456, 3)) for k in THREADS]
print(json.dumps(report, indent=1))
if __name__ == "__main__":
main()
+1029
View File
File diff suppressed because it is too large Load Diff
+86 -22
View File
@@ -1,37 +1,101 @@
# Матрица доверия — заполнить в решении lab7 # Матрица доверия — решение lab7 (уровень 3)
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, 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 нужно доказать.
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | **Два домена доверия** (`scripts/init_pki.py`, ключи в `./secrets/pki`, вне Git и образов):
| --- | --- | --- | --- |
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | * `public-ca` подписывает только то, к чему подключается человек: ingress `:8443` и Grafana UI (SAN `localhost`, `127.0.0.1`, `::1`). Это `CA_FILE` публичных тестов. Ни один сервис ему не доверяет.
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | * `internal-ca` подписывает identity сервисов. SAN = имя сервиса compose (то, что набирает клиент), EKU `serverAuth`/`clientAuth` по роли. Сервисы доверяют только ему.
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | * Ключи CA не монтируются ни в один контейнер. Leaf-сертификаты: ECDSA P-256, срок 365 дней, CA — 5 лет. Каждый контейнер получает через compose `secrets:` только свой cert/key и нужный ему CA.
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | Колонки «Минимум на 3» и «Дополнительно на 4» — из задания (уровень 4 не заявлен), «Решение» — что сделано (порт, CA/SAN, identity, срок жизни credentials), «Доказательство» — конфиг и тест (положительный / отрицательный). Тесты лежат в `student-tests/test_security.py` (`make security-test`), выводы — в `evidence/`.
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | | Связь | Минимум на 3 | Дополнительно на 4 | Решение (порт, CA/SAN, identity, срок жизни) | Доказательство / конфиг |
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | | --- | --- | --- | --- | --- |
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | | Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit — *не заявлено (цель — уровень 3)* | HAProxy `bind :8443 ssl crt ingress.pem ssl-min-ver TLSv1.2`, опубликован только на `127.0.0.1`/`[::1]`. Сервер: `public-ca`, SAN `localhost`/`127.0.0.1`/`::1`. Клиент: Bearer-сессия (≥256 бит, TTL `SESSION_TTL_SECONDS`), вход Basic + Argon2id, лимит неудачных входов. Открытого порта 8080 нет | `infra/haproxy/haproxy.cfg`. **+** `make test`, `make test-security` с `CA_FILE`. **−** пустой trust store и чужой hostname → `SSLCertVerificationError`; внутренний CA не подходит; открытый HTTP на 8443 не отвечает 200; порты 8080/8404/5432/… закрыты (`test_ingress_verifies_ca_and_hostname`, `test_no_plaintext_entry_point`) |
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | | LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки — *не заявлено (цель — уровень 3)* | HAProxy → `api:8443` (`server-template`, DNS): `ssl verify required ca-file internal-ca.crt verifyhost api crt lb.pem`. API (`src/messenger/tls.py`): `CERT_REQUIRED`, доверяет только `internal-ca`, после рукопожатия класс протокола uvicorn сверяет DNS SAN клиента с `MTLS_ALLOWED_CLIENTS=lb`, иначе `abort()` до чтения HTTP. Health-проверки HAProxy идут тем же mTLS. Docker healthcheck — отдельный listener `127.0.0.1:8081` в loopback контейнера, только `/health/*` | `scripts/mtls_check.py` (`make mtls-check`) по **каждой** реплике напрямую. **−** без cert, cert `foreign-ca` с SAN `lb`, cert `internal-ca` с SAN `worker` → отказ при TLS 1.3 и TLS 1.2; открытый HTTP на 8443 и порт 8081 снаружи → отказ. **+** cert `lb` → `200`. В логе API `mtls_identity_rejected client_san=[worker]` |
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO | | API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление — *не заявлено (цель — уровень 3)* | `postgres:5432`, `ssl=on`, TLS 1.2+, SAN `postgres`. `pg_hba.conf`: только `hostssl` для 6 сервисных ролей (SCRAM), `host all all all reject`. Суперпользователь `postgres` — только через локальный сокет (peer). Роли: `messenger_migrate` (владелец схемы), `messenger_api`/`_relay`/`_worker` (GRANT по коду, `migrations/0007_least_privilege.sql`), `messenger_jobctl`/`_auditor` (инструменты). URL: `sslmode=verify-full&sslrootcert=internal-ca.crt`. URL api/relay/worker приходят из OpenBao, файлом их нет. Пароли статические (ротация — уровень 4) | `test_postgres_tls_only_and_roles_least_privilege`. **+** `SELECT 1` по TLS (`pg_stat_ssl.ssl = t`). **−** `sslmode=disable` → `no encryption`; суперпользователь по сети → `pg_hba.conf`; api: `DELETE FROM messages`, `job_attempts`, `CREATE TABLE`, `TRUNCATE`, `UPDATE users`; relay/worker: `users`, `messages`, `sessions`; worker: `post_message_v3`; auditor: запись → `permission denied` |
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO | | API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация — *не заявлено (цель — уровень 3)* | SeaweedFS S3 `s3:8333` только HTTPS (`-s3.cert.file`), SAN `s3`. Клиенты aiobotocore с `verify=internal-ca.crt`. Identities: `messenger-api` = Write staging + Read final; `messenger-worker` = Read/Write обоих; `messenger-auditor` = Read+List; `bootstrap-admin` — только у `s3-init` и самого `s3`. Ключи api/worker — из OpenBao. Внутренние master/volume/filer слушают `127.0.0.1` контейнера (закрытый local hop) | `s3-init` проверяет модель доступа при каждом старте: `api: write final: refused (AccessDenied)`, `auditor: delete staging: refused`, `api: ListBuckets: []`. `test_s3_https_and_scoped_keys`. **−** `http://s3:8333` → нет ответа |
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей — *не заявлено (цель — уровень 3)* | RabbitMQ: `listeners.tcp = none`, `listeners.ssl.default = 5671`, SAN `broker`, TLS 1.2/1.3. Пользователи: `relay` — `configure ^$`, `write ^messenger\.jobs$`, `read ^$`; `worker` — `read ^messenger\.attachment-jobs$`, остальное `^$`. API в сети `queue` не состоит. URL `amqps://` — из OpenBao | `test_broker_tls_only_and_users_scoped`. **−** relay пытается читать очередь → `ChannelAccessRefused`; порт 5672 закрыт. **+** relay публикует и worker потребляет (smoke: thumbnail готов) |
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities — *не заявлено (цель — уровень 3)* | OTLP/HTTPS `otel-collector:4318`, SAN `otel-collector`. Receiver `tls.client_ca_file` = обязательный клиентский сертификат `internal-ca`. SDK: `OTEL_EXPORTER_OTLP_CERTIFICATE` (CA) + свой cert `api`/`relay`/`worker`. Сеть `telemetry` — `internal`. `health_check` только на `127.0.0.1` | `test_telemetry_endpoints_require_client_certificates`. **−** процесс без client cert → отказ. **+** `make trace-demo`: span'ы и логи api/relay/worker доходят (7/7 PASS) |
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege — *не заявлено (цель — уровень 3)* | mTLS: Collector предъявляет cert `otel-collector`. Prometheus `--web.config.file`: `RequireAndVerifyClientCert`, `client_allowed_sans: [otel-collector, grafana, prometheus]`. Loki (`:3100`) и Tempo (`:4318`, `:3200`): `RequireAndVerifyClientCert` по `internal-ca`, gRPC на `127.0.0.1`. Собственные метрики Collector — OTLP push по mTLS (pull-endpoint `:8888` без TLS убран) | **−** worker с сертификатом того же CA → Prometheus отказывает (SAN не в allowlist). **+** метрики, логи и трассы в хранилищах (`scripts/obs.py`, trace-demo). Ограничение: Loki/Tempo проверяют только цепочку CA, без allowlist SAN |
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа — *не заявлено (цель — уровень 3)* | Datasources `https://prometheus:9090`, `https://loki:3100`, `https://tempo:3200`: `tlsAuthWithCACert` (internal CA), `serverName` = SAN, клиентский cert `grafana`, файлы через `$__file{}`. Grafana UI — HTTPS `127.0.0.1:3000`, cert `public-ca`, cookie secure | **+** `scripts/check_dashboard.py` — все запросы dashboard через datasource proxy. **−** без client cert backend отказывает (см. строку выше). Ограничение: identity `grafana` в Prometheus может и писать (OTLP) — роли чтения нет |
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation — *не заявлено (цель — уровень 3)* | `openbao:8200` (сеть `vault`, `internal`), TLS 1.2+, SAN `openbao`. AppRole на каждый сервис: `token_policies=<svc>`, `token_no_default_policy`, `token_ttl=1h`, `token_max_ttl=4h`; SecretID `ttl=720h`. Policy: `read messenger/data/<svc>` + lookup/revoke-self. Сервис при старте делает login → читает свой путь → `revoke-self` (`src/messenger/bao.py`). role_id/secret_id — Docker secrets только своего сервиса | `scripts/bao_check.py` (`make bao-check`) внутри api/relay/worker. **+** login, свой путь. **−** чужие пути, запись своего, list metadata, запись policy, `sys/policies`, `auth/token/create`, `sys/auth`, `sys/mounts` → 403; отозванный токен → 403; неверный secret_id → 400 |
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles — *не заявлено (цель — уровень 3)* | OpenBao: `docker compose exec openbao bao …` к `https://127.0.0.1:8200` с проверкой CA, root token и доли передаются **через stdin** (`scripts/bao_operator.py`). Root token и 3 доли unseal (порог 2) лежат в `~/.mtusi-lab7-operator/<project>/` (0600, вне репозитория). Grafana: `https://localhost:3000`, admin + пароль из `secrets/`. S3 admin: порт не опубликован, ключ только у `s3-init`. PostgreSQL superuser: `docker compose exec -u postgres postgres psql` | `scripts/bao_check.sh`: root token и доли не найдены в `/run/secrets`, `/app`, `/tmp`, окружении PID 1 api/relay/worker. Положительный контроль: свой role_id тем же поиском находится. В env нет `*TOKEN*` |
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности — *не заявлено (цель — уровень 3)* | Valkey `port 0`, `tls-port 6379`, SAN `valkey`, `tls-auth-clients no`. ACL: `user default off`; `user api` (SHA-256 пароля) `~session:* ~ratelimit:*`, `-@all +get +set +del +incr +incrby +pexpire +pttl +multi +exec +discard +ping +client|setinfo`. Клиент: `rediss://` + `ssl_ca_certs` + `ssl_check_hostname`. URL — из OpenBao | `test_valkey_tls_and_acl`. **+** `PING` → `PONG`. **−** FLUSHALL, CONFIG, KEYS, ACL, чужой ключ, EVAL → `NOPERM`; без TLS и пользователем `default` → нет `PONG` |
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа — *не заявлено (цель — уровень 3)* | N/A: каждое хранилище в одном экземпляре (один Docker-host). Raft-порт OpenBao 8201 слушает, но пиров нет; если бы были, использовался бы его собственный автоматический TLS | — |
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
## Служебные каналы: scrape, health, bootstrap
| Канал | Как защищён | Почему не обход |
| --- | --- | --- |
| Docker healthcheck API | `python -m messenger.healthcheck` → `http://127.0.0.1:8081/health/ready` | listener на loopback контейнера, только `/health/live`, `/health/ready`, `/health/ready/core`, иначе 404. `mtls_check`: порт 8081 с другого контейнера → `ConnectionRefused` |
| Healthcheck хранилищ | postgres `pg_isready` (socket); valkey `valkey-cli --tls --cacert`; s3 и grafana `curl --cacert https://localhost…`; prometheus `promtool check ready` с mTLS; openbao `bao status` (TLS, CA) | только изнутри своего контейнера |
| HAProxy health checks | тот же mTLS, что и трафик (`ssl` наследуется) | реплика без правильного cert не попадает в ротацию |
| HAProxy stats | `bind 127.0.0.1:8404` в контейнере, не опубликован; admin socket — через `docker compose exec` | недоступен из сети |
| Prometheus scrape | `prometheus` (self), `loki`, `tempo` по HTTPS + client cert `prometheus`; scrape Grafana убран | все цели требуют mTLS |
| Bootstrap | `migrate` (роль-владелец, TLS), `s3-init` (admin-ключ S3, HTTPS), `bao_operator.py` (stdin → CLI в контейнере OpenBao), `init_secrets.py`/`init_pki.py` (файлы на хосте) | одноразовые задачи, своих портов нет |
## Сравнительная матрица разрешений (S3, брокер, PostgreSQL)
«—» значит запрещено. Источник правды — конфиги: `infra/seaweedfs/start.sh`, `scripts/init_secrets.py` (RabbitMQ), `migrations/0007_least_privilege.sql`, `infra/valkey/start.sh`, `infra/openbao/policies/*.hcl`.
| Ресурс | api | relay | worker | migrate / s3-init | jobctl / auditor (оператор) |
| --- | --- | --- | --- | --- | --- |
| S3 staging bucket | Write (+DELETE для уборщика) | — | Read, Write | s3-init: Admin (создать bucket) | auditor: Read, List |
| S3 final bucket | Read | — | Read, Write | s3-init: Admin | auditor: Read, List |
| S3 ListBuckets / Admin | — | — | — | s3-init | — |
| RabbitMQ exchange `messenger.jobs` | — (не в сети `queue`) | write | — | — | — |
| RabbitMQ queue `messenger.attachment-jobs` | — | — | read (consume/ack) | — | — |
| RabbitMQ configure (declare/delete) | — | — | — | топология из definitions самого брокера | — |
| PG `users`, `chat_members`, `messages`, `message_attachments` | SELECT, INSERT | — | — | migrate: владелец (DDL) | — |
| PG `chats` | SELECT, INSERT, UPDATE | — | — | владелец | — |
| PG `sessions`, `idempotency_keys` | SELECT, INSERT, (UPDATE), DELETE | — | — | владелец | — |
| PG `attachments` | SELECT, INSERT, UPDATE, DELETE | SELECT, UPDATE | SELECT, UPDATE | владелец | jobctl: SELECT, UPDATE; auditor: SELECT |
| PG `attachment_variants` | SELECT | — | SELECT, INSERT | владелец | SELECT |
| PG `jobs` | SELECT, INSERT | SELECT, UPDATE | SELECT, UPDATE | владелец | jobctl: SELECT, INSERT, UPDATE; auditor: SELECT |
| PG `job_attempts` | — | SELECT, UPDATE | SELECT, INSERT, UPDATE | владелец | SELECT |
| PG `outbox` | INSERT | SELECT, INSERT, UPDATE, DELETE | INSERT | владелец | jobctl: SELECT, INSERT; auditor: SELECT |
| PG `job_events` | SELECT, INSERT | SELECT, INSERT | SELECT, INSERT | владелец | jobctl: SELECT, INSERT; auditor: SELECT |
| PG `post_message*()` | EXECUTE | — | — | владелец | — |
| PG DDL / TRUNCATE / superuser | — | — | — | migrate: DDL своей схемы; superuser ни у кого из сервисов | — |
| Valkey `session:*`, `ratelimit:*` | GET/SET/DEL/INCR/PEXPIRE/PTTL | — | — | — | — |
| OpenBao | read `messenger/data/api` | read `messenger/data/relay` | read `messenger/data/worker` | — | оператор: root token (вне контейнеров) |
## Обязательные отрицательные проверки ## Обязательные отрицательные проверки
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». 1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». → `make test-security`, `test_ingress_verifies_ca_and_hostname`.
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. 2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. → `make mtls-check` (каждая реплика, TLS 1.3 и 1.2).
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. 3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. → уровень 4 не заявлен. На уровне 3 Collector уже требует client cert, Prometheus — allowlist SAN.
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. 4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. → `test_api.py::test_foreign_chat_is_indistinguishable_from_missing`, `test_x_user_id_basic_and_garbage_do_not_authenticate`, `test_attachments.py` (чужое вложение → 404).
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. 5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. → `make bao-check`; KV worker = роль `messenger_worker` + ключ `messenger-worker`.
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. 6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. → уровень 4 не заявлен.
## Bootstrap и эксплуатация ## Bootstrap и эксплуатация
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
**Как сделано:** подробно в [docs/OPERATOR.md](../docs/OPERATOR.md).
* Ключи CA и leaf создаёт `init_pki.py` в `./secrets/pki`: папка 0700, `.gitignore`, `.dockerignore`. Доступ к ним есть только у оператора хоста.
* Root token и 3 доли unseal создаёт `bao_operator.py bootstrap` в `~/.mtusi-lab7-operator/<project>/` — вне репозитория и вне контейнеров. В реальной команде каждую долю хранит отдельный человек.
* После рестарта OpenBao запечатан. Уже работающие сервисы продолжают работу, новые реплики не стартуют, пока оператор не выполнит `bao_operator.py unseal` (это делает и `scripts/restart.sh`).
* Хук `test_security.py::test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones` это доказывает.
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 — хорошее расширение, но не обязательное название технологии. 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 — хорошее расширение, но не обязательное название технологии.
**Как сделано:**
* Integrated storage (Raft, один узел) на volume `baodata`, AppRole, KV v2 `messenger/`.
* Токен сервиса живёт секунды: login → read → revoke-self. Max TTL 1 ч — граница, если отзыв не удался.
* Re-auth выполняется при каждом старте процесса.
* SecretID живёт 30 дней и выдаётся заново командой `bao_operator.py new-secret-id <svc>`. Это осознанный компромисс уровня 3; короткий SecretID и wrapping относятся к уровню 4.
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
**Как сделано:**
* Доли хранятся у оператора, не в volume и не в контейнере OpenBao.
* Обычный рестарт API unseal не требует: unseal нужен только после рестарта самого OpenBao.
+57
View File
@@ -0,0 +1,57 @@
# Модель данных lab5
Схема: [0001_init.sql](../migrations/0001_init.sql) (lab2), [0002_idempotency_keys.sql](../migrations/0002_idempotency_keys.sql) и [0003_post_message_function.sql](../migrations/0003_post_message_function.sql) (lab3), [0004_attachments.sql](../migrations/0004_attachments.sql) (lab4), [0005_pipeline.sql](../migrations/0005_pipeline.sql) (lab5: задания, outbox, попытки, варианты). Миграции применяет один раз отдельный сервис `migrate` до старта реплик API; миграции lab3–lab5 только добавляют объекты (0004 ослабляет `CHECK` длины текста, 0005 — `CHECK` статуса и ключа объекта), поэтому совместимы с работающей предыдущей версией. Байты вложений живут **только** в двух приватных bucket S3 (SeaweedFS): `messenger-staging` (оригинал до обработки) и `messenger-attachments` (опубликованный оригинал и варианты); в PostgreSQL — метаданные, задания и их история. Порядок записи и окна отказа — [PIPELINE.md](PIPELINE.md). Источник истины для пользователей, чатов, участников и сообщений — PostgreSQL 18. Для сессий источник истины — хранилище, выбранное через `SESSION_STORE`. По умолчанию это Valkey с AOF, его можно переключить на таблицу `sessions` в PostgreSQL.
## Таблицы и ограничения
| Таблица | Ключ | Ограничения | Зачем |
| --- | --- | --- | --- |
| `users` | `id uuid` | `UNIQUE (username)`, `CHECK` формата username, длина `display_name` | уникальность имени держит БД, а не код: гонку регистрации разрешает уникальный индекс |
| `chats` | `id uuid` | FK `created_by → users`, длина `title` | `last_message_at` — «часы» чата для упорядочивания сообщений |
| `chat_members` | `(chat_id, user_id)` | FK на `chats` и `users`, `UNIQUE (chat_id, position)` | `position` хранит порядок `member_ids`; `chat_created_at` — копия времени чата для keyset-списка чатов |
| `messages` | `id uuid` | FK `(chat_id, sender_id) → chat_members`, длина `text` | отправитель обязан быть участником — это гарантирует сама БД |
| `sessions` | `token_hash bytea` | FK `user_id → users`, длина хеша 32 байта | хранится SHA-256 токена; сам токен не хранится нигде |
| `idempotency_keys` | `(user_id, chat_id, key)` | FK на `users`, `chats`; `message_id → messages` (DEFERRABLE, `UNIQUE`); `CHECK` формата ключа и длины SHA-256 | общая для всех реплик идемпотентность отправки: ключ → отпечаток тела → сообщение. Хранится ≥ `IDEMPOTENCY_TTL_SECONDS` (24 ч), очистка — пачками раз в 10 мин под advisory-замком |
| `attachments` (lab4, lab5) | `id uuid` | FK `(chat_id, owner_id) → chat_members`; `UNIQUE object_key`, `UNIQUE staging_key` (`COLLATE "C"`); `CHECK` статуса `pending/queued/processing/ready/failed`, формата ключей, типа, размера, пикселей ≤ 40 млн; **`attachments_active_has_source`**: у `queued/processing` есть опубликованный оригинал или staging `present`; `ready` ⇒ `object_key` и `published_version`; `failed` ⇔ `error_code` + `failed_at` | метаданные оригинала. `staging_key` (`s/<128 бит>`) — копия в staging, `staging_state none/present/deleting/deleted`; `object_key` — опубликованный оригинал (`a/<id>/<token>/original`, у строк lab4 — `o/<hex>`). `published_version` — версия pipeline, чьи варианты видны, только растёт |
| `jobs` (lab5) | `id uuid` = job_id | FK на `attachments`; `CHECK` состояния, вида (`upload/replay/reprocess/migrate`), `attempt ≤ max_attempts`, lease есть ⇔ `processing`, `finished_at` ⇔ конечное; частичный `UNIQUE (attachment_id, pipeline_version) WHERE state IN ('queued','processing')` | одна логическая работа «версия V для вложения A». `available_at` — backoff, `lease_token`/`lease_until`/`lease_owner` — аренда текущей попытки (fencing). Индексы: истекающие lease, queued, failed |
| `job_attempts` (lab5) | `token uuid` | FK на `jobs`; `UNIQUE (job_id, attempt)`; `CHECK` исхода `running/succeeded/retry/failed/abandoned/superseded`; опубликованную попытку нельзя «почистить» | один claim worker. `planned_keys` — ключи всех объектов попытки, записаны ДО записи в S3: уборке не нужен List. Частичный индекс — кандидаты на уборку |
| `attachment_variants` (lab5) | `(attachment_id, pipeline_version, name)` | FK на `attachments`, `job_attempts`; `UNIQUE object_key`, `CHECK` имени, типа, размера, длины SHA-256 | опубликованные варианты; первичный ключ — ключ эффекта контракта, дубль физически невозможен |
| `outbox` (lab5) | `id bigint` identity | FK на `jobs`; `attempt ≥ 1` | намерение опубликовать сообщение; пишется в одной транзакции с изменением задания. Частичный индекс `WHERE published_at IS NULL` — работа relay |
| `job_events` (lab5) | `id bigint` identity | FK на `jobs` | аудит: создание, claim, retry с задержкой, lease_expired, replay/reprocess (оператор и причина), результат, внедрённые отказы. Без секретов и имён файлов. View `failed_jobs` — реестр failed |
| `message_attachments` (lab4) | `(message_id, position)` | FK на `messages` и `attachments`, `UNIQUE (message_id, attachment_id)`, индекс по `attachment_id` | целостность ссылок (вложение, на которое ссылается сообщение, удалить нельзя) и обратный поиск «используется ли вложение» |
| `schema_migrations` | `version` | checksum файла | какие миграции применены; изменённую задним числом миграцию мигратор не применит |
**Почему `bytea` для текста.** Контракт разрешает символ U+0000, а тип `text` в PostgreSQL не может содержать байт NUL (`DataError`). Поэтому `display_name`, `title` и `text` хранятся как байты UTF-8. Длину в code points проверяет API, а `CHECK` в байтах — страховка (1 code point ≤ 4 байта).
## Индексы и запросы
- `messages_chat_keyset (chat_id, created_at, id)`. Первая страница — `WHERE chat_id=$1 ORDER BY created_at, id LIMIT n`, следующая — `WHERE chat_id=$1 AND (created_at, id) > ($2, $3) ORDER BY ... LIMIT n`. Сравнение строк `(created_at, id) > (...)` попадает в `Index Cond`: поиск начинается прямо с позиции cursor и читает только `n+1` строк. Запросов два, а не один с `($2 IS NULL OR ...)`: иначе при generic plan условие cursor уходит в `Filter`, и поздняя страница сканирует всю историю чата до неё.
- `chat_members_user_keyset (user_id, chat_created_at, chat_id)` — список чатов пользователя тем же keyset-способом.
- `users_username_key` — вход по username и уникальность.
- `sessions_expires_at` — очистка истёкших сессий.
## Транзакционные границы
| Операция | Транзакция | Что гарантирует |
| --- | --- | --- |
| Регистрация | один `INSERT` | `UniqueViolation` → 409; ровно одна строка при гонке |
| Создание чата | `INSERT chats` → `INSERT chat_members` (все участники одним запросом) → `COMMIT` | неизвестный участник вызывает FK-ошибку **после** вставки чата; откат удаляет и чат, и частичное членство |
| Сообщение (lab3, с ключом) | проверка членства → `INSERT idempotency_keys … ON CONFLICT DO UPDATE … WHERE ключ старше 24 ч` → если вставлен: `UPDATE chats … RETURNING` → `INSERT messages`; если нет: прочитать сохранённое сообщение и сравнить отпечаток → `COMMIT`. По умолчанию всё это — одна SQL-функция `post_message` в autocommit (одно обращение к БД) | ключ, сообщение и «результат» коммитятся вместе или не коммитятся вовсе: «висящего» ключа нет. Конкурентный повтор ждёт на уникальном индексе завершения первой транзакции и затем видит её результат (READ COMMITTED, новый снимок на каждый оператор). Другое тело → 409, тот же — тот же Message |
| Сообщение с `attachment_ids` (lab4, lab5) | функция `post_message_v3` (0005): проверка членства → проверка вложений (этого чата, не `pending`; `failed`/карантин → 409; `FOR SHARE`) → только если всё хорошо — захват ключа → `UPDATE chats` → `INSERT messages (…, attachment_ids)` → `INSERT message_attachments` | чужое/неизвестное/незавершённое вложение — 404, в карантине — 409, ключ при этом не «сгорает». Порядок `attachment_ids` хранится массивом в строке сообщения: страница истории остаётся одним диапазонным сканом индекса |
| Загрузка вложения (lab5) | `INSERT attachments … 'pending'` (autocommit) → S3 PUT в staging (Content-MD5) → **одна транзакция**: `UPDATE … SET status='queued' WHERE status='pending'` + `INSERT jobs` + `INSERT outbox` + `INSERT job_events` → 202 | 202 только когда оригинал в staging и задание с outbox зафиксированы. Сбой до COMMIT оставляет невидимый `pending`, его убирает janitor. Компенсации в обработчике нет |
| Claim (worker) | `SELECT jobs … FOR UPDATE` → решение (no-op / superseded / работа) → `SELECT attachments … FOR UPDATE` → `UPDATE jobs` (processing, attempt+1, lease, token) + `INSERT job_attempts` + `UPDATE attachments` (processing) + событие | дубль доставки видит конечное состояние или чужой lease и ничего не делает |
| Результат (worker) | `SELECT jobs … FOR UPDATE` (проверка токена) → `SELECT attachments … FOR UPDATE` → если версия не новее опубликованной: `superseded`; иначе `INSERT attachment_variants` ×3 + `UPDATE attachments` (ready, published_version, object_key) + `UPDATE jobs/job_attempts` + событие → потом ack | результат публикуется атомарно и только владельцем текущей аренды; версия только растёт |
| Retry / failed (worker), lease (relay) | под блокировкой задания: попытка `retry`/`failed`/`abandoned`; задание `queued` с `available_at` + новая строка outbox, или `failed` (реестр) | повтор идёт тем же путём outbox; бесконечного немого retry нет |
| Replay / reprocess (jobctl), уборка staging | `SELECT attachments … FOR UPDATE` (одна и та же блокировка) → проверки → новое задание + outbox, либо `staging_state='deleting'` | уборка и replay сериализованы строкой вложения |
| Порядок блокировок | везде, где нужны обе строки: сначала `jobs`, потом `attachments` | нет взаимных ожиданий в разном порядке |
| Сообщение (lab2-часть) | проверка членства → `UPDATE chats SET last_message_at = greatest(clock_timestamp(), last_message_at + 1 мкс) RETURNING` → `INSERT messages` → `COMMIT` | строка чата заблокирована до конца транзакции, поэтому писатели одного чата идут по очереди. Время сообщений строго растёт **в порядке коммитов**: страница по cursor не пропустит сообщение, закоммиченное «задним числом» |
| Вход | `SELECT` пользователя, проверка Argon2id, запись сессии | неверный пароль ничего не пишет |
| Logout | `DELETE` сессии (или `DEL` в Valkey) | повтор с тем же токеном — 401 |
Чтение истории не требует snapshot между HTTP-запросами (так в контракте): новое сообщение появится на следующей странице. Список чатов сортируется по `chats.created_at = clock_timestamp()` без блокировки. Два чата, создаваемые одновременно, могут закоммититься не в порядке времени. Тогда у обхода, который уже начался, такой чат может оказаться «до» cursor; новый обход его увидит. Чаты создаются редко, поэтому мы не сериализуем их глобальным замком; это ограничение описано в REPORT.md.
## Сессии
- Токен: `secrets.token_urlsafe(32)` — 256 бит случайности, в ответе 43 символа. В хранилище лежит только SHA-256 токена. Для случайного 256-битного значения быстрого хеша достаточно, медленный KDF нужен только для низкоэнтропийных паролей.
- `SESSION_STORE=valkey` (по умолчанию): ключ `session:<sha256-hex>`, значение `{user_id, expires_at}`. Срок жизни задаётся абсолютным `PXAT expires_at`, поэтому рестарт его не продлевает. Включён `appendonly yes` + `appendfsync always`: подтверждённые вход и logout сохраняются до ответа клиенту. Valkey — **единственное** хранилище сессий, это не кэш над PostgreSQL. Поэтому нет второй копии, которая могла бы «оживить» отозванный токен после отказа. Если Valkey недоступен, проверить сессию нельзя: защищённые запросы и logout получают 503, анонимный доступ не открывается.
- `SESSION_STORE=postgres`: таблица `sessions`, проверка `expires_at > now()` в запросе.
+80
View File
@@ -0,0 +1,80 @@
# Защита lab7 — ответы на вопросы README
## 1. Какая часть mTLS проверяет шифрование, какая идентичность и где разрешение на действие?
Возьмём связь LB → API. На ней три разных проверки, и каждая отвечает на свой вопрос.
1. **Шифрование и подлинность сервера** — TLS-рукопожатие и проверка сертификата **сервера**.
* Ключ сессии согласуется через ECDHE, дальше трафик шифруется AEAD-шифром (TLS 1.2+/1.3).
* HAProxy проверяет, что сертификат реплики подписан `internal-ca` и в нём SAN `api` (`ssl verify required ca-file ... verifyhost api`). Посредник без ключа `api` ничего не прочитает и не выдаст себя за API.
2. **Идентичность клиента** — вторая половина mTLS, в двух шагах.
* a) **Цепочка.** Контекст API настроен с `CERT_REQUIRED` и доверяет только `internal-ca`. Без сертификата или с сертификатом чужого CA рукопожатие не завершается. Это говорит только о том, что сертификат выпустил наш CA.
* b) **Allowlist identity.** `MtlsHttpProtocol.connection_made` в `src/messenger/tls.py` сверяет DNS SAN клиентского сертификата с `MTLS_ALLOWED_CLIENTS=lb`. Если не совпало — `transport.abort()` до первого байта HTTP, а в логе запись `mtls_identity_rejected`.
3. **Разрешение на действие** — уже не TLS, а приложение.
* Bearer-сессия пользователя (`authenticate`) говорит, *кто из пользователей* просит.
* Проверка членства в чате (SQL) говорит, *можно ли ему* это сделать. Посторонний получает 404.
* mTLS доказывает, что запрос пришёл от *процесса LB*, но не даёт прав ни одному пользователю. Поэтому `X-User-Id` по-прежнему игнорируется.
Доказательство: `make mtls-check`, по каждой реплике, TLS 1.3 и 1.2:
| Клиент | Результат | Какой уровень отказал |
| --- | --- | --- |
| без сертификата | отказ | 2a |
| `foreign-ca`, SAN `lb` | отказ | 2a (имя правильное, CA чужой) |
| `internal-ca`, SAN `worker` | отказ | 2b, в логе `client_san=["worker"]` |
| `internal-ca`, SAN `lb` | 200 | — |
Аналогия: TLS — бронированный фургон, который нельзя вскрыть по дороге. CA — отдел кадров, выдающий пропуска. Allowlist — список «на этот этаж с пропуском пускать только инкассаторов». Сессия — подпись клиента на платёжке.
## 2. Почему доверенный CA ещё не означает, что любой его клиент может быть LB?
* Наш `internal-ca` выпускает сертификаты всем сервисам: `api`, `relay`, `worker`, `otel-collector`, `grafana`, `prometheus` и другим. Цепочка у всех правильная.
* Если API проверяет только цепочку, «быть LB» может любой, у кого есть любой ключ этого CA. Например, взломанный worker: он в своей сети, у него есть свой валидный сертификат.
* Такой процесс пошёл бы в API мимо HAProxy:
* обошёл бы ограничение частоты входа (подставил бы свой `X-Forwarded-For`);
* обошёл бы лимиты LB;
* получил бы канал к API, которого по модели у него нет.
* Поэтому сервер проверяет **роль** — SAN `lb` — а не только факт подписи. Тест: сертификат `worker` от нашего CA → отказ.
Альтернатива — отдельный CA только для LB-клиентов. Цепочка тогда сама означает «LB», но это хуже:
* Identity держится на дисциплине выпуска. Достаточно случайно подписать этим CA второй сертификат, и он тоже станет «LB»: в конфигурации API нигде не видно, кому именно можно.
* Каждой новой роли нужен новый CA.
* Allowlist по SAN явный, проверяемый тестом и меняется одной переменной.
Тот же принцип в Prometheus: `client_allowed_sans: [otel-collector, grafana, prometheus]`. Сертификат worker от того же CA туда не пускают — это проверяет тест.
## 3. Где хранится первый секрет для доступа к OpenBao и кто имеет право unseal?
* **Первый секрет — это `secret_id` AppRole.**
* Его выпускает оператор (`scripts/bao_operator.py bootstrap`) в `./secrets/bao/<svc>_secret_id`: вне Git, вне образов, папка 0700.
* Монтируется он только в свой сервис как Docker secret `/run/secrets/bao_secret_id`.
* Рядом лежит `role_id` — это не секрет, а имя роли.
* Вход требует **обе** части. Он даёт токен с одной политикой (`read messenger/data/<svc>`), TTL 1 ч, без default policy. Сервис читает свой путь и тут же отзывает токен (`revoke-self`).
* Срок жизни secret_id — 30 дней: учебный компромисс уровня 3. На уровне 4 был бы короткий secret_id с response wrapping или cert-auth.
* **Unseal может только оператор.**
* При `init` создаются 3 доли ключа (Shamir, порог 2) и root token.
* Они лежат в `~/.mtusi-lab7-operator/<project>/` с правами 0600: вне репозитория, вне volume OpenBao и вне всех контейнеров. В команде доли были бы у трёх разных людей.
* Root token нужен только для настройки. Он передаётся в CLI через stdin и никогда не попадает в приложение — это проверяет `make bao-check` с положительным контролем.
## 4. Что происходит при истечении credentials, остановке OpenBao и рестарте API?
| Событие | Что видит система | Почему так |
| --- | --- | --- |
| Истёк токен сервиса | ничего | токен отзывается через секунды после старта; секреты в памяти процесса; TTL 1 ч — верхняя граница, если отзыв не удался |
| Истёк secret_id | новый процесс получает 400 при входе и не стартует; работающие продолжают | оператор: `bao_operator.py new-secret-id <svc>` + пересоздать сервис |
| Истекла сессия пользователя | 401 `Bearer realm="messenger"` | TTL в Valkey проверяется при каждом запросе; рестарт TTL не продлевает |
| Истёк leaf-сертификат | новые TLS-соединения отказываются (рукопожатие) | перевыпуск `init_pki.py` + пересоздать сервис; CA остаётся |
| OpenBao остановлен или sealed | работающие api/relay/worker обслуживают запросы; новая реплика пишет `openbao_unavailable`, ждёт 60 с, падает, Docker перезапускает её, пока не будет unseal | секреты нужны только при старте; доказано в `test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones` |
| Рестарт OpenBao | он запечатан, нужен `bao_operator.py unseal`; данные на месте (raft на volume `baodata`) | `scripts/restart.sh` делает это после рестарта хранилищ; `make test-persistence` PASS |
| Рестарт API | новый процесс: AppRole login → свой путь → revoke; новый случайный `X-Instance-Id`; unseal не нужен | `make test-failover`: реплика остановлена и восстановлена, запросы шли через вторую |
## Короткие фразы для защиты
* **PKI:** «Два CA. Публичный знают только клиенты, внутренний — только сервисы; ключи CA не лежат ни в одном контейнере.»
* **mTLS:** «Подпись CA — это пропуск, allowlist SAN — список допущенных ролей, сессия — права пользователя.»
* **PostgreSQL:** «Шесть ролей, никто из сервисов не суперпользователь, `pg_hba` принимает только `hostssl`; GRANT выписаны по коду, а worker не видит даже таблицу users.»
* **OpenBao:** «Не dev, raft на volume, TLS. AppRole на каждый сервис, токен живёт секунды, root token и доли — у оператора вне репозитория.»
* **Argon2id:** «Параметры m=19 MiB, t=2, p=1 выбраны замером в контейнере API с лимитом 1 CPU. Это 30–50 мс на вход при 1 CPU; более тяжёлые давали 70–250 мс и 2–14 входов в секунду на реплику, то есть дешёвый DoS.»
* **Лимит входа:** «Счётчик неудач в Valkey, общий для реплик, проверяется до Argon2; при блокировке даже верный пароль получает 429, иначе блокировка подсказывала бы, что пароль угадан.»
* **Hardening:** «Везде `cap_drop: ALL` и `no-new-privileges`, app/worker с uid 10001 и нулевыми capabilities; наружу только 8443 и 3000, оба HTTPS на loopback.»
+109
View File
@@ -0,0 +1,109 @@
# Наблюдаемость: схема сигналов (lab 6)
## Путь данных
```
api ×2 ─┐ ┌─► Prometheus 3.16 (метрики + recording/alert rules, том promdata)
relay ─┼─ OTLP/HTTP protobuf ─► otel-collector ─┼─► Loki 3.7 (логи, том lokidata)
worker ─┘ :4318, сеть telemetry 0.165 contrib └─► Tempo 2.10 (трассы, том tempodata)
▲
Grafana 13.2 (https 127.0.0.1:3000) ──────┘ datasources с фиксированными UID,
dashboard из Git (provisioning)
Prometheus сам опрашивает (scrape) по HTTPS с клиентским сертификатом: loki, tempo, себя. Собственные метрики Collector (lab 7) приходят OTLP push по mTLS, pull-порт :8888 убран (у него не было TLS).
```
| Компонент | Зачем | Что хранит / делает | Где конфиг |
| --- | --- | --- | --- |
| OpenTelemetry SDK (Python 1.45.2) | Создаёт сигналы в процессе | spans, metrics, log records → OTLP | `src/messenger/telemetry.py` |
| OTel Collector contrib 0.165.0 | Принять, ограничить, сгруппировать, разослать | **ничего не хранит**: memory_limiter → batch → 3 exporter-а с ограниченной очередью | `infra/otel/collector.yaml`, `traces-*.yaml` |
| Prometheus 3.16.0 | Метрики: «сколько и как быстро» во времени | TSDB 15 дней / 2 GB; OTLP receiver; правила SLI и алертов | `infra/prometheus/` |
| Loki 3.7.10 | Логи: «что именно произошло» | строки + structured metadata, 7 дней | `infra/loki/loki.yaml` |
| Tempo 2.10.10 | Трассы: «где по пути ушло время» | spans, 72 ч, поиск TraceQL | `infra/tempo/tempo.yaml` |
| Grafana 13.2.6 | Интерфейс и запросы | только свою БД настроек (том grafanadata); данные не хранит | `infra/grafana/` |
Grafana не хранит сигналы — она спрашивает три хранилища. Collector не долговременная БД: при недоступном backend он держит ограниченную очередь (100 пачек на exporter) и повторяет до 60 с, потом **отбрасывает и считает** (`otelcol_exporter_send_failed_*`).
## Ресурсные атрибуты
| Атрибут | Значение | Откуда |
| --- | --- | --- |
| `service.name` | `messenger-api`, `messenger-relay`, `messenger-worker` | `telemetry.setup()` (+ `OTEL_SERVICE_NAME` в compose) |
| `service.version` | `1.6.0` | `messenger.__version__` |
| `service.instance.id` | hostname контейнера = `X-Instance-Id` | `Settings.instance_id` |
| `deployment.environment.name` | `lab` | `OTEL_RESOURCE_ATTRIBUTES` |
В Prometheus: `job` = service.name, `instance` = service.instance.id (так делает OTLP receiver), `deployment_environment_name` и `service_version` — promoted labels. В Loki индексные метки: `service_name`, `service_instance_id`, `deployment_environment_name`.
## Метрики: контракт → имя в SDK → имя в Prometheus
Prometheus переводит имена OTel с суффиксами единиц и типа (`UnderscoreEscapingWithSuffixes`): точка → `_`, единица `s` → `_seconds`, счётчик → `_total`.
| Сигнал контракта (уровень) | Инструмент SDK, единица | В Prometheus | Атрибуты (labels) |
| --- | --- | --- | --- |
| HTTP requests, counter (3) | `_count` гистограммы ниже (второго инструмента нет) | `http_server_request_duration_seconds_count` | `http_request_method`, `http_route` (шаблон), `http_response_status_code`, `http_response_status_class` |
| HTTP duration, histogram s (3) | `http.server.request.duration`, s | `http_server_request_duration_seconds_bucket/_sum/_count` | те же; buckets 1 мс…10 с |
| Jobs processed / failed (3) | `messenger.jobs.processed`, {job} | `messenger_jobs_processed_total` | `messenger_job_type`, `outcome` (succeeded, retry, failed, fenced, superseded, released, deferred, cancelled, rejected, noop_*) |
| Job processing duration (3) | `messenger.job.duration`, s | `messenger_job_duration_seconds_*` | `messenger_job_type`, `outcome` |
| Queue depth (4) | `messenger.queue.depth`, {job} (relay, из PostgreSQL) | `messenger_queue_depth` | `messaging_destination_name`, `state` (queued/processing) |
| Oldest job age (4) | `messenger.queue.oldest_age`, s | `messenger_queue_oldest_age_seconds` | `messaging_destination_name` |
| Outbox (диагностика брокера) | `messenger.outbox.pending`, `messenger.outbox.oldest_age` | `messenger_outbox_pending`, `messenger_outbox_oldest_age_seconds` | `state` (due/delayed) |
| DB pool (4) | `db.client.connection.count/max/pending_requests` | `db_client_connection_count` и т. д. | `db_client_connection_pool_name`, `db_client_connection_state` |
| DB время (4, диагностика) | `db.client.operation.duration`, `db.client.connection.wait_time`, s | `db_client_operation_duration_seconds_*`, `db_client_connection_wait_time_seconds_*` | `db_operation_name` (имя функции кода), `outcome`, pool |
| Worker saturation (4) | `messenger.worker.busy` / `messenger.worker.capacity` | `messenger_worker_busy`, `messenger_worker_capacity` | — |
| CPU/RAM (4) | `container.cpu.time` (s), `container.memory.usage/limit` (By), `process.memory.usage` | `container_cpu_time_seconds_total`, `container_memory_usage_bytes` … | — (job/instance) |
| End-to-end time to ready (4) | `messenger.attachment.time_to_ready`, s | `messenger_attachment_time_to_ready_seconds_*` | `messenger_job_kind` |
| HTTP в работе | `http.server.active_requests` | `http_server_active_requests` | `http_request_method` |
| Цена телеметрии (трек 1) | `messenger.telemetry.spans.ended/exported` | `messenger_telemetry_spans_ended_total`, `…_exported_total` | `result` |
CPU/RAM контейнера читаются из cgroup v2 (`/sys/fs/cgroup/cpu.stat`, `memory.current`) — те же числа, что у `docker stats`, вместе с дочерними процессами worker-а.
**Почему нет user_id/chat_id/message_id/attachment_id/request_id в labels.** Каждое новое значение label — новый временной ряд (своя запись в индексе, свои chunks в памяти). Чатов миллионы → миллионы рядов → памяти и диска Prometheus не хватит («cardinality explosion»). `http_route` — шаблон `/api/v1/chats/{chat_id}/messages`, неизвестные пути — одно значение `UNMATCHED`. Проверка: `student-tests/test_observability.py::test_no_ids_or_raw_paths_in_metric_labels`.
**Почему buckets свои.** Стандартные границы OTel (0, 5, 10, 25 … 10000) рассчитаны на миллисекунды; при единице «секунды» все запросы попали бы в один bucket 0–5 с, и p95 показал бы ~4,75 с при реальных 5 мс (так было у других студентов). Границы задаются на каждом инструменте (`explicit_bucket_boundaries_advisory`), проверка: `test_http_metric_attributes_are_low_cardinality_and_buckets_fit_seconds`.
**Перцентили** считаются только как `histogram_quantile(q, sum by (le) (rate(..._bucket[w])))` — buckets всех реплик складываются до вычисления. Усреднять p99 двух реплик нельзя: p99 — не линейная величина, у реплики с 10 запросами и реплики с 10 000 вес разный.
## Трассы
| Span | Kind | Процесс | Важные атрибуты |
| --- | --- | --- | --- |
| `POST /api/v1/chats/{chat_id}/attachments` (и все маршруты) | SERVER | api | `http.route`, `http.response.status_code`, `messenger.request_id`; ERROR только при 5xx |
| `db <функция>` | CLIENT | все | `db.system.name=postgresql`, `db.operation.name`, `db.client.connection.wait_time_ms` |
| `s3 put/get/head/delete/list`, `s3 download` | CLIENT / INTERNAL | api, worker | `aws.s3.bucket`, без ключа объекта |
| `messenger.jobs publish` | PRODUCER | relay | `messaging.*`, `messenger.job.id`, `messenger.job.attempt` |
| `messenger.attachment-jobs process` | CONSUMER | worker | `messenger.job.outcome`, `messenger.job.attempt`, `messenger.attachment.id`, `messenger.job.error_code` |
| `image render` | INTERNAL | worker | content type, размер, список вариантов |
**Как очередь переносит причинную связь.** В транзакции upload (`jobs.create_job`) текущий W3C context запроса сохраняется в `jobs.traceparent/tracestate` (миграция 0006). Relay публикует каждую строку outbox этого задания как PRODUCER span-потомок сохранённого контекста и кладёт **свой** `traceparent` в тело сообщения (поле `traceparent` из `contracts/jobs.schema.json`) и в AMQP headers. Worker извлекает его и создаёт CONSUMER span-потомок PRODUCER. Retry (через outbox) и истечение lease публикуются снова от того же сохранённого контекста — поэтому все попытки видны в одной трассе upload. Выбор parent-child, а не link: у одной логической работы один причинный предок, а задание из jobctl (без контекста) просто начинает новую трассу.
Без root span-ов из фоновых циклов: `db`/`s3` span создаётся, только если уже есть записываемый родитель (`telemetry.child_span`). `/health/*` не трассируется (HAProxy опрашивает каждую секунду), но учитывается в метриках.
## Логи
Каждая запись — OTLP log record: `timestamp`, `severity_text/number`, `service.name` (ресурс), `event` (= тело записи, короткое имя события: `request`, `attachment_queued`, `job_done`…), `trace_id`/`span_id` активного span-а и поля события (`request_id`, `route`, `status`, `job_id`, `outcome`…). В Loki они — structured metadata, не метки потоков. Тот же JSON с `trace_id`/`span_id` пишется в stdout (`docker compose logs`). Успешные health-пробы в Loki не отправляются (остаются в stdout).
Никогда не экспортируются: пароль, `Authorization`, session token, текст сообщения, байты изображения, ключи S3, signed URL, query string (cursor, filename), SQL. Проверка: `test_no_secrets_or_message_text_in_logs_and_traces`.
## Поведение при отказах телеметрии
| Что упало | Что происходит | Ограничение памяти | Как видно потери |
| --- | --- | --- | --- |
| Tempo / Loki / Prometheus | Collector копит пачки в `sending_queue` (≤100 на exporter), повторяет ≤60 с, потом отбрасывает | memory_limiter 400 MiB (soft 320), GOMEMLIMIT 360 MiB, лимит контейнера 512 MiB | `otelcol_exporter_send_failed_*`, алерт `TelemetryExportFailing` |
| Collector | SDK: экспорт в фоновом потоке, таймаут 3 с; очереди BatchSpanProcessor / BatchLogRecordProcessor по 2048 записей, лишнее отбрасывается | очереди SDK ограничены; запросы не ждут экспорта | `messenger_telemetry_spans_exported_total{result="failure"}` (доставится после восстановления), «дырка» в графиках |
| Grafana | Ничего: приложение о Grafana не знает | — | — |
Приложение не зависит от телеметрии: ни один сервис приложения не имеет `depends_on` на телеметрию, readiness API её не проверяет. Доказательства — в ЛР 6 (`evidence/incidents/` того репозитория); в ЛР 7 топология та же, только по TLS.
## Переменные окружения (`compose.yaml`, якорь `x-otel-env`)
| Переменная | По умолчанию | Смысл |
| --- | --- | --- |
| `OTEL_SDK_DISABLED` | `false` | `true` — телеметрия выключена (трек 1, baseline) |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `https://otel-collector:4318` (lab 7: + `OTEL_EXPORTER_OTLP_CERTIFICATE`, клиентский cert/key сервиса) | Collector |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf` | как в `.env.example` |
| `OTEL_EXPORTER_OTLP_TIMEOUT` | `3` (секунды) | таймаут одного экспорта |
| `OTEL_TRACES_SAMPLER` / `_ARG` | `parentbased_always_on` / `1.0` | head sampling |
| `OTEL_METRIC_EXPORT_INTERVAL` | `5000` мс | как часто SDK отправляет метрики |
| `OTEL_BSP_MAX_QUEUE_SIZE`, `OTEL_BLRP_MAX_QUEUE_SIZE` | `2048` | ограничение очередей span/log в процессе |
| `OTEL_SERVICE_NAME` | по сервису | задано в compose для api/relay/worker |
| `OTEL_RESOURCE_ATTRIBUTES` | `deployment.environment.name=lab` | ресурс |
+91
View File
@@ -0,0 +1,91 @@
# Инструкция оператора — lab7
Кто такой оператор: человек, у которого есть доступ к хосту и Docker. Только он держит:
* ключи CA (`./secrets/pki/*-ca.key`);
* root token и доли unseal OpenBao (`~/.mtusi-lab7-operator/<project>/`);
* файлы паролей (`./secrets/*`).
У приложения ничего из этого нет: у него только свой сертификат и свой AppRole.
Команды ниже для Git Bash/Linux. На Windows `python` — это `.venv/Scripts/python`; подробнее в [WINDOWS.md](WINDOWS.md).
## 1. Первый запуск из чистого clone
```sh
python -m venv .venv
.venv/Scripts/python -m pip install --require-hashes --no-deps -r requirements.txt # для unit-тестов
.venv/Scripts/python -m pip install -r requirements-test.txt # pytest, httpx2, cryptography
# 1) Пароли (по одному на сервис и роль) + PKI (два CA и сертификаты сервисов) -> ./secrets
.venv/Scripts/python scripts/init_secrets.py
# 2) OpenBao. Стартует ЗАПЕЧАТАННЫМ (sealed); dev-режима нет
docker compose up -d openbao
# 3) init (3 доли, порог 2) + unseal + KV/AppRole/политики + секреты + role_id/secret_id
.venv/Scripts/python scripts/bao_operator.py bootstrap
# 4) Весь стенд: сборка, миграции (один раз), bucket'ы, API x2, LB, relay, worker, телеметрия
docker compose up -d --build --wait
# 5) Проверка
make test CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/Scripts/python
```
То же короче: `make secrets up PYTHON=.venv/Scripts/python`.
Что создаётся и где лежит:
| Что | Где | Кто читает |
| --- | --- | --- |
| Ключи CA `public-ca.key`, `internal-ca.key` | `./secrets/pki/` (вне Git и образов; папка `./secrets` 0700) | только `init_pki.py`; в контейнеры не монтируются |
| Leaf-сертификат и ключ сервиса | `./secrets/pki/<service>.crt/.key` | только свой сервис, через compose `secrets:` (`/run/secrets/...`, read-only) |
| `public-ca.crt` | `./secrets/pki/` | любой клиент (`CA_FILE`); это не секрет |
| Пароли ролей БД, ключи S3, пароли RabbitMQ и Valkey | `./secrets/` | серверы (postgres, s3, broker, valkey), bootstrap-задачи (migrate, s3-init) и OpenBao KV. api/relay/worker файлов не получают |
| Root token, `unseal-share-1..3` | `~/.mtusi-lab7-operator/<COMPOSE_PROJECT_NAME>/` (0600, **вне репозитория**) | только оператор (`bao_operator.py`) |
| role_id/secret_id api/relay/worker | `./secrets/bao/` | только свой сервис |
Скрипты печатают только имена файлов, а не значения. Секреты попадают в CLI OpenBao через stdin `docker compose exec`: их нет в аргументах команд и в переменных окружения.
## 2. Ежедневная работа
| Ситуация | Что делать |
| --- | --- |
| Остановить стенд, сохранив данные | `docker compose stop` (или `down`, но **без** `-v`) |
| Запустить снова | `docker compose up -d openbao && python scripts/bao_operator.py unseal && docker compose up -d --wait` |
| Рестарт API / relay / worker | просто `docker compose restart api`: новый процесс заново входит по AppRole, unseal **не нужен** |
| Рестарт OpenBao (или всего хоста) | OpenBao запечатан. Уже работающие сервисы продолжают работу (секреты у них в памяти), новые реплики не стартуют, пока оператор не выполнит `python scripts/bao_operator.py unseal` |
| Проверить состояние OpenBao | `python scripts/bao_operator.py status` |
| Полный перезапуск всех процессов (хук теста) | `sh scripts/restart.sh` — в нём есть шаг unseal |
| Остановить одну реплику API (хук теста) и вернуть | `TARGET_INSTANCE_ID=<alias> sh scripts/stop-one.sh`, затем `make restore` |
| Чей это `X-Instance-Id`? | `docker compose exec api cat /tmp/instance_id` у каждой реплики (alias случайный, без hostname/IP) |
## 3. Что происходит при отказах
* **OpenBao sealed или остановлен.** Сервис при старте ждёт до `BAO_STARTUP_TIMEOUT_SECONDS` (60 с) и пишет `openbao_unavailable`. Потом завершается с ошибкой конфигурации, Docker его перезапускает, цикл повторяется до unseal. Healthcheck OpenBao (`bao status`) зелёный только у распечатанного сервера, поэтому `depends_on: service_healthy` не даёт `docker compose up` запустить api/relay/worker к запечатанному OpenBao.
* **Истёк токен сервиса.** Ничего не происходит: токен отзывается сразу после чтения (`revoke-self`), TTL 1 ч — только верхняя граница. Каждый новый процесс входит заново.
* **Истёк secret_id (30 дней).** Новый процесс получит 400 при входе и не стартует. Выпустить новый: `python scripts/bao_operator.py new-secret-id api`, затем `docker compose up -d --force-recreate api`.
* **Истёк leaf-сертификат (365 дней).** Удалить `secrets/pki/<service>.crt/.key` (для LB ещё `lb.pem`/`ingress.pem`), запустить `python scripts/init_pki.py`, пересоздать сервис. CA при этом сохраняется.
* **Потерян volume `baodata`.** Секреты пропали, но их источник — `./secrets`. Нужно убрать старый каталог оператора (он принадлежит удалённому хранилищу), заново выполнить `bao_operator.py bootstrap` и удалить `secrets/bao/*_secret_id`, чтобы выпустились новые.
## 4. Намеренное удаление учебных данных
```sh
docker compose down -v # ВСЕ volumes стенда: БД, S3, очередь, OpenBao
rm -rf secrets ~/.mtusi-lab7-operator/mtusi-lab7 # пароли, PKI, доли unseal и root token
```
После этого остаётся только первый запуск (раздел 1).
## 5. Второй (чистый) стенд рядом с рабочим
Порты 8443 и 3000 у обоих стендов одинаковые, поэтому рабочий стенд сначала останавливается (`docker compose -p mtusi-lab7 stop`). Чистый стенд разворачивается в отдельной папке со своим проектом:
```sh
git clone <fork> lab7-clean && cd lab7-clean && git checkout solution/bvt2302-bodanyuk
export COMPOSE_PROJECT_NAME=mtusi-lab7-clean # свои контейнеры, volumes, сети и свой каталог оператора
python -m venv .venv && .venv/Scripts/python -m pip install -r requirements-test.txt \
&& .venv/Scripts/python -m pip install --require-hashes --no-deps -r requirements.txt
make secrets up PYTHON=.venv/Scripts/python
```
+128
View File
@@ -0,0 +1,128 @@
# Pipeline обработки вложений (lab5)
Схема: [migrations/0005_pipeline.sql](../migrations/0005_pipeline.sql). Код: API — [attachments.py](../src/messenger/attachments.py), переходы заданий — [jobs.py](../src/messenger/jobs.py), relay — [relay.py](../src/messenger/relay.py), worker — [worker.py](../src/messenger/worker.py), картинки — [imaging.py](../src/messenger/imaging.py), версии — [pipeline.py](../src/messenger/pipeline.py), оператор — [jobctl.py](../src/messenger/jobctl.py), аудит — [audit.py](../src/messenger/audit.py).
## Кто что делает
```text
клиент ──POST──▶ LB ──▶ API ──(1) INSERT attachments 'pending' ──▶ PostgreSQL
│ (2) PUT оригинал в messenger-staging ──▶ S3 (staging)
│ (3) ОДНА транзакция: 'queued' + jobs + outbox ──▶ PostgreSQL
└─ 202 queued
relay: outbox ─(4) publish + publisher confirm─▶ RabbitMQ (quorum queue) ─(5) deliver─▶ worker
worker: (6) claim: lease + token попытки ─▶ (7) читает источник, сверяет SHA-256 ─▶ (8) варианты
в дочернем процессе ─▶ (9) PUT a/<id>/<token>/* в messenger-attachments ─▶
(10) ОДНА транзакция: варианты + attachment 'ready' (с проверкой токена) ─▶ (11) ack ─▶
(12) staging 'deleting' → S3 DELETE → 'deleted'
```
- **Источник истины — PostgreSQL**: состояние задания, попытки, lease, время следующей попытки (`available_at`), реестр failed, аудит (`job_events`). Брокер только доставляет `job_id`.
- **API не знает брокер** (нет даже сети `queue`). Брокер упал — upload всё равно 202, задания копятся в outbox.
- В сообщении только поля [jobs.schema.json](../contracts/jobs.schema.json): `schema_version, job_id, type, attachment_id, pipeline_version, attempt, created_at`. Никаких байтов, URL, ключей S3, имени файла. Worker берёт `content_type`, размер, SHA-256 и ключ источника из БД.
## Что сохранено в момент 202
1. Полный, **проверенный** оригинал лежит в приватном bucket `messenger-staging`: S3 подтвердил PUT и Content-MD5. Проверки 413/415 делаются до этого, синхронно, теми же валидаторами, что в lab4 (PNG — свой потоковый, JPEG — `djpeg -strict`).
2. Строка `attachments` в статусе `queued`, строка `jobs` (`queued`, attempt 0) и строка `outbox` — **в одной транзакции**, закоммичены (fsync PostgreSQL).
Значит, после 202 можно убить API, relay, broker и worker: работа восстановится из этих двух записей. Честная граница: staging — это уже S3, а не «временная папка». На одном Docker-хосте «устойчиво» значит «переживает рестарт процессов и контейнеров с volumes», а не потерю диска.
## Состояния
Вложение (`attachments.status`):
| Статус | Видно клиенту | Как попадает | Как выходит |
| --- | --- | --- | --- |
| `pending` | нет (404) | INSERT до PUT в staging | → `queued` (COMMIT задания) или удаляется janitor через `PENDING_GRACE_SECONDS` |
| `queued` | да, content 409 | COMMIT задания; retry; истёк lease; replay | → `processing` при claim |
| `processing` | да, content 409 | claim worker | → `ready` / `queued` (retry, lease) / `failed` |
| `ready` | да, варианты | COMMIT результата | никогда не возвращается назад. Reprocess новой версии не меняет статус |
| `failed` | да, `error_code`, content 409 | постоянная ошибка или попытки кончились | → `queued` только через `jobctl replay` |
Задание (`jobs.state`): `queued → processing → succeeded | failed | superseded`, `processing → queued` (retry, lease, graceful stop). `superseded` — старая версия pipeline, когда опубликована более новая.
Ограничения в самой БД (CHECK) не дают коду ошибиться:
- `attachments_active_has_source`: у `queued/processing` есть источник — опубликованный оригинал или staging в состоянии `present`. **Уборка физически не может пометить staging принятой работы**;
- `jobs_lease`: lease есть ровно тогда, когда `processing`;
- `jobs_one_active`: одно активное задание на `(attachment, pipeline_version)`;
- PK `attachment_variants (attachment_id, pipeline_version, name)` — ключ эффекта из контракта.
## Окна отказа (contracts/attachment-states.md)
| Окно | Что остаётся | Кто восстанавливает | Проверка |
| --- | --- | --- | --- |
| после staging, до записи задания | `pending` + объект staging, задания нет, 503 клиенту | janitor API: объект, потом строка (после grace) | `API_FAULT_POINTS=after_s3_put`, test_consistency |
| после COMMIT, до publish | строка outbox без `published_at` | relay при следующем проходе; никто не создаёт задание вручную | broker/relay остановлены, test_pipeline_flow |
| после publish, до записи confirm | сообщение в очереди + неотмеченная строка outbox | relay публикует ещё раз → дубль → no-op | `RELAY_FAULT_POINTS=crash_after_publish` |
| после записи S3, до COMMIT результата | объекты под ключами попытки 1, не опубликованы | lease истекает → reaper → попытка 2 со своими ключами; уборка удаляет ключи попытки 1 | `WORKER_FAULT_POINTS=crash_after_s3_write` |
| после COMMIT результата, до ack | `ready` | redelivery → claim видит `succeeded` → ack без работы | `WORKER_FAULT_POINTS=crash_after_commit` |
| worker умер/завис в processing | lease без продления | reaper (в relay, раз в 5 с) → `queued` + outbox; commit старой попытки отвергается токеном | `crash_after_claim`, `docker pause` |
## Publisher confirm ≠ consumer ack
- **Publisher confirm** (relay ← broker): «брокер принял сообщение и записал его в quorum log». Это граница «намерение передано в очередь»; после неё relay ставит `published_at`.
- **Consumer ack** (worker → broker): «результат работы устойчиво зафиксирован». Worker шлёт ack только **после COMMIT** результата (или после COMMIT решения «retry/failed/no-op»).
- Между ними может пройти сколько угодно времени и случиться любой сбой. Confirm без ack = сообщение ждёт в очереди; потеря ack = повторная доставка.
## Идемпотентность и повторная доставка
Доставка at-least-once: дубль может появиться из relay (crash до отметки), из брокера (нет ack из-за падения worker, разрыв соединения, consumer_timeout), от оператора. Поэтому каждая доставка начинается с `claim` под блокировкой строки `jobs`:
| Состояние задания | Решение | ack |
| --- | --- | --- |
| `succeeded/failed/superseded` | no-op (`noop_finished`) | да |
| `processing` (lease держит другой) | no-op (`noop_leased`), его смерть обработает reaper | да |
| `queued`, `available_at` в будущем | no-op (`noop_not_due`), outbox опубликует вовремя | да |
| `queued`, опубликована версия ≥ своей | `superseded` | да |
| `queued`, пора | claim: attempt+1, новый `lease_token`, строка `job_attempts` с заранее известными ключами | после результата |
Ключ идемпотентности задания — `job_id` (строка в БД), ключ эффекта — `(attachment_id, pipeline_version, variant)`. Объекты пишутся под ключами `a/<attachment>/<token>/<name>`: у каждой попытки свои. Опубликовано ровно то, на что ссылается COMMIT результата. **Fencing**: COMMIT проходит, только если `jobs.lease_token` всё ещё равен токену попытки. Reaper обнуляет токен, поэтому «проснувшаяся» старая попытка ничего не опубликует.
Это не exactly-once **доставка**. Сообщение может прийти несколько раз, а работа выполниться дважды (например, зависший worker досчитает варианты). Exactly-once — только **видимый эффект**: одна опубликованная запись на ключ эффекта, монотонная версия, мусор попыток убирается.
## Зависший vs долго работающий worker
- Долго работающий продлевает lease каждые `JOB_LEASE_SECONDS/3` (heartbeat в БД, `WHERE lease_token = мой`).
- Зависший (`docker pause`, deadlock, потеря сети к БД) не продлевает; через `JOB_LEASE_SECONDS` reaper возвращает задание.
- Worker, у которого жив heartbeat, но зависла обработка, ограничен `JOB_TIMEOUT_SECONDS`: дочерний процесс убивается, heartbeat перестаёт продлевать lease после этого срока.
- Если heartbeat узнал, что lease потерян, попытка отменяется сама. Даже если не отменилась — её COMMIT отвергнет fencing.
- Брокер со своей стороны: AMQP heartbeat 10 с закрывает соединение замороженного клиента и возвращает его неподтверждённые сообщения; `consumer_timeout` 5 мин — для подключённого, но не отвечающего ack.
## Retry, failed, replay
- `JOB_MAX_ATTEMPTS=5` claim-ов на задание. Backoff — full jitter: `uniform(0, min(JOB_RETRY_MAX_SECONDS, JOB_RETRY_BASE_SECONDS·2^(n−1)))`. Задержка хранится в `jobs.available_at` и строке outbox — повтор проходит тем же путём outbox → broker, без TTL-очередей.
- Постоянные ошибки (сразу `failed`): `invalid_image`, `image_too_large`, `source_missing`, `source_corrupt`. Временные: `storage_unavailable`, `processing_timeout`, `processing_killed`, `processing_failed`. Когда попытки кончились — `retry_exhausted`.
- Реестр failed — view `failed_jobs` (`jobctl list-failed`). DLQ RabbitMQ (`messenger.attachment-jobs.dlq`) — для «ядовитых» сообщений: не по схеме или превысили `x-delivery-limit=20`.
- Страховка от потерянного сообщения: `queued`-задание без claim и без публикаций дольше `QUEUED_REPUBLISH_SECONDS` получает новую строку outbox.
- `jobctl replay <id>`: только для `failed` с живым источником, создаёт **новое** задание `kind=replay, replay_of=<failed>`, пишет оператора и причину в `job_events`. Для `ready` — отказ `already_ready`, ничего не создаётся.
## Уборка (worker), всегда под блокировкой строки
- staging `ready` — сразу после COMMIT результата; staging `failed` — через `STAGING_RETENTION_SECONDS`. Порядок: под `UPDATE … WHERE <условие заново>` пометить `deleting` → S3 DELETE → `deleted`. Replay берёт ту же блокировку: либо replay первым (строка уже `queued`, уборка её пропустит), либо уборка первой (replay видит `deleting` и отказывает `source_missing`).
- Объекты попыток, которые не опубликовали результат (`retry/failed/abandoned/superseded`): удаляются по `planned_keys` через `ORPHAN_GRACE_SECONDS`. Перед этим проверяется, что токен не текущий и ни один ключ не опубликован. Новые результаты (replay, другая попытка) лежат под другими ключами — устаревший проход не может их удалить.
- `pending` без задания — janitor API (как в lab4).
- Опубликованные варианты старых версий pipeline сохраняются (ограничение, см. REPORT).
## Версии pipeline (трек 2)
Версия фиксируется в задании при создании (`PIPELINE_VERSION` для upload, `jobctl reprocess --pipeline N` для готового вложения). Версии 1/2/3 отличаются параметрами кодеков, геометрия — по контракту. Публикация: только если `N > published_version`; иначе `superseded`. Reprocess неготового вложения запрещён: его единственный источник — staging текущего задания.
## Лимиты worker
| Что | Чем |
| --- | --- |
| параллельность | prefetch = `WORKER_CONCURRENCY` (2) + семафор на дочерние процессы |
| bytes | размер из БД ≤ `MAX_UPLOAD_BYTES` проверяется до скачивания; длина и SHA-256 скачанного = БД |
| пиксели | `width×height` из заголовка ≤ `MAX_IMAGE_PIXELS` до декодирования; JPEG декодируется с DCT-масштабом (`draft`) |
| память | `RLIMIT_AS = IMAGE_MAX_MEMORY_MB` (768) у дочернего процесса; контейнер 1536m без swap |
| время | `JOB_TIMEOUT_SECONDS` (60): дочерний процесс убивается, lease перестаёт продлеваться |
## Варианты
| Вариант | Формат | Геометрия | Параметры v1 |
| --- | --- | --- | --- |
| thumbnail | JPEG baseline 4:2:0 | вписан в 256×256, без увеличения, округление вниз, ≥1 px | q=85, optimize |
| crop | JPEG | центральный квадрат → 128×128 (маленькие увеличиваются) | q=85 |
| optimized | WebP lossy | вписан в 1280×1280, без увеличения, alpha сохраняется | q=80, method=4 |
EXIF orientation применяется к пикселям; в варианты не копируются EXIF, XMP, ICC, комментарии. Пиксели считаются sRGB. Alpha при ресайзе — premultiplied (без цветных ореолов), для JPEG композится на белый. 16-битный серый масштабируется (`/257`), а не обрезается. Оригинал публикуется побайтно без изменений. Уменьшение размера маленьких файлов не обещается.
+70
View File
@@ -0,0 +1,70 @@
# Текст PR
**Заголовок:** `ЛР 7 — БВТ2302 — Боданюк — на 3`
**База:** `mtusi2026/mtusi2026lab7:main` ← `wfa/mtusi2026lab7:solution/bvt2302-bodanyuk`
---
## Лабораторная 7
Автор / группа: Боданюк Алексей, БВТ2302
Целевая оценка (3/4/5): 3
Трек 5, если заявлен: нет
**Что реализовано и что перенесено.** Перенесено решение ЛР 6 (первый коммит, без изменений): Python 3.13, Starlette/uvicorn, PostgreSQL 18, Valkey 8.1, HAProxy 3.2 (2 реплики API), SeaweedFS 4.46, RabbitMQ 4.3 (outbox, relay, worker, lease), OpenTelemetry → Collector → Prometheus/Loki/Tempo → Grafana.
Новое в ЛР 7:
* **PKI.** `scripts/init_pki.py`: `public-ca` для ingress и Grafana, `internal-ca` для сервисов, leaf на каждый сервис (SAN = имя compose). Ключи лежат вне Git и образов, каждому сервису монтируется только его пара.
* **Внешний HTTPS.** HAProxy на `127.0.0.1/[::1]:8443`, TLS 1.2+, открытого 8080 нет.
* **LB → API: обязательное mTLS с allowlist identity.** API требует клиентский сертификат `internal-ca` и после рукопожатия сверяет SAN с `lb` (`src/messenger/tls.py`). Docker-healthcheck ходит на loopback-listener.
* **TLS ко всем зависимостям с проверкой сервера:**
* PostgreSQL `verify-full`, в `pg_hba` только `hostssl`;
* Valkey только TLS-порт, ACL-пользователь `api`;
* RabbitMQ только AMQPS 5671;
* SeaweedFS S3 только HTTPS;
* OTLP → Collector с обязательным клиентским сертификатом;
* Collector/Grafana → Prometheus/Loki/Tempo по mTLS, у Prometheus allowlist SAN.
* **Минимальные права.** 6 ролей PostgreSQL с GRANT по коду (`migrations/0007_least_privilege.sql`), раздельные ключи S3 (admin только у `s3-init`), пользователи RabbitMQ publish-only / consume-only.
* **OpenBao 2.7.3.**
* Не dev-режим: raft на volume, TLS, audit в stdout.
* Вход по AppRole с отдельной политикой для api/relay/worker, у каждого свой путь KV. Сервис входит, читает свой путь и отзывает токен.
* Root token и доли unseal лежат у оператора вне репозитория (`scripts/bao_operator.py`).
* У приложения нет ни одного файла с паролем.
* **Argon2id** m=19 MiB / t=2 / p=1, формат PHC. Параметры выбраны замером в контейнере API (`bench/argon2_bench.py`).
* **Лимит неудачных входов.** Хранится в Valkey, общий для реплик: 429 + `Retry-After`, проверяется до Argon2.
* **Hardening.** Везде `cap_drop: [ALL]` и `no-new-privileges`; app/worker работают от uid 10001 с нулевыми capabilities; лимиты у всех контейнеров; наружу открыты только 8443 и 3000 (HTTPS, loopback).
* **`X-Instance-Id`** — случайный alias `i-<12 hex>`, без hostname/IP.
**Команды запуска из чистого clone** (подробно — REPORT.md, docs/OPERATOR.md, docs/WINDOWS.md):
```sh
python -m venv .venv && .venv/bin/python -m pip install -r requirements-test.txt
.venv/bin/python scripts/init_secrets.py # пароли + PKI -> ./secrets (вне Git)
docker compose up -d openbao # стартует sealed
.venv/bin/python scripts/bao_operator.py bootstrap # init/unseal/политики/секреты
docker compose up -d --build --wait
make test test-security CA_FILE=$PWD/secrets/pki/public-ca.crt
make mtls-check bao-check
```
**Результаты проверок и ссылка на REPORT.md:** см. таблицу «критерий → команда → результат → файл» в [REPORT.md](../REPORT.md) и [evidence/SUMMARY.md](../evidence/SUMMARY.md). Доказательства собраны из чистого clone в отдельной папке с отдельным `COMPOSE_PROJECT_NAME`.
**Ограничения / известные ошибки** (подробно — REPORT.md, «Ограничения»):
* уровень 4 не заявлен: нет ротации и отзыва leaf/secret, нет mTLS к брокеру, нет сканирования образов;
* SecretID живёт 30 дней;
* Loki/Tempo проверяют только цепочку CA, без allowlist SAN;
* четыре stateful-образа стартуют от root ради `chown` (оставлены CHOWN/SETUID/SETGID/DAC_OVERRIDE/FOWNER).
**Замечания к другим PR учтены.** Сгенерированные `secrets/` и учётные данные в Git не попадают (это проверяет тест); API не получает admin-ключ S3, bucket создаёт `s3-init`; сравнительная матрица разрешений S3/брокер/PostgreSQL есть в `contracts/trust-matrix.md`.
**Источники и использование ИИ:** документация OpenBao (AppRole, policies, production hardening), OWASP Password Storage, документация HAProxy, PostgreSQL, Valkey, RabbitMQ TLS, OpenTelemetry Collector, Prometheus web-config. Код, тесты, конфигурации и документы написаны с помощью ИИ-ассистента Claude (Anthropic). Решения разобраны и проверены мной; на защите объясняю их сам.
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [x] Контракт и публичные тесты не ослаблены.
- [x] make check и make test выполнены; приложен реальный вывод.
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
+54
View File
@@ -0,0 +1,54 @@
# Runbook: что делать, когда сработал алерт
Общий порядок: **метрика говорит «что и насколько», трасса — «где по пути», лог — «что именно случилось»**. Начинать с dashboard «Messenger lab 6» (Grafana, https://localhost:3000, CA `secrets/pki/public-ca.crt`), потом Explore → Tempo/Loki. Без Grafana: `python scripts/obs.py alerts|promql|search|trace|logs`.
## MessengerApiHighErrorRate
Больше 5 % бизнес-запросов отвечают 5xx.
1. Dashboard → «Error ratio» и «Requests per second by route»: какой маршрут даёт 5xx, все реплики или одна (`sum by (instance)`).
2. Логи предупреждений: `{service_name="messenger-api"} | detected_level=~"warn|error"` — смотреть `event`: `database_unavailable` (поле `op`), `s3_unavailable`, `unhandled_error`, `fault_injected`.
3. Трасса ошибочного запроса: Tempo, TraceQL `{ resource.service.name = "messenger-api" && status = error }`. Какой дочерний span красный и долгий:
* `db …` с `error.type = LockNotAvailable / QueryCanceled` → блокировка или медленный запрос в PostgreSQL (шаг 4);
* `db …` с `PoolTimeout` → пул исчерпан (см. MessengerDbPoolSaturated);
* `s3 …` с ошибкой → S3 (`docker compose ps s3`, логи s3);
* дочерних span-ов нет, сам SERVER красный → ошибка в коде (`unhandled_error`, stack в stdout реплики).
4. БД: `docker compose exec postgres psql -U messenger -d messenger -c "SELECT pid, wait_event_type, wait_event, state, now()-xact_start AS age, left(query,60) FROM pg_stat_activity WHERE state <> 'idle' ORDER BY age DESC"`. Долгая транзакция, держащая блокировку, — `pg_terminate_backend(pid)` (только чужой/зависший сеанс, после согласования).
5. Готово, когда ratio < 5 % и алерт resolved (≈ 1–2 мин после устранения).
## MessengerQueueLagGrowing
Старейшее незавершённое задание старше 60 с — загрузки не становятся ready.
1. Dashboard → «Queue depth», «Oldest job age», «Jobs handled per second by outcome», «Worker saturation».
* `jobs succeeded/s = 0`, busy = 0 → **worker не работает**: `docker compose ps worker`, `docker compose logs --tail 50 worker`; поднять `docker compose start worker`.
* busy/capacity ≈ 100 %, succeeded/s > 0 → **worker не успевает** (насыщение): рост загрузок или медленная обработка («Job duration p95»); масштабировать `docker compose up -d --scale worker=2` или поднять `WORKER_CONCURRENCY`.
* много `retry`/`failed` в outcome → обработка падает: логи `{service_name="messenger-worker"} | event="attempt_failed"` (поле `code`), трасса `{ span.messenger.job.outcome = "retry" }`.
* «oldest due outbox row» растёт → не публикуется: брокер или relay (`docker compose ps broker relay`, лог `publish_failed`).
2. После устранения backlog должен уменьшаться («Queue depth» вниз), алерт — resolved.
## MessengerApiLatencyHigh
p99 бизнес-запросов > 1 с в течение 2 минут. Главный вопрос: **медленная БД или медленный код обработчика?**
1. Сравнить на dashboard «Latency p50/p95/p99» с «DB unit of work p95» и «DB pool wait p95».
* DB p95 вырос вместе с HTTP, есть ожидание пула → **БД** (блокировки, тяжёлый запрос, нехватка соединений): дальше как в шаге 4 MessengerApiHighErrorRate.
* DB p95 прежний (единицы мс), HTTP p99 вырос → **код обработчика / CPU реплики**: «Container CPU», «Requests in flight».
2. Подтвердить трассой: TraceQL `{ resource.service.name = "messenger-api" && kind = server && duration > 1s }`. Время внутри дочернего `db …` span-а → БД; длинный SERVER span с короткими детьми (пустой промежуток) → код самого обработчика.
3. Проверить, не включены ли экспериментальные отказы: `docker compose exec api printenv FAULT_POINTS`.
## MessengerDbPoolSaturated
Запросы ждут свободное соединение PostgreSQL. Соединения заняты дольше обычного (медленные запросы, блокировки) или пул мал для нагрузки. Смотреть «DB pool: used / max, waiting» по `job`, затем `pg_stat_activity` (как выше). Увеличивать `DB_POOL_MAX` только после того, как исключены блокировки: больше соединений к заблокированной таблице лишь удлинят очередь.
## MessengerQueueMetricsAbsent
Нет метрик очереди: relay не работает или не может читать БД. `docker compose ps relay`, `docker compose logs --tail 50 relay` (события `database_unavailable`, `publish_failed`). Пока алерт активен, MessengerQueueLagGrowing **не может сработать** — очередь не наблюдается.
## TelemetryExportFailing
Collector не может отправить данные в Tempo/Loki/Prometheus (`exporter` в метках алерта). Приложение не затронуто, но наблюдения теряются после заполнения очереди (≤100 пачек, ≤60 с повторов).
1. `docker compose ps tempo loki prometheus`, `up{job=~"tempo|loki|prometheus"}` на dashboard.
2. Поднять backend: `docker compose start tempo loki`.
3. Оценить потерю: прирост `otelcol_exporter_send_failed_spans` / `_log_records` за время отказа (панель «Collector: spans accepted / sent / failed»).
+32
View File
@@ -0,0 +1,32 @@
# SLI, SLO и алерты (lab 6, уровень 4)
Окна укорочены под учебный стенд: в продакшене SLO берут на 28–30 дней, здесь — 1 час, чтобы результат был виден за время защиты.
## SLI и SLO
| SLO | SLI (что меряем) | Цель | Окно | Запрос (recording rule) |
| --- | --- | --- | --- | --- |
| Доступность API | доля бизнес-запросов (все маршруты, кроме `/health/*`), ответивших **не 5xx** | ≥ 99 % | 1 ч | `1 - messenger:http_error_ratio:rate1h` |
| Скорость API | доля бизнес-запросов быстрее 250 мс (bucket `le="0.25"`) | ≥ 95 % | 5 мин | `messenger:http_fast_ratio:rate5m` |
| Время до ready | доля загрузок, ставших ready за ≤ 30 с от 202 (bucket `le="30"`) | ≥ 99 % | 1 ч | `messenger:ready_within_30s_ratio:rate1h` |
**Числитель и знаменатель ошибок.** Числитель — ответы 5xx (500, 503); знаменатель — все бизнес-запросы. 4xx не ошибка сервиса: неверный пароль, чужой чат (404), повтор ключа с другим телом (409) — правильный ответ на неправильный запрос. Health-пробы исключены: их шлёт инфраструктура, не пользователь.
**Почему 250 мс и 30 с.** На стенде p95 бизнес-запросов около 10–60 мс, p99 < 150 мс (dashboard, нагрузка `tests/load.py`), так что 250 мс — запас в несколько раз, но медленная БД (секунды) его нарушает. Публичный smoke ждёт ready до 60 с; обычная обработка — около 1–2 с, поэтому 30 с ловит остановленный или перегруженный worker раньше, чем клиент сдастся.
**Что значит 99 % за час.** Бюджет ошибок — 1 % запросов. При 10 запросах в секунду это 360 ошибочных ответов в час; полный отказ API «съедает» такой бюджет за 36 секунд.
## Алерты (`infra/prometheus/rules/alerts.yml`)
| Алерт | Условие | `for` | Связь с SLO | Runbook |
| --- | --- | --- | --- | --- |
| `MessengerApiHighErrorRate` | 5xx/все за 1 мин > 5 % и трафик > 0,2 req/s | 1 мин | доступность: 5 % ошибок съедают часовой бюджет за 12 мин | [RUNBOOK](RUNBOOK.md#messengerapihigherrorrate) |
| `MessengerQueueLagGrowing` | старейшее незавершённое задание > 60 с и есть queued | 1 мин | время до ready (30 с) уже нарушается | [RUNBOOK](RUNBOOK.md#messengerqueuelaggrowing) |
| `MessengerApiLatencyHigh` | p99 бизнес-запросов за 2 мин > 1 с | 2 мин | скорость API | [RUNBOOK](RUNBOOK.md#messengerapilatencyhigh) |
| `MessengerDbPoolSaturated` | есть ожидающие соединения с БД | 1 мин | причина обоих выше | [RUNBOOK](RUNBOOK.md#messengerdbpoolsaturated) |
| `MessengerQueueMetricsAbsent` | нет метрики очереди 2 мин | 2 мин | очередь не наблюдается вообще | [RUNBOOK](RUNBOOK.md#messengerqueuemetricsabsent) |
| `TelemetryExportFailing` | Collector не может отправить в backend | 30 с | сама наблюдаемость деградировала | [RUNBOOK](RUNBOOK.md#telemetryexportfailing) |
Время обнаружения ≈ время, пока условие станет истинным по окну rate (до 1 мин) + `for` + до 15 с интервала вычисления. Порог «трафик > 0,2 req/s» убирает ложное срабатывание на пустом стенде, где одна ошибка из пяти запросов — уже 20 %.
Доставки наружу нет (нет Alertmanager): состояния pending → firing → resolved видны в Prometheus (`/api/v1/alerts`, ряд `ALERTS`), на dashboard (панели «Alerts firing» и таблица) и через `python scripts/obs.py alerts`. Проверка искусственными отказами проводилась в ЛР 6 (`bench/incidents.py` там); в ЛР 7 инциденты уровня 4 не повторялись.
+106
View File
@@ -0,0 +1,106 @@
# Запуск на Windows и сценарий защиты ЛР 7
Команды — в **PowerShell** из папки проекта (где лежит `compose.yaml`). Переменные `$env:...` действуют до закрытия окна.
## 1. Что установить один раз
| Программа | Зачем | Важно |
| --- | --- | --- |
| [Git for Windows](https://git-scm.com/download/win) | clone и Git Bash | путь по умолчанию `C:\Program Files\Git`: оттуда `scripts\*.cmd` запускают `.sh`-хуки и проверки |
| [Docker Desktop](https://www.docker.com/products/docker-desktop/) | весь стенд: 16 сервисов (ЛР 6 + OpenBao) | backend WSL 2; Settings → Resources ≥ 4 CPU и ≥ 10 ГБ RAM |
| [Python 3.12+](https://www.python.org/downloads/windows/) | PKI, secrets, оператор OpenBao, тесты | галочка **Add python.exe to PATH** |
| GNU make (необязательно) | `make test/...` | `winget install ezwinports.make`; в каждом окне `$env:Path += ";C:\Program Files\Git\usr\bin"` |
Если Docker пишет `all predefined address pools have been fully subnetted`, значит, сети старых стендов заняли все подсети. Удалите сети стендов, которые сейчас не нужны: `docker network rm <имя>`. Тома с данными при этом не трогаются, а `docker compose up` создаст сети заново.
## 2. Развернуть (заранее)
```powershell
git clone https://gitea.privcloud.tech/wfa/mtusi2026lab7 mtusi2026lab7
cd mtusi2026lab7
git checkout solution/bvt2302-bodanyuk
python -m venv .venv
.venv\Scripts\python -m pip install --require-hashes --no-deps -r requirements.txt
.venv\Scripts\python -m pip install -r requirements-test.txt # pytest, httpx2, cryptography (PKI)
$env:PYTHONUTF8 = "1"
.venv\Scripts\python scripts\init_secrets.py # пароли + PKI -> .\secrets
docker compose up -d openbao # стартует запечатанным
.venv\Scripts\python scripts\bao_operator.py bootstrap # init/unseal/политики/секреты
docker compose up -d --build --wait
```
Root token и доли unseal окажутся в `%USERPROFILE%\.mtusi-lab7-operator\mtusi-lab7\`: вне папки проекта и вне Git.
Порты 8443 и 3000 должны быть свободны. Стенды других лабораторных останавливайте через `docker compose -p <проект> stop`, без `down -v`.
## 3. Перед защитой
```powershell
$env:PYTHONUTF8 = "1"
$env:CA_FILE = (Resolve-Path secrets\pki\public-ca.crt).Path
docker compose up -d openbao; .venv\Scripts\python scripts\bao_operator.py unseal; docker compose up -d --wait
python tests\smoke.py --ca-file $env:CA_FILE # = make test
```
* Grafana: **https://localhost:3000**. Браузер не знает учебный CA, поэтому предупредит о сертификате. Чтобы предупреждения не было, нужно добавить `secrets\pki\public-ca.crt` в «Доверенные корневые центры» текущего пользователя (`certmgr.msc`), а после защиты удалить.
* Пользователь Grafana — `admin`, пароль — `Get-Content secrets\grafana_admin_password`.
## 4. Сценарий защиты README — по шагам
**Шаг 1. Развернуть с нуля и `make test` по HTTPS.**
```powershell
docker compose down -v; Remove-Item -Recurse secrets, "$env:USERPROFILE\.mtusi-lab7-operator\mtusi-lab7" # ТОЛЬКО для чистого листа: удаляет учебные данные
.venv\Scripts\python scripts\init_secrets.py
docker compose up -d openbao
.venv\Scripts\python scripts\bao_operator.py bootstrap
docker compose up -d --build --wait
python tests\smoke.py --base-url https://localhost:8443 --ca-file $env:CA_FILE
```
**Шаг 2. `make test-security`: недоверенный CA отклоняется; ACL и logout.**
```powershell
python tests\security.py --ca-file $env:CA_FILE
.venv\Scripts\python -m pytest student-tests\test_security.py -k "ingress or plaintext" -v
.venv\Scripts\python -m pytest student-tests\test_api.py -k "foreign_chat or logout or x_user_id" -v
```
**Шаг 3. Внутреннее mTLS LB → API.**
```powershell
scripts\mtls_check.cmd
```
По каждой реплике: без сертификата, с чужим CA и с сертификатом `worker` — отказ; с `lb` — 200. В конце печатаются строки лога API `mtls_identity_rejected`.
**Шаг 4. OpenBao, рестарт с сохранением данных, отказ реплик.**
```powershell
scripts\bao_check.cmd # allow/deny + root token в app отсутствует
.venv\Scripts\python scripts\bao_operator.py status
python tests\resilience.py --mode persistence --action-script scripts\restart.cmd --ca-file $env:CA_FILE
python tests\resilience.py --mode failover --action-script scripts\stop-one.cmd --ca-file $env:CA_FILE
bash scripts/restore-api.sh # вернуть остановленную реплику
python tests\resilience.py --mode failover --action-script scripts\stop-one.cmd --ca-file $env:CA_FILE
bash scripts/restore-api.sh
```
Тест failover сам выбирает реплику, обслужившую запрос. Если второй прогон остановил ту же реплику (видно в `docker compose ps -a api`), повторите его.
Показать запечатанный OpenBao (минута):
```powershell
docker compose restart openbao
.venv\Scripts\python scripts\bao_operator.py status # sealed=True
python tests\smoke.py --ca-file $env:CA_FILE # API работает: секреты в памяти
.venv\Scripts\python scripts\bao_operator.py unseal
```
## 5. Подводные камни Windows
* `PYTHONUTF8=1` обязателен: в путях и выводе есть кириллица.
* Хуки запускаются через `scripts\*.cmd` → Git Bash. Аргументы вида `/run/secrets/...` Git Bash превращает в пути Windows, поэтому скрипты ставят `MSYS_NO_PATHCONV=1`.
* Секреты передаются в контейнеры через stdin. Python в текстовом режиме на Windows пишет `\r\n`, поэтому тесты передают stdin байтами.
* Долгие прогоны (полный `pytest`, сбор доказательств) запускайте отдельным процессом: `powershell -File scripts\bg.ps1 -Log <файл> -Cmd "<команда>"`. Фоновые задачи терминала умирают вместе с ним.
* После перезапуска Docker Desktop OpenBao запечатан: `bao_operator.py unseal`, затем `docker compose up -d --wait`.
+18
View File
@@ -0,0 +1,18 @@
# Сводка доказательств lab7
Собрано: 2026-11-28T14:51:20+00:00
| Шаг | Команда | Код | Файл | Время, с |
| --- | --- | --- | --- | --- |
| стенд: версии/hardening/секреты по сервисам | `docker compose config/ps/inspect/exec` | 0 | [stand.md](stand.md) | 0 |
| make check | `.venv\Scripts\python.exe scripts/check_contract.py` | 0 | [check.txt](check.txt) | 4 |
| make test (HTTPS, public CA) | `.venv\Scripts\python.exe tests/smoke.py --base-url https://localhost:8443 --ca-file C:\Users\wfa2` | 0 | [smoke.txt](smoke.txt) | 5 |
| make test-security (недоверенный CA) | `.venv\Scripts\python.exe tests/security.py --base-url https://localhost:8443 --ca-file C:\Users\w` | 0 | [test-security.txt](test-security.txt) | 1 |
| mTLS LB->API: без cert / чужой CA / неверная identity / lb | `C:\Program Files\Git\bin\bash.exe scripts\mtls_check.sh` | 0 | [mtls-check.txt](mtls-check.txt) | 4 |
| OpenBao allow/deny, root credential отсутствует в app | `C:\Program Files\Git\bin\bash.exe scripts\bao_check.sh && C:\Users\wfa22\Desktop\Высоконагруженны` | 0 | [bao-check.txt](bao-check.txt) | 20 |
| make test-persistence (рестарт всех процессов, unseal) | `docker compose ps -a && .venv\Scripts\python.exe tests/resilience.py --mode persistence --action-` | 0 | [persistence.txt](persistence.txt) | 65 |
| make test-failover x N, обе реплики по очереди | `tests/resilience.py --mode failover + restore` | 0 | [failover.txt](failover.txt) | 0 |
| Argon2id: замер в контейнере API (1 CPU) | `docker compose exec -T api python - < bench/argon2_bench.py` | 0 | [argon2/bench.json](argon2/bench.json) | 52 |
| Телеметрия по mTLS: trace + logs | `.venv\Scripts\python.exe scripts/trace_demo.py` | 0 | [trace-demo.txt](trace-demo.txt) | 7 |
| Dashboard: все запросы через Grafana (HTTPS) | `.venv\Scripts\python.exe scripts/check_dashboard.py` | 0 | [dashboard-check.txt](dashboard-check.txt) | 2 |
| Свои тесты (unit + стенд, в т.ч. test_security.py) | `.venv\Scripts\python.exe -m pytest student-tests -v -p no:cacheprovider --durations=15` | 0 | [student-tests.txt](student-tests.txt) | 1923 |
+290
View File
@@ -0,0 +1,290 @@
{
"when": "2026-11-27T13:50:01Z",
"python": "3.13.16",
"argon2_cffi": "25.1.0",
"cpus_visible": 8,
"cgroup": {
"cpu_max": "100000 100000",
"memory_max": "536870912"
},
"sequential": [
{
"m_kib": 19456,
"t": 2,
"p": 1,
"n": 15,
"median_ms": 30.6,
"p95_ms": 47.4,
"cpu_ms_per_hash": 30.4,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=19456,t=2,p=1"
]
},
{
"m_kib": 19456,
"t": 3,
"p": 1,
"n": 15,
"median_ms": 47.4,
"p95_ms": 54.7,
"cpu_ms_per_hash": 45.1,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=19456,t=3,p=1"
]
},
{
"m_kib": 19456,
"t": 4,
"p": 1,
"n": 15,
"median_ms": 102.3,
"p95_ms": 175.4,
"cpu_ms_per_hash": 62.3,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=19456,t=4,p=1"
]
},
{
"m_kib": 32768,
"t": 2,
"p": 1,
"n": 15,
"median_ms": 72.9,
"p95_ms": 82.4,
"cpu_ms_per_hash": 69.8,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=32768,t=2,p=1"
]
},
{
"m_kib": 32768,
"t": 3,
"p": 1,
"n": 15,
"median_ms": 144.5,
"p95_ms": 284.0,
"cpu_ms_per_hash": 116.3,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=32768,t=3,p=1"
]
},
{
"m_kib": 32768,
"t": 4,
"p": 1,
"n": 15,
"median_ms": 144.6,
"p95_ms": 378.7,
"cpu_ms_per_hash": 135.4,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=32768,t=4,p=1"
]
},
{
"m_kib": 47104,
"t": 2,
"p": 1,
"n": 15,
"median_ms": 119.1,
"p95_ms": 291.2,
"cpu_ms_per_hash": 114.6,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=47104,t=2,p=1"
]
},
{
"m_kib": 47104,
"t": 3,
"p": 1,
"n": 15,
"median_ms": 144.3,
"p95_ms": 384.1,
"cpu_ms_per_hash": 141.7,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=47104,t=3,p=1"
]
},
{
"m_kib": 47104,
"t": 4,
"p": 1,
"n": 15,
"median_ms": 246.7,
"p95_ms": 485.3,
"cpu_ms_per_hash": 215.5,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=47104,t=4,p=1"
]
},
{
"m_kib": 65536,
"t": 2,
"p": 1,
"n": 15,
"median_ms": 162.8,
"p95_ms": 368.5,
"cpu_ms_per_hash": 157.4,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=65536,t=2,p=1"
]
},
{
"m_kib": 65536,
"t": 3,
"p": 1,
"n": 15,
"median_ms": 233.3,
"p95_ms": 669.8,
"cpu_ms_per_hash": 222.1,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=65536,t=3,p=1"
]
},
{
"m_kib": 65536,
"t": 4,
"p": 1,
"n": 15,
"median_ms": 319.5,
"p95_ms": 711.3,
"cpu_ms_per_hash": 261.4,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=65536,t=4,p=1"
]
}
],
"concurrent": [
{
"m_kib": 19456,
"t": 2,
"threads": 1,
"hashes": 6,
"wall_s": 0.22,
"hashes_per_s": 26.8,
"median_ms": 33.6,
"p95_ms": 61.0,
"cpu_utilisation": 0.86,
"ram_mib_hashing": 19.0
},
{
"m_kib": 19456,
"t": 2,
"threads": 2,
"hashes": 12,
"wall_s": 0.39,
"hashes_per_s": 30.6,
"median_ms": 74.3,
"p95_ms": 89.3,
"cpu_utilisation": 1.09,
"ram_mib_hashing": 38.0
},
{
"m_kib": 19456,
"t": 2,
"threads": 4,
"hashes": 24,
"wall_s": 1.38,
"hashes_per_s": 17.4,
"median_ms": 204.1,
"p95_ms": 289.0,
"cpu_utilisation": 0.86,
"ram_mib_hashing": 76.0
},
{
"m_kib": 47104,
"t": 2,
"threads": 1,
"hashes": 6,
"wall_s": 1.4,
"hashes_per_s": 4.3,
"median_ms": 206.5,
"p95_ms": 369.1,
"cpu_utilisation": 0.58,
"ram_mib_hashing": 46.0
},
{
"m_kib": 47104,
"t": 2,
"threads": 2,
"hashes": 12,
"wall_s": 1.62,
"hashes_per_s": 7.4,
"median_ms": 286.2,
"p95_ms": 295.9,
"cpu_utilisation": 1.01,
"ram_mib_hashing": 92.0
},
{
"m_kib": 47104,
"t": 2,
"threads": 4,
"hashes": 24,
"wall_s": 4.47,
"hashes_per_s": 5.4,
"median_ms": 703.6,
"p95_ms": 988.7,
"cpu_utilisation": 0.86,
"ram_mib_hashing": 184.0
},
{
"m_kib": 19456,
"t": 3,
"threads": 1,
"hashes": 6,
"wall_s": 0.68,
"hashes_per_s": 8.8,
"median_ms": 101.2,
"p95_ms": 165.8,
"cpu_utilisation": 0.45,
"ram_mib_hashing": 19.0
},
{
"m_kib": 19456,
"t": 3,
"threads": 2,
"hashes": 12,
"wall_s": 0.84,
"hashes_per_s": 14.3,
"median_ms": 114.2,
"p95_ms": 201.5,
"cpu_utilisation": 0.82,
"ram_mib_hashing": 38.0
},
{
"m_kib": 19456,
"t": 3,
"threads": 4,
"hashes": 24,
"wall_s": 1.97,
"hashes_per_s": 12.2,
"median_ms": 304.6,
"p95_ms": 409.3,
"cpu_utilisation": 0.92,
"ram_mib_hashing": 76.0
}
]
}
+290
View File
@@ -0,0 +1,290 @@
{
"when": "2026-11-28T14:18:18Z",
"python": "3.13.16",
"argon2_cffi": "25.1.0",
"cpus_visible": 8,
"cgroup": {
"cpu_max": "100000 100000",
"memory_max": "536870912"
},
"sequential": [
{
"m_kib": 19456,
"t": 2,
"p": 1,
"n": 15,
"median_ms": 50.6,
"p95_ms": 64.9,
"cpu_ms_per_hash": 47.8,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=19456,t=2,p=1"
]
},
{
"m_kib": 19456,
"t": 3,
"p": 1,
"n": 15,
"median_ms": 106.1,
"p95_ms": 172.3,
"cpu_ms_per_hash": 57.4,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=19456,t=3,p=1"
]
},
{
"m_kib": 19456,
"t": 4,
"p": 1,
"n": 15,
"median_ms": 87.9,
"p95_ms": 152.6,
"cpu_ms_per_hash": 78.5,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=19456,t=4,p=1"
]
},
{
"m_kib": 32768,
"t": 2,
"p": 1,
"n": 15,
"median_ms": 109.9,
"p95_ms": 277.4,
"cpu_ms_per_hash": 82.5,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=32768,t=2,p=1"
]
},
{
"m_kib": 32768,
"t": 3,
"p": 1,
"n": 15,
"median_ms": 144.1,
"p95_ms": 371.5,
"cpu_ms_per_hash": 126.9,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=32768,t=3,p=1"
]
},
{
"m_kib": 32768,
"t": 4,
"p": 1,
"n": 15,
"median_ms": 165.8,
"p95_ms": 294.4,
"cpu_ms_per_hash": 143.4,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=32768,t=4,p=1"
]
},
{
"m_kib": 47104,
"t": 2,
"p": 1,
"n": 15,
"median_ms": 167.8,
"p95_ms": 249.6,
"cpu_ms_per_hash": 140.0,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=47104,t=2,p=1"
]
},
{
"m_kib": 47104,
"t": 3,
"p": 1,
"n": 15,
"median_ms": 166.3,
"p95_ms": 516.5,
"cpu_ms_per_hash": 157.7,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=47104,t=3,p=1"
]
},
{
"m_kib": 47104,
"t": 4,
"p": 1,
"n": 15,
"median_ms": 210.6,
"p95_ms": 586.1,
"cpu_ms_per_hash": 209.4,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=47104,t=4,p=1"
]
},
{
"m_kib": 65536,
"t": 2,
"p": 1,
"n": 15,
"median_ms": 162.0,
"p95_ms": 379.4,
"cpu_ms_per_hash": 157.2,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=65536,t=2,p=1"
]
},
{
"m_kib": 65536,
"t": 3,
"p": 1,
"n": 15,
"median_ms": 264.1,
"p95_ms": 601.4,
"cpu_ms_per_hash": 233.3,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=65536,t=3,p=1"
]
},
{
"m_kib": 65536,
"t": 4,
"p": 1,
"n": 15,
"median_ms": 301.6,
"p95_ms": 1100.1,
"cpu_ms_per_hash": 279.5,
"hash_example_prefix": [
"argon2id",
"v=19",
"m=65536,t=4,p=1"
]
}
],
"concurrent": [
{
"m_kib": 19456,
"t": 2,
"threads": 1,
"hashes": 6,
"wall_s": 0.19,
"hashes_per_s": 32.0,
"median_ms": 29.7,
"p95_ms": 40.7,
"cpu_utilisation": 0.99,
"ram_mib_hashing": 19.0
},
{
"m_kib": 19456,
"t": 2,
"threads": 2,
"hashes": 12,
"wall_s": 0.42,
"hashes_per_s": 28.8,
"median_ms": 83.0,
"p95_ms": 89.6,
"cpu_utilisation": 1.04,
"ram_mib_hashing": 38.0
},
{
"m_kib": 19456,
"t": 2,
"threads": 4,
"hashes": 24,
"wall_s": 1.38,
"hashes_per_s": 17.4,
"median_ms": 205.0,
"p95_ms": 291.6,
"cpu_utilisation": 0.88,
"ram_mib_hashing": 76.0
},
{
"m_kib": 47104,
"t": 2,
"threads": 1,
"hashes": 6,
"wall_s": 1.09,
"hashes_per_s": 5.5,
"median_ms": 176.9,
"p95_ms": 309.5,
"cpu_utilisation": 0.6,
"ram_mib_hashing": 46.0
},
{
"m_kib": 47104,
"t": 2,
"threads": 2,
"hashes": 12,
"wall_s": 1.46,
"hashes_per_s": 8.2,
"median_ms": 224.2,
"p95_ms": 305.3,
"cpu_utilisation": 0.99,
"ram_mib_hashing": 92.0
},
{
"m_kib": 47104,
"t": 2,
"threads": 4,
"hashes": 24,
"wall_s": 4.76,
"hashes_per_s": 5.0,
"median_ms": 799.9,
"p95_ms": 980.1,
"cpu_utilisation": 0.82,
"ram_mib_hashing": 184.0
},
{
"m_kib": 19456,
"t": 3,
"threads": 1,
"hashes": 6,
"wall_s": 0.27,
"hashes_per_s": 22.1,
"median_ms": 43.9,
"p95_ms": 53.1,
"cpu_utilisation": 0.94,
"ram_mib_hashing": 19.0
},
{
"m_kib": 19456,
"t": 3,
"threads": 2,
"hashes": 12,
"wall_s": 0.63,
"hashes_per_s": 19.0,
"median_ms": 106.5,
"p95_ms": 156.0,
"cpu_utilisation": 1.0,
"ram_mib_hashing": 38.0
},
{
"m_kib": 19456,
"t": 3,
"threads": 4,
"hashes": 24,
"wall_s": 2.09,
"hashes_per_s": 11.5,
"median_ms": 385.3,
"p95_ms": 407.5,
"cpu_utilisation": 0.83,
"ram_mib_hashing": 76.0
}
]
}
+98
View File
@@ -0,0 +1,98 @@
# OpenBao allow/deny, root credential отсутствует в app
# 2026-11-28T14:15:50+00:00
$ C:\Program Files\Git\bin\bash.exe scripts\bao_check.sh
== api
service api: OpenBao https://openbao:8200 (TLS verified against /run/secrets/internal-ca.crt)
PASS allow AppRole login with the service's role_id/secret_id -> HTTP 200
token policies=['api'] ttl=3600s renewable=True
PASS allow read own path messenger/data/api -> HTTP 200
keys: ['cache_url', 'database_url', 's3_access_key_id', 's3_secret_access_key']
PASS allow token lookup-self -> HTTP 200
PASS deny read other service's path messenger/data/relay -> HTTP 403
PASS deny read other service's path messenger/data/worker -> HTTP 403
PASS deny write own path messenger/data/api -> HTTP 403
PASS deny list messenger/metadata -> HTTP 403
PASS deny write policy sys/policies/acl/api -> HTTP 403
PASS deny read policy list sys/policies/acl -> HTTP 403
PASS deny create a child token auth/token/create -> HTTP 403
PASS deny enable an auth method sys/auth/userpass -> HTTP 403
PASS deny read sys/mounts -> HTTP 403
PASS allow revoke-self -> HTTP 204
PASS deny use the token after revoke-self (lookup-self) -> HTTP 403
PASS deny read own path with the revoked token -> HTTP 403
PASS deny AppRole login with a wrong secret_id -> HTTP 400
PASS: OpenBao policy of api, 0 failure(s)
== relay
service relay: OpenBao https://openbao:8200 (TLS verified against /run/secrets/internal-ca.crt)
PASS allow AppRole login with the service's role_id/secret_id -> HTTP 200
token policies=['relay'] ttl=3600s renewable=True
PASS allow read own path messenger/data/relay -> HTTP 200
keys: ['broker_url', 'database_url']
PASS allow token lookup-self -> HTTP 200
PASS deny read other service's path messenger/data/api -> HTTP 403
PASS deny read other service's path messenger/data/worker -> HTTP 403
PASS deny write own path messenger/data/relay -> HTTP 403
PASS deny list messenger/metadata -> HTTP 403
PASS deny write policy sys/policies/acl/relay -> HTTP 403
PASS deny read policy list sys/policies/acl -> HTTP 403
PASS deny create a child token auth/token/create -> HTTP 403
PASS deny enable an auth method sys/auth/userpass -> HTTP 403
PASS deny read sys/mounts -> HTTP 403
PASS allow revoke-self -> HTTP 204
PASS deny use the token after revoke-self (lookup-self) -> HTTP 403
PASS deny read own path with the revoked token -> HTTP 403
PASS deny AppRole login with a wrong secret_id -> HTTP 400
PASS: OpenBao policy of relay, 0 failure(s)
== worker
service worker: OpenBao https://openbao:8200 (TLS verified against /run/secrets/internal-ca.crt)
PASS allow AppRole login with the service's role_id/secret_id -> HTTP 200
token policies=['worker'] ttl=3600s renewable=True
PASS allow read own path messenger/data/worker -> HTTP 200
keys: ['broker_url', 'database_url', 's3_access_key_id', 's3_secret_access_key']
PASS allow token lookup-self -> HTTP 200
PASS deny read other service's path messenger/data/api -> HTTP 403
PASS deny read other service's path messenger/data/relay -> HTTP 403
PASS deny write own path messenger/data/worker -> HTTP 403
PASS deny list messenger/metadata -> HTTP 403
PASS deny write policy sys/policies/acl/worker -> HTTP 403
PASS deny read policy list sys/policies/acl -> HTTP 403
PASS deny create a child token auth/token/create -> HTTP 403
PASS deny enable an auth method sys/auth/userpass -> HTTP 403
PASS deny read sys/mounts -> HTTP 403
PASS allow revoke-self -> HTTP 204
PASS deny use the token after revoke-self (lookup-self) -> HTTP 403
PASS deny read own path with the revoked token -> HTTP 403
PASS deny AppRole login with a wrong secret_id -> HTTP 400
PASS: OpenBao policy of worker, 0 failure(s)
== root credential / unseal material in the application containers (values compared, never printed)
PASS api: no *TOKEN*/*UNSEAL*/*ROOT* environment variable
PASS control: own role_id found by the same search (/run/secrets/bao_role_id)
PASS api: root-token absent (/run/secrets, /app, /tmp, PID 1 environment)
PASS api: unseal-share-1 absent (/run/secrets, /app, /tmp, PID 1 environment)
PASS api: unseal-share-2 absent (/run/secrets, /app, /tmp, PID 1 environment)
PASS api: unseal-share-3 absent (/run/secrets, /app, /tmp, PID 1 environment)
api /run/secrets: bao_role_id bao_secret_id internal-ca.crt service.crt service.key
PASS relay: no *TOKEN*/*UNSEAL*/*ROOT* environment variable
PASS control: own role_id found by the same search (/run/secrets/bao_role_id)
PASS relay: root-token absent (/run/secrets, /app, /tmp, PID 1 environment)
PASS relay: unseal-share-1 absent (/run/secrets, /app, /tmp, PID 1 environment)
PASS relay: unseal-share-2 absent (/run/secrets, /app, /tmp, PID 1 environment)
PASS relay: unseal-share-3 absent (/run/secrets, /app, /tmp, PID 1 environment)
relay /run/secrets: bao_role_id bao_secret_id internal-ca.crt service.crt service.key
PASS worker: no *TOKEN*/*UNSEAL*/*ROOT* environment variable
PASS control: own role_id found by the same search (/run/secrets/bao_role_id)
PASS worker: root-token absent (/run/secrets, /app, /tmp, PID 1 environment)
PASS worker: unseal-share-1 absent (/run/secrets, /app, /tmp, PID 1 environment)
PASS worker: unseal-share-2 absent (/run/secrets, /app, /tmp, PID 1 environment)
PASS worker: unseal-share-3 absent (/run/secrets, /app, /tmp, PID 1 environment)
worker /run/secrets: bao_role_id bao_secret_id internal-ca.crt service.crt service.key
PASS: OpenBao allow/deny and no root credential in the application
[exit 0]
$ .venv\Scripts\python.exe scripts/bao_operator.py status
bao-operator: initialized=True sealed=False storage=raft version=2.7.3 operator_dir=C:\Users\wfa22\.mtusi-lab7-operator\mtusi-lab7-clean
[exit 0]
+7
View File
@@ -0,0 +1,7 @@
# make check
# 2026-11-28T14:15:37+00:00
$ .venv\Scripts\python.exe scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
[exit 0]
+42
View File
@@ -0,0 +1,42 @@
# Dashboard: все запросы через Grafana (HTTPS)
# 2026-11-28T14:19:16+00:00
$ .venv\Scripts\python.exe scripts/check_dashboard.py
dashboard messenger-lab6 "Messenger lab 6: API, worker, queue, SLO" (provisioned), window 30 min
== API: requests, errors, latency (all replicas)
[timeseries] Requests per second by route: A: 10 series/446 points
[timeseries] Error ratio (5xx and 4xx / all business requests): A: 1 series/67 points; B: 1 series/67 points
[timeseries] Latency p50 / p95 / p99 (all routes, all replicas): A: 1 series/67 points; B: 1 series/67 points; C: 1 series/67 points
[timeseries] p95 by route: A: 10 series/446 points
[timeseries] Requests in flight by replica: A: 42 series/851 points
== Worker and queue
[timeseries] Jobs handled per second by outcome: A: 1 series/47 points
[timeseries] Job duration p50 / p95 / p99 (succeeded): A: 1 series/47 points; B: 1 series/47 points; C: 1 series/47 points
[timeseries] Time to ready p50 / p95 / p99 (uploads): A: 1 series/47 points; B: 1 series/47 points; C: 1 series/47 points
[timeseries] Queue depth (PostgreSQL) and outbox: A: 2 series/136 points; B: 2 series/136 points
[timeseries] Oldest job age / oldest due outbox row: A: 1 series/68 points; B: 1 series/68 points
[timeseries] Worker saturation (busy / capacity): A: 1 series/66 points
== Database pool and resources
[timeseries] DB pool: used / max, waiting requests: A: 3 series/204 points; B: 3 series/204 points; C: 3 series/204 points
[timeseries] DB unit of work p95 by service: A: 3 series/202 points
[timeseries] DB pool wait p95 by service: A: 3 series/202 points
[timeseries] Container CPU (cores): A: 48 series/375 points; B: 1 series/69 points
[timeseries] Container memory: A: 48 series/1042 points; B: 1 series/70 points
== SLO (docs/SLO.md) and alerts
[stat] Availability, last 1 h (target 99 %): A: 1 series/70 points
[stat] Requests under 250 ms, last 5 min (target 95 %): A: 1 series/67 points
[stat] Uploads ready within 30 s, last 1 h (target 99 %): A: 1 series/70 points
[stat] Alerts firing: A: 1 series/121 points
[table] Alerts (pending / firing): A: no data
== Telemetry pipeline (Collector, SDK)
[timeseries] Collector: spans accepted / sent / failed per second: A: 1 series/66 points; B: 1 series/66 points; C: 1 series/66 points; D: no data
[timeseries] Collector: logs and metric points per second: A: 1 series/67 points; B: no data; C: 1 series/67 points; D: no data
[timeseries] Collector: exporter queues: A: 3 series/210 points; B: 3 series/210 points
[timeseries] SDK: spans recorded vs exported (all processes): A: 3 series/161 points; B: 3 series/161 points
[timeseries] Telemetry components up: A: 3 series/209 points
== Logs and traces
[logs] Application logs (Loki): warnings and errors: A: 1 series/100 points
[table] Recent upload traces (Tempo): A: 1 series/12 points
queries failed: 0
[exit 0]
+67
View File
@@ -0,0 +1,67 @@
# make test-failover: последовательный отказ реплик API
$ .venv\Scripts\python.exe tests/resilience.py --mode failover --action-script scripts\stop-one.cmd --ca-file secrets\pki\public-ca.crt
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 117, "failed_attempts": 0, "first_recovery_seconds": 1.748}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
[exit 0]
$ docker compose ps -a api
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi-lab7-clean-api-1 mtusi-messenger:lab7 "python -m messenger" api 3 minutes ago Exited (0) 9 seconds ago
mtusi-lab7-clean-api-2 mtusi-messenger:lab7 "python -m messenger" api 3 minutes ago Up 26 seconds (healthy) 8080/tcp, 8443/tcp
[exit 0]
$ C:\Program Files\Git\bin\bash.exe scripts\restore-api.sh
mtusi-lab7-clean-api-1 Up 6 seconds (healthy)
mtusi-lab7-clean-api-2 Up 35 seconds (healthy)
Container mtusi-lab7-clean-api-2 Running
Container mtusi-lab7-clean-api-1 Starting
Container mtusi-lab7-clean-api-1 Started
Container mtusi-lab7-clean-api-1 Waiting
Container mtusi-lab7-clean-api-2 Waiting
Container mtusi-lab7-clean-api-1 Healthy
Container mtusi-lab7-clean-api-2 Healthy
[exit 0]
$ .venv\Scripts\python.exe scripts/lbctl.py wait-up 2
2 API replica(s) UP in HAProxy after 1.1 s: ['i-5f67386b096f', 'i-7bcf23aa0693']
[exit 0]
$ .venv\Scripts\python.exe tests/resilience.py --mode failover --action-script scripts\stop-one.cmd --ca-file secrets\pki\public-ca.crt
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 120, "failed_attempts": 0, "first_recovery_seconds": 1.787}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
[exit 0]
$ docker compose ps -a api
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi-lab7-clean-api-1 mtusi-messenger:lab7 "python -m messenger" api 3 minutes ago Up 28 seconds (healthy) 8080/tcp, 8443/tcp
mtusi-lab7-clean-api-2 mtusi-messenger:lab7 "python -m messenger" api 3 minutes ago Exited (0) 10 seconds ago
[exit 0]
$ C:\Program Files\Git\bin\bash.exe scripts\restore-api.sh
mtusi-lab7-clean-api-1 Up 37 seconds (healthy)
mtusi-lab7-clean-api-2 Up 7 seconds (healthy)
Container mtusi-lab7-clean-api-1 Running
Container mtusi-lab7-clean-api-2 Starting
Container mtusi-lab7-clean-api-2 Started
Container mtusi-lab7-clean-api-1 Waiting
Container mtusi-lab7-clean-api-2 Waiting
Container mtusi-lab7-clean-api-1 Healthy
Container mtusi-lab7-clean-api-2 Healthy
[exit 0]
$ .venv\Scripts\python.exe scripts/lbctl.py wait-up 2
2 API replica(s) UP in HAProxy after 1.1 s: ['i-5f67386b096f', 'i-83def22f481a']
[exit 0]
stopped containers over the runs: ['17c5883f5d19', '87d05ecea97d']
+39
View File
@@ -0,0 +1,39 @@
# mTLS LB->API: без cert / чужой CA / неверная identity / lb
# 2026-11-28T14:15:47+00:00
$ C:\Program Files\Git\bin\bash.exe scripts\mtls_check.sh
API replicas behind DNS name `api`: 2
replica 172.26.0.3:8443
PASS TLS 1.3 client cert none -> refused closed by the server after the handshake (no HTTP response)
PASS TLS 1.3 client cert foreign-ca SAN=lb -> refused closed by the server after the handshake (no HTTP response)
PASS TLS 1.3 client cert internal-ca SAN=worker -> refused closed by the server after the handshake (no HTTP response)
PASS TLS 1.3 client cert internal-ca SAN=lb -> 200 HTTP 200; server cert SAN api verified
PASS TLS 1.2 client cert none -> refused server closed the connection during the handshake (no HTTP response)
PASS TLS 1.2 client cert foreign-ca SAN=lb -> refused server closed the connection during the handshake (no HTTP response)
PASS TLS 1.2 client cert internal-ca SAN=worker -> refused server closed the connection during the handshake (no HTTP response)
PASS TLS 1.2 client cert internal-ca SAN=lb -> 200 HTTP 200; server cert SAN api verified
PASS plaintext HTTP to the mTLS port -> no HTTP answer (TLS-only listener)
PASS loopback health port from outside -> ConnectionRefusedError
replica 172.26.0.4:8443
PASS TLS 1.3 client cert none -> refused closed by the server after the handshake (no HTTP response)
PASS TLS 1.3 client cert foreign-ca SAN=lb -> refused closed by the server after the handshake (no HTTP response)
PASS TLS 1.3 client cert internal-ca SAN=worker -> refused closed by the server after the handshake (no HTTP response)
PASS TLS 1.3 client cert internal-ca SAN=lb -> 200 HTTP 200; server cert SAN api verified
PASS TLS 1.2 client cert none -> refused server closed the connection during the handshake (no HTTP response)
PASS TLS 1.2 client cert foreign-ca SAN=lb -> refused server closed the connection during the handshake (no HTTP response)
PASS TLS 1.2 client cert internal-ca SAN=worker -> refused server closed the connection during the handshake (no HTTP response)
PASS TLS 1.2 client cert internal-ca SAN=lb -> 200 HTTP 200; server cert SAN api verified
PASS plaintext HTTP to the mTLS port -> no HTTP answer (TLS-only listener)
PASS loopback health port from outside -> ConnectionRefusedError
PASS: mTLS LB->API, 2 replica(s), 0 failure(s)
API log since 2026-11-28T14:15:47Z, identity allowlist refusals (cases 1-2 are dropped by TLS and never logged):
{"ts": "2026-11-28T14:15:49.594Z", "level": "warning", "logger": "messenger.tls", "event": "mtls_identity_rejected", "client_san": ["worker"], "peer": "172.26.0.5", "allowed": ["lb"]}
{"ts": "2026-11-28T14:15:49.691Z", "level": "warning", "logger": "messenger.tls", "event": "mtls_identity_rejected", "client_san": ["worker"], "peer": "172.26.0.5", "allowed": ["lb"]}
{"ts": "2026-11-28T14:15:49.309Z", "level": "warning", "logger": "messenger.tls", "event": "mtls_identity_rejected", "client_san": ["worker"], "peer": "172.26.0.5", "allowed": ["lb"]}
{"ts": "2026-11-28T14:15:49.438Z", "level": "warning", "logger": "messenger.tls", "event": "mtls_identity_rejected", "client_san": ["worker"], "peer": "172.26.0.5", "allowed": ["lb"]}
[exit 0]
+52
View File
@@ -0,0 +1,52 @@
# make test-persistence (рестарт всех процессов, unseal)
# 2026-11-28T14:16:10+00:00
$ docker compose ps -a
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi-lab7-clean-api-1 mtusi-messenger:lab7 "python -m messenger" api About a minute ago Up About a minute (healthy) 8080/tcp, 8443/tcp
mtusi-lab7-clean-api-2 mtusi-messenger:lab7 "python -m messenger" api About a minute ago Up About a minute (healthy) 8080/tcp, 8443/tcp
mtusi-lab7-clean-broker-1 rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 "docker-entrypoint.s…" broker 16 hours ago Up 14 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
mtusi-lab7-clean-grafana-1 grafana/grafana:13.2.6@sha256:b21409d7951ddcfd63a4b49083e4ef2cc35bc1437d071813bf82bfb238b00bca "/run.sh" grafana 16 hours ago Up 14 minutes (healthy) 127.0.0.1:3000->3000/tcp, [::1]:3000->3000/tcp
mtusi-lab7-clean-lb-1 haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 "docker-entrypoint.s…" lb 16 hours ago Up 14 minutes (healthy) 127.0.0.1:8443->8443/tcp, [::1]:8443->8443/tcp
mtusi-lab7-clean-loki-1 grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 "/usr/bin/loki -conf…" loki 16 hours ago Up 14 minutes 3100/tcp
mtusi-lab7-clean-migrate-1 mtusi-messenger:lab7 "python -m messenger…" migrate 5 minutes ago Exited (0) 5 minutes ago
mtusi-lab7-clean-openbao-1 openbao/openbao:2.7.3@sha256:b9418c63e2185157d8ee8689a8a93265d5aadad677d6320156172bd42ad3b10b "docker-entrypoint.s…" openbao 16 hours ago Up 14 minutes (healthy) 8200/tcp
mtusi-lab7-clean-otel-collector-1 otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea "/otelcol-contrib --…" otel-collector 16 hours ago Up 14 minutes 4317-4318/tcp, 55679/tcp
mtusi-lab7-clean-postgres-1 postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c "docker-entrypoint.s…" postgres 16 hours ago Up About a minute (healthy) 5432/tcp
mtusi-lab7-clean-prometheus-1 prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 "/bin/prometheus --c…" prometheus 16 hours ago Up 14 minutes (healthy) 9090/tcp
mtusi-lab7-clean-relay-1 mtusi-messenger:lab7 "python -m messenger…" relay 5 minutes ago Up 5 minutes (healthy) 8080/tcp
mtusi-lab7-clean-s3-1 chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 "/bin/sh /etc/seawee…" s3 16 hours ago Up 14 minutes (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
mtusi-lab7-clean-s3-init-1 mtusi-messenger:lab7 "python -m messenger…" s3-init 5 minutes ago Exited (0) 5 minutes ago
mtusi-lab7-clean-tempo-1 grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38 "/tempo -config.file…" tempo 16 hours ago Up 14 minutes
mtusi-lab7-clean-valkey-1 valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 "/bin/sh /etc/valkey…" valkey 16 hours ago Up 3 minutes (healthy) 6379/tcp
mtusi-lab7-clean-worker-1 mtusi-messenger:lab7 "python -m messenger…" worker 5 minutes ago Up 5 minutes (healthy) 8080/tcp
[exit 0]
$ .venv\Scripts\python.exe tests/resilience.py --mode persistence --action-script scripts\restart.cmd --ca-file 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.
[exit 0]
$ docker compose ps -a
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi-lab7-clean-api-1 mtusi-messenger:lab7 "python -m messenger" api 2 minutes ago Up 8 seconds (healthy) 8080/tcp, 8443/tcp
mtusi-lab7-clean-api-2 mtusi-messenger:lab7 "python -m messenger" api 2 minutes ago Up 7 seconds (healthy) 8080/tcp, 8443/tcp
mtusi-lab7-clean-broker-1 rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 "docker-entrypoint.s…" broker 16 hours ago Up 53 seconds (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
mtusi-lab7-clean-grafana-1 grafana/grafana:13.2.6@sha256:b21409d7951ddcfd63a4b49083e4ef2cc35bc1437d071813bf82bfb238b00bca "/run.sh" grafana 16 hours ago Up 15 minutes (healthy) 127.0.0.1:3000->3000/tcp, [::1]:3000->3000/tcp
mtusi-lab7-clean-lb-1 haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 "docker-entrypoint.s…" lb 16 hours ago Up 1 second (health: starting) 127.0.0.1:8443->8443/tcp, [::1]:8443->8443/tcp
mtusi-lab7-clean-loki-1 grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 "/usr/bin/loki -conf…" loki 16 hours ago Up 15 minutes 3100/tcp
mtusi-lab7-clean-migrate-1 mtusi-messenger:lab7 "python -m messenger…" migrate 7 minutes ago Exited (0) 28 seconds ago
mtusi-lab7-clean-openbao-1 openbao/openbao:2.7.3@sha256:b9418c63e2185157d8ee8689a8a93265d5aadad677d6320156172bd42ad3b10b "docker-entrypoint.s…" openbao 16 hours ago Up 53 seconds (healthy) 8200/tcp
mtusi-lab7-clean-otel-collector-1 otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea "/otelcol-contrib --…" otel-collector 16 hours ago Up 15 minutes 4317-4318/tcp, 55679/tcp
mtusi-lab7-clean-postgres-1 postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c "docker-entrypoint.s…" postgres 16 hours ago Up 54 seconds (healthy) 5432/tcp
mtusi-lab7-clean-prometheus-1 prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 "/bin/prometheus --c…" prometheus 16 hours ago Up 15 minutes (healthy) 9090/tcp
mtusi-lab7-clean-relay-1 mtusi-messenger:lab7 "python -m messenger…" relay 7 minutes ago Up 28 seconds (healthy) 8080/tcp
mtusi-lab7-clean-s3-1 chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 "/bin/sh /etc/seawee…" s3 16 hours ago Up 34 seconds (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
mtusi-lab7-clean-s3-init-1 mtusi-messenger:lab7 "python -m messenger…" s3-init 7 minutes ago Exited (0) 8 seconds ago
mtusi-lab7-clean-tempo-1 grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38 "/tempo -config.file…" tempo 16 hours ago Up 15 minutes
mtusi-lab7-clean-valkey-1 valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 "/bin/sh /etc/valkey…" valkey 16 hours ago Up 54 seconds (healthy) 6379/tcp
mtusi-lab7-clean-worker-1 mtusi-messenger:lab7 "python -m messenger…" worker 7 minutes ago Up 6 seconds (healthy) 8080/tcp
[exit 0]
+7
View File
@@ -0,0 +1,7 @@
# make test (HTTPS, public CA)
# 2026-11-28T14:15:41+00:00
$ .venv\Scripts\python.exe tests/smoke.py --base-url https://localhost:8443 --ca-file secrets\pki\public-ca.crt
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
[exit 0]
+64
View File
@@ -0,0 +1,64 @@
# Стенд: версии, образы, hardening, секреты по сервисам (только имена)
commit: f2bd580c2f1ee6473034e6f8bd03f44dbc67c73c
docker: 29.8.0 (linux/amd64)
docker VM: 8 CPU, 15686336512 bytes RAM
compose project: mtusi-lab7-clean
| service | image | cap_drop | cap_add | no-new-priv | cpus | memory | published | secrets (names) |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| api | mtusi-messenger:lab7 | ['ALL'] | | True | 1 | 512 MiB | [] | bao_api_role_id, bao_api_secret_id, pki_api_crt, pki_api_key, pki_internal_ca |
| broker | rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 | ['ALL'] | ['CHOWN', 'DAC_OVERRIDE', 'FOWNER', 'SETGID', 'SETUID'] | True | 1 | 512 MiB | [] | pki_broker_crt, pki_broker_key, pki_internal_ca, rabbitmq_users |
| grafana | grafana/grafana:13.2.6@sha256:b21409d7951ddcfd63a4b49083e4ef2cc35bc1437d071813bf82bfb238b00bca | ['ALL'] | | True | 1 | 1024 MiB | ['127.0.0.1:3000', '::1:3000'] | grafana_admin_password, pki_grafana_crt, pki_grafana_key, pki_grafana_ui_crt, pki_grafana_ui_key, pki_internal_ca, pki_public_ca |
| lb | haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 | ['ALL'] | | True | 1 | 128 MiB | ['127.0.0.1:8443', '::1:8443'] | pki_ingress_pem, pki_internal_ca, pki_lb_pem |
| loki | grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 | ['ALL'] | | True | 1 | 512 MiB | [] | pki_internal_ca, pki_loki_crt, pki_loki_key |
| migrate | mtusi-messenger:lab7 | ['ALL'] | | True | 0.5 | 256 MiB | [] | database_url_migrate, pki_internal_ca |
| openbao | openbao/openbao:2.7.3@sha256:b9418c63e2185157d8ee8689a8a93265d5aadad677d6320156172bd42ad3b10b | ['ALL'] | | True | 0.5 | 256 MiB | [] | pki_internal_ca, pki_openbao_crt, pki_openbao_key |
| otel-collector | otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea | ['ALL'] | | True | 1 | 512 MiB | [] | pki_internal_ca, pki_otel_collector_crt, pki_otel_collector_key |
| postgres | postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c | ['ALL'] | ['CHOWN', 'DAC_OVERRIDE', 'FOWNER', 'SETGID', 'SETUID'] | True | 2 | 1024 MiB | [] | pg_api_password, pg_auditor_password, pg_jobctl_password, pg_migrate_password, pg_relay_password, pg_worker_password, pki_internal_ca, pki_postgres_crt, pki_postgres_key, postgres_password |
| prometheus | prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 | ['ALL'] | | True | 1 | 512 MiB | [] | pki_internal_ca, pki_prometheus_crt, pki_prometheus_key |
| relay | mtusi-messenger:lab7 | ['ALL'] | | True | 0.5 | 256 MiB | [] | bao_relay_role_id, bao_relay_secret_id, pki_internal_ca, pki_relay_crt, pki_relay_key |
| s3 | chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 | ['ALL'] | ['CHOWN', 'DAC_OVERRIDE', 'FOWNER', 'SETGID', 'SETUID'] | True | 1 | 1024 MiB | [] | pki_internal_ca, pki_s3_crt, pki_s3_key, s3_admin_access_key_id, s3_admin_secret_access_key, s3_api_access_key_id, s3_api_secret_access_key, s3_auditor_access_key_id, s3_auditor_secret_access_key, s3_worker_access_key_id, s3_worker_secret_access_key |
| s3-init | mtusi-messenger:lab7 | ['ALL'] | | True | 0.5 | 256 MiB | [] | pki_internal_ca, s3_admin_access_key_id, s3_admin_secret_access_key, s3_api_access_key_id, s3_api_secret_access_key, s3_auditor_access_key_id, s3_auditor_secret_access_key, s3_worker_access_key_id, s3_worker_secret_access_key |
| tempo | grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38 | ['ALL'] | | True | 1 | 512 MiB | [] | pki_internal_ca, pki_tempo_crt, pki_tempo_key |
| valkey | valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 | ['ALL'] | ['CHOWN', 'DAC_OVERRIDE', 'FOWNER', 'SETGID', 'SETUID'] | True | 0.5 | 256 MiB | [] | pki_internal_ca, pki_valkey_crt, pki_valkey_key, valkey_api_password |
| worker | mtusi-messenger:lab7 | ['ALL'] | | True | 2 | 1536 MiB | [] | bao_worker_role_id, bao_worker_secret_id, pki_internal_ca, pki_worker_crt, pki_worker_key |
## docker compose ps -a
```
api Up 49 seconds (healthy) 8080/tcp, 8443/tcp
api Up 48 seconds (healthy) 8080/tcp, 8443/tcp
broker Up 13 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
grafana Up 13 minutes (healthy) 127.0.0.1:3000->3000/tcp, [::1]:3000->3000/tcp
lb Up 13 minutes (healthy) 127.0.0.1:8443->8443/tcp, [::1]:8443->8443/tcp
loki Up 13 minutes 3100/tcp
migrate Exited (0) 5 minutes ago
openbao Up 13 minutes (healthy) 8200/tcp
otel-collector Up 13 minutes 4317-4318/tcp, 55679/tcp
postgres Up About a minute (healthy) 5432/tcp
prometheus Up 13 minutes (healthy) 9090/tcp
relay Up 5 minutes (healthy) 8080/tcp
s3 Up 13 minutes (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
s3-init Exited (0) 4 minutes ago
tempo Up 13 minutes
valkey Up 2 minutes (healthy) 6379/tcp
worker Up 4 minutes (healthy) 8080/tcp
```
## Пользователь и capabilities PID 1 (запущенные контейнеры)
| service | container | user | capabilities | X-Instance-Id alias |
| --- | --- | --- | --- | --- |
| api | 17c5883f5d19 | uid 10001 | CapEff 0000000000000000 | i-1c2252476ea2 |
| api | 87d05ecea97d | uid 10001 | CapEff 0000000000000000 | i-7a9bc4eb5903 |
| relay | 638e500712f8 | uid 10001 | CapEff 0000000000000000 | i-f6d48092a828 |
| worker | 7b83b29d9feb | uid 10001 | CapEff 0000000000000000 | i-5751896bbdd1 |
| lb | ae03174dae61 | uid 99 | CapEff 0000000000000000 | - |
| openbao | 51aa7f9765f9 | uid 100 | CapEff 0000000000000000 | - |
| otel-collector | 1acf642bfd4f | uid OCI runtime exec failed: exec failed: unable to start container process: exec: "id": executable file not found in $PATH | CapEff $PATH | OCI runtime exec failed: exec failed: unable to start container process: exec: "cat": executable file not found in $PATH |
| prometheus | 8583fee78ae1 | uid 65534 | CapEff 0000000000000000 | - |
| grafana | 294735cabfeb | uid 472 | CapEff 0000000000000000 | - |
| loki | 163ba071b6b3 | uid OCI runtime exec failed: exec failed: unable to start container process: exec: "id": executable file not found in $PATH | CapEff $PATH | OCI runtime exec failed: exec failed: unable to start container process: exec: "cat": executable file not found in $PATH |
| tempo | fa42af48bede | uid OCI runtime exec failed: exec failed: unable to start container process: exec: "id": executable file not found in $PATH | CapEff $PATH | OCI runtime exec failed: exec failed: unable to start container process: exec: "cat": executable file not found in $PATH |
+459
View File
@@ -0,0 +1,459 @@
# Свои тесты (unit + стенд, в т.ч. test_security.py)
# 2026-11-28T14:19:18+00:00
$ .venv\Scripts\python.exe -m pytest student-tests -v -p no:cacheprovider --durations=15
============================= test session starts =============================
platform win32 -- Python 3.14.6, pytest-9.1.1, pluggy-1.7.0 -- .venv\Scripts\python.exe
rootdir: .
plugins: anyio-4.15.1
collecting ... collected 429 items
student-tests/test_api.py::test_register_never_returns_password_and_login_returns_bearer PASSED [ 0%]
student-tests/test_api.py::test_duplicate_username_is_409 PASSED [ 0%]
student-tests/test_api.py::test_bad_password_on_registration_is_400[short-11ch] PASSED [ 0%]
student-tests/test_api.py::test_bad_password_on_registration_is_400[ ] PASSED [ 0%]
student-tests/test_api.py::test_bad_password_on_registration_is_400[ \t \n \t \n \t \n ] PASSED [ 1%]
student-tests/test_api.py::test_bad_password_on_registration_is_400[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 1%]
student-tests/test_api.py::test_edge_passwords_register_and_login[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 1%]
student-tests/test_api.py::test_edge_passwords_register_and_login[with:colons:inside] PASSED [ 1%]
student-tests/test_api.py::test_edge_passwords_register_and_login[Twelve chars] PASSED [ 2%]
student-tests/test_api.py::test_wrong_password_and_unknown_user_give_the_same_401 PASSED [ 2%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic \xe9] PASSED [ 2%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic !!!] PASSED [ 2%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic bm9fY29sb24=] PASSED [ 3%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic //46eA==] PASSED [ 3%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 3%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[] PASSED [ 3%]
student-tests/test_api.py::test_logout_revokes_only_this_token PASSED [ 3%]
student-tests/test_api.py::test_x_user_id_basic_and_garbage_do_not_authenticate PASSED [ 4%]
student-tests/test_api.py::test_malformed_json_is_400[{] PASSED [ 4%]
student-tests/test_api.py::test_malformed_json_is_400[] PASSED [ 4%]
student-tests/test_api.py::test_malformed_json_is_400[[]] PASSED [ 4%]
student-tests/test_api.py::test_malformed_json_is_400[null] PASSED [ 5%]
student-tests/test_api.py::test_malformed_json_is_400[{"username": "abc_def", "display_name": NaN, "password": "Twelve-chars"}] PASSED [ 5%]
student-tests/test_api.py::test_malformed_json_is_400[{"username": "abc_def", "display_name": "x", "password": "Twelve-chars"}{"a": 1}] PASSED [ 5%]
student-tests/test_api.py::test_malformed_json_is_400[{"username": "abc_def", "display_name": "\ud800", "password": "Twelve-chars"}] PASSED [ 5%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body0] PASSED [ 6%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body1] PASSED [ 6%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body2] PASSED [ 6%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body3] PASSED [ 6%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body4] PASSED [ 6%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body5] PASSED [ 7%]
student-tests/test_api.py::test_unicode_limits_are_code_points_and_nul_is_stored PASSED [ 7%]
student-tests/test_api.py::test_oversized_body_and_wrong_content_type PASSED [ 7%]
student-tests/test_api.py::test_chat_validation PASSED [ 7%]
student-tests/test_api.py::test_foreign_chat_is_indistinguishable_from_missing PASSED [ 8%]
student-tests/test_api.py::test_chat_list_order_pagination_and_isolation PASSED [ 8%]
student-tests/test_api.py::test_history_pages_without_loss_or_duplicates PASSED [ 8%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=0] PASSED [ 8%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=101] PASSED [ 9%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=abc] PASSED [ 9%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=1&limit=2] PASSED [ 9%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=] PASSED [ 9%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=garbage] PASSED [ 10%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=djF8bXx4fDF8Mg] PASSED [ 10%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=djF8bXx4fDk5OTk5OTk5OTk5OTk5OTk5OTk5fHk=] PASSED [ 10%]
student-tests/test_api.py::test_cursor_bound_to_chat PASSED [ 10%]
student-tests/test_api.py::test_read_after_write PASSED [ 10%]
student-tests/test_api.py::test_malformed_cursor_values_are_400_on_both_lists PASSED [ 11%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[\xff] PASSED [ 11%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"first","TEXT":"second"}] PASSED [ 11%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"a","text":"b"}] PASSED [ 11%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":123}] PASSED [ 12%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"valid"}}] PASSED [ 12%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"valid"}]] PASSED [ 12%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x"} {}] PASSED [ 12%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x","sender_id":"11111111-1111-4111-8111-111111111111"}] PASSED [ 13%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x","attachment_ids":null}] PASSED [ 13%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x","attachment_ids":["nope"]}] PASSED [ 13%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":" \n\t "}] PASSED [ 13%]
student-tests/test_api.py::test_ff_byte_body_on_registration_is_contract_error PASSED [ 13%]
student-tests/test_api.py::test_text_is_stored_verbatim_and_length_counts_raw_text PASSED [ 14%]
student-tests/test_api.py::test_unknown_attachment_ids_are_404 PASSED [ 14%]
student-tests/test_api.py::test_member_ids_are_compared_as_uuids_not_strings PASSED [ 14%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer \xe9] PASSED [ 14%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer .] PASSED [ 15%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer a b] PASSED [ 15%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer \xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9] PASSED [ 15%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[bearer\taaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 15%]
student-tests/test_api.py::test_login_with_a_body_is_rejected PASSED [ 16%]
student-tests/test_api.py::test_password_range_is_12_to_128_code_points PASSED [ 16%]
student-tests/test_api.py::test_every_api_response_carries_instance_and_request_id PASSED [ 16%]
student-tests/test_api.py::test_unicode_whitespace_only_strings_are_400[\xa0] PASSED [ 16%]
student-tests/test_api.py::test_unicode_whitespace_only_strings_are_400[\u2003\u2003] PASSED [ 17%]
student-tests/test_api.py::test_unicode_whitespace_only_strings_are_400[ \xa0\t\u3000] PASSED [ 17%]
student-tests/test_api.py::test_odd_registration_bodies_are_400_and_the_api_survives[{"username":"num_probe","display_name":"x","password":1e1000}] PASSED [ 17%]
student-tests/test_api.py::test_odd_registration_bodies_are_400_and_the_api_survives[{"username":"ff_probe","display_name":"x","password":"12345678901\xff"}] PASSED [ 17%]
student-tests/test_api.py::test_odd_registration_bodies_are_400_and_the_api_survives[{"username":"num_probe","display_name":1,"password":"Twelve-chars-ok"}] PASSED [ 17%]
student-tests/test_api.py::test_more_than_100_members_is_400 PASSED [ 18%]
student-tests/test_api.py::test_cursor_of_one_list_is_rejected_by_the_other PASSED [ 18%]
student-tests/test_attachments.py::test_png_and_jpeg_roundtrip_byte_for_byte PASSED [ 18%]
student-tests/test_attachments.py::test_metadata_reveals_no_storage_details PASSED [ 18%]
student-tests/test_attachments.py::test_original_is_not_stored_on_api_containers PASSED [ 19%]
student-tests/test_attachments.py::test_outsider_and_unknown_get_404 PASSED [ 19%]
student-tests/test_attachments.py::test_attachment_ids_are_checked_per_chat PASSED [ 19%]
student-tests/test_attachments.py::test_message_with_attachments_and_history PASSED [ 19%]
student-tests/test_attachments.py::test_idempotent_replay_with_attachments PASSED [ 20%]
student-tests/test_attachments.py::test_message_body_validation[{"attachment_ids":["%(a)s"]}] PASSED [ 20%]
student-tests/test_attachments.py::test_message_body_validation[{"text":null,"attachment_ids":["%(a)s"]}] PASSED [ 20%]
student-tests/test_attachments.py::test_message_body_validation[{"text":1,"attachment_ids":["%(a)s"]}] PASSED [ 20%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":null}] PASSED [ 20%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":"%(a)s"}] PASSED [ 21%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":{}}] PASSED [ 21%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":["%(a)s","%] PASSED [ 21%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":["%(a)s",1]] PASSED [ 21%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":["not-a-uui] PASSED [ 22%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"","attachment_ids":[]}] PASSED [ 22%]
student-tests/test_attachments.py::test_message_body_validation[{"text":" "}] PASSED [ 22%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":[],"sender_] PASSED [ 22%]
student-tests/test_attachments.py::test_at_most_ten_attachments PASSED [ 23%]
student-tests/test_attachments.py::test_size_limit_through_the_load_balancer PASSED [ 23%]
student-tests/test_attachments.py::test_pixel_limit_before_decoding PASSED [ 23%]
student-tests/test_attachments.py::test_exactly_40_megapixels_is_accepted PASSED [ 23%]
student-tests/test_attachments.py::test_bad_content_is_415[png: first 33 bytes of the fixture] PASSED [ 24%]
student-tests/test_attachments.py::test_bad_content_is_415[png: truncated] PASSED [ 24%]
student-tests/test_attachments.py::test_bad_content_is_415[png: corrupt IDAT, valid CRC] PASSED [ 24%]
student-tests/test_attachments.py::test_bad_content_is_415[png: fewer rows than IHDR] PASSED [ 24%]
student-tests/test_attachments.py::test_bad_content_is_415[png: flipped byte] PASSED [ 24%]
student-tests/test_attachments.py::test_bad_content_is_415[png: bytes after IEND] PASSED [ 25%]
student-tests/test_attachments.py::test_bad_content_is_415[jpeg: no scan data after SOS] PASSED [ 25%]
student-tests/test_attachments.py::test_bad_content_is_415[jpeg: truncated] PASSED [ 25%]
student-tests/test_attachments.py::test_bad_content_is_415[review: png row filter 5] PASSED [ 25%]
student-tests/test_attachments.py::test_bad_content_is_415[review: png row filter 0xff] PASSED [ 26%]
student-tests/test_attachments.py::test_bad_content_is_415[review: png IDAT not-a-zlib-stream] PASSED [ 26%]
student-tests/test_attachments.py::test_bad_content_is_415[review: jpeg 27 bytes, no tables/scan] PASSED [ 26%]
student-tests/test_attachments.py::test_bad_content_is_415[review: jpeg SOS component not in SOF] PASSED [ 26%]
student-tests/test_attachments.py::test_bad_content_is_415[mime: png bytes declared jpeg] PASSED [ 27%]
student-tests/test_attachments.py::test_bad_content_is_415[mime: jpeg bytes declared png] PASSED [ 27%]
student-tests/test_attachments.py::test_bad_content_is_415[mime: gif declared png] PASSED [ 27%]
student-tests/test_attachments.py::test_bad_content_is_415[mime: html declared png] PASSED [ 27%]
student-tests/test_attachments.py::test_bad_content_is_415[type: text/plain] PASSED [ 27%]
student-tests/test_attachments.py::test_bad_content_is_415[type: octet-stream] PASSED [ 28%]
student-tests/test_attachments.py::test_bad_content_is_415[type: multipart] PASSED [ 28%]
student-tests/test_attachments.py::test_bad_content_is_415[type: missing] PASSED [ 28%]
student-tests/test_attachments.py::test_empty_body_is_400 PASSED [ 28%]
student-tests/test_attachments.py::test_bad_filename_is_400[missing] PASSED [ 29%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=] PASSED [ 29%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=%20%20%20] PASSED [ 29%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=.] PASSED [ 29%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=..] PASSED [ 30%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=a%2Fb.png] PASSED [ 30%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=a%5Cb.png] PASSED [ 30%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=a%00b.png] PASSED [ 30%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=c1%C2%85.png] PASSED [ 31%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=tab%09.png] PASSED [ 31%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=photo%E2%80%AEgnp.exe] PASSED [ 31%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=%FF%FE.png] PASSED [ 31%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=a.png&filename=b.png] PASSED [ 31%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 32%]
student-tests/test_attachments.py::test_unicode_filename_is_kept_and_safely_exposed PASSED [ 32%]
student-tests/test_attachments.py::test_variant_parameter PASSED [ 32%]
student-tests/test_balancing.py::test_one_session_is_served_by_every_real_replica PASSED [ 32%]
student-tests/test_balancing.py::test_write_on_one_replica_is_read_on_the_other PASSED [ 33%]
student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[0-pg_hba] PASSED [ 33%]
student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[0-network] PASSED [ 33%]
student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[1-pg_hba] PASSED [ 33%]
student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[1-network] PASSED [ 34%]
student-tests/test_balancing.py::test_graceful_stop_of_each_replica_loses_no_request[0] PASSED [ 34%]
student-tests/test_balancing.py::test_graceful_stop_of_each_replica_loses_no_request[1] PASSED [ 34%]
student-tests/test_balancing.py::test_killed_replica_bounded_errors_recovery_and_no_duplicates[0] PASSED [ 34%]
student-tests/test_balancing.py::test_killed_replica_bounded_errors_recovery_and_no_duplicates[1] PASSED [ 34%]
student-tests/test_balancing.py::test_graceful_shutdown_order_in_logs PASSED [ 35%]
student-tests/test_balancing.py::test_full_restart_lb_rediscovers_all_replicas PASSED [ 35%]
student-tests/test_balancing.py::test_scale_up_and_down_is_picked_up_without_errors PASSED [ 35%]
student-tests/test_balancing.py::test_compose_policy_limits_ports_secrets_images PASSED [ 35%]
student-tests/test_balancing.py::test_running_containers_have_limits_and_no_bypass_ports PASSED [ 36%]
student-tests/test_balancing.py::test_migrations_ran_once_by_the_migrate_service PASSED [ 36%]
student-tests/test_consistency.py::test_interrupted_and_stalled_uploads_leave_nothing PASSED [ 36%]
student-tests/test_consistency.py::test_crash_after_staging_before_job_is_cleaned_by_janitor PASSED [ 36%]
student-tests/test_consistency.py::test_lost_answer_after_job_commit_still_becomes_ready PASSED [ 37%]
student-tests/test_consistency.py::test_fresh_pending_upload_is_not_touched_by_janitor PASSED [ 37%]
student-tests/test_db.py::test_registration_race_exactly_one_201_and_seven_409 PASSED [ 37%]
student-tests/test_db.py::test_create_chat_rolls_back_after_the_chat_row_was_inserted PASSED [ 37%]
student-tests/test_db.py::test_migrations_rerun_is_a_noop PASSED [ 37%]
student-tests/test_db.py::test_100_messages_from_10_clients_keep_order_and_cursor_walk PASSED [ 38%]
student-tests/test_db.py::test_secrets_are_not_stored_in_plain_text PASSED [ 38%]
student-tests/test_explain.py::test_late_page_uses_index_range_not_filter PASSED [ 38%]
student-tests/test_failures.py::test_valkey_failure[stop] PASSED [ 38%]
student-tests/test_failures.py::test_valkey_failure[pause] PASSED [ 39%]
student-tests/test_failures.py::test_postgres_failure[stop] PASSED [ 39%]
student-tests/test_failures.py::test_postgres_failure[pause] PASSED [ 39%]
student-tests/test_failures.py::test_locked_table_gives_bounded_503 PASSED [ 39%]
student-tests/test_failures.py::test_logout_during_valkey_outage_is_never_lost PASSED [ 40%]
student-tests/test_idempotency.py::test_replay_returns_the_same_201_and_message_from_every_replica PASSED [ 40%]
student-tests/test_idempotency.py::test_other_body_with_the_same_key_is_409_and_keeps_the_original PASSED [ 40%]
student-tests/test_idempotency.py::test_key_order_and_missing_attachment_ids_are_the_same_body PASSED [ 40%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[] PASSED [ 41%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 41%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[\u043a\u043b\u044e\u0447] PASSED [ 41%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a b] PASSED [ 41%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a/b] PASSED [ 41%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a,b] PASSED [ 42%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a\tb] PASSED [ 42%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[*] PASSED [ 42%]
student-tests/test_idempotency.py::test_repeated_key_header_is_400 PASSED [ 42%]
student-tests/test_idempotency.py::test_longest_key_and_every_allowed_character PASSED [ 43%]
student-tests/test_idempotency.py::test_scope_is_user_plus_chat_plus_key PASSED [ 43%]
student-tests/test_idempotency.py::test_outsider_and_revoked_session_never_see_the_stored_result PASSED [ 43%]
student-tests/test_idempotency.py::test_concurrent_same_key_through_different_replicas_creates_exactly_one PASSED [ 43%]
student-tests/test_idempotency.py::test_concurrent_same_key_different_bodies_one_wins PASSED [ 44%]
student-tests/test_idempotency.py::test_failure_after_the_key_insert_rolls_everything_back PASSED [ 44%]
student-tests/test_idempotency.py::test_client_timeout_then_retry_with_the_same_key_gives_the_committed_message PASSED [ 44%]
student-tests/test_idempotency.py::test_lock_timeout_is_a_transient_503_that_is_not_recorded PASSED [ 44%]
student-tests/test_idempotency.py::test_replay_after_the_serving_replica_is_stopped PASSED [ 44%]
student-tests/test_observability.py::test_upload_is_one_trace_api_relay_worker_s3_db PASSED [ 45%]
student-tests/test_observability.py::test_retry_is_visible_in_the_same_trace PASSED [ 45%]
student-tests/test_observability.py::test_logs_of_api_and_worker_are_joined_by_trace_id PASSED [ 45%]
student-tests/test_observability.py::test_no_ids_or_raw_paths_in_metric_labels PASSED [ 45%]
student-tests/test_observability.py::test_no_secrets_or_message_text_in_logs_and_traces PASSED [ 46%]
student-tests/test_observability.py::test_history_survives_restart_of_the_stores PASSED [ 46%]
student-tests/test_pipeline_flow.py::test_upload_is_202_queued_then_ready_with_contract_variants PASSED [ 46%]
student-tests/test_pipeline_flow.py::test_queued_attachment_is_attachable_failed_is_not PASSED [ 46%]
student-tests/test_pipeline_flow.py::test_worker_stopped_upload_202_content_409_restart_api_and_broker_then_ready PASSED [ 47%]
student-tests/test_pipeline_flow.py::test_broker_down_commit_to_publish_gap_is_closed_by_the_outbox PASSED [ 47%]
student-tests/test_pipeline_flow.py::test_relay_down_job_waits_in_outbox_not_lost PASSED [ 47%]
student-tests/test_pipeline_flow.py::test_crash_after_publish_before_confirm_is_recorded_gives_a_harmless_duplicate PASSED [ 47%]
student-tests/test_pipeline_flow.py::test_duplicate_and_reordered_deliveries_are_noops PASSED [ 48%]
student-tests/test_pipeline_flow.py::test_worker_crash_before_side_effect_lease_expires_and_job_completes PASSED [ 48%]
student-tests/test_pipeline_flow.py::test_worker_crash_after_s3_write_before_commit_republishes_without_duplicates PASSED [ 48%]
student-tests/test_pipeline_flow.py::test_worker_crash_after_commit_before_ack_redelivery_is_noop PASSED [ 48%]
student-tests/test_pipeline_flow.py::test_transient_errors_are_retried_with_jittered_backoff PASSED [ 48%]
student-tests/test_pipeline_flow.py::test_retry_exhausted_failed_registry_then_replay PASSED [ 49%]
student-tests/test_pipeline_flow.py::test_permanent_error_fails_at_once_without_retries PASSED [ 49%]
student-tests/test_pipeline_flow.py::test_memory_and_time_limits_of_the_worker PASSED [ 49%]
student-tests/test_pipeline_flow.py::test_bad_message_is_dead_lettered_not_processed PASSED [ 49%]
student-tests/test_pipeline_flow.py::test_hung_worker_loses_its_lease_and_cannot_publish PASSED [ 50%]
student-tests/test_pipeline_flow.py::test_graceful_worker_stop_finishes_the_running_attempt PASSED [ 50%]
student-tests/test_pipeline_flow.py::test_concurrency_is_bounded_by_prefetch PASSED [ 50%]
student-tests/test_pipeline_flow.py::test_queued_staging_is_never_deleted_even_after_retention PASSED [ 50%]
student-tests/test_pipeline_flow.py::test_retention_deletes_failed_staging_then_replay_is_refused PASSED [ 51%]
student-tests/test_pipeline_flow.py::test_cleanup_racing_a_replay_never_deletes_the_replayed_source PASSED [ 51%]
student-tests/test_pipeline_flow.py::test_reprocess_of_a_not_ready_upload_is_refused PASSED [ 51%]
student-tests/test_pipeline_flow.py::test_zz_invariants_hold_after_all_scenarios PASSED [ 51%]
student-tests/test_security.py::test_ingress_verifies_ca_and_hostname PASSED [ 51%]
student-tests/test_security.py::test_no_plaintext_entry_point PASSED [ 52%]
student-tests/test_security.py::test_lb_to_api_mtls_refuses_foreign_and_wrong_identity PASSED [ 52%]
student-tests/test_security.py::test_api_has_no_published_port_and_answers_only_mtls PASSED [ 52%]
student-tests/test_security.py::test_postgres_tls_only_and_roles_least_privilege PASSED [ 52%]
student-tests/test_security.py::test_valkey_tls_and_acl PASSED [ 53%]
student-tests/test_security.py::test_broker_tls_only_and_users_scoped PASSED [ 53%]
student-tests/test_security.py::test_s3_https_and_scoped_keys PASSED [ 53%]
student-tests/test_security.py::test_telemetry_endpoints_require_client_certificates PASSED [ 53%]
student-tests/test_security.py::test_openbao_policies_and_no_root_credential_in_apps PASSED [ 54%]
student-tests/test_security.py::test_openbao_not_dev_and_persistent PASSED [ 54%]
student-tests/test_security.py::test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones PASSED [ 54%]
student-tests/test_security.py::test_argon2id_hash_carries_salt_and_parameters PASSED [ 54%]
student-tests/test_security.py::test_failed_logins_are_rate_limited_with_retry_after PASSED [ 55%]
student-tests/test_security.py::test_x_instance_id_is_a_random_alias_without_hostname_or_ip PASSED [ 55%]
student-tests/test_security.py::test_running_containers_are_hardened PASSED [ 55%]
student-tests/test_security.py::test_no_secret_in_git_or_in_the_image PASSED [ 55%]
student-tests/test_sessions.py::test_short_ttl_expires[valkey] PASSED [ 55%]
student-tests/test_sessions.py::test_short_ttl_expires[postgres] PASSED [ 56%]
student-tests/test_sessions.py::test_restart_does_not_extend_ttl PASSED [ 56%]
student-tests/test_sessions.py::test_postgres_session_store PASSED [ 56%]
student-tests/test_storage_failures.py::test_s3_outage_is_503_and_text_keeps_working[stop] PASSED [ 56%]
student-tests/test_storage_failures.py::test_s3_outage_is_503_and_text_keeps_working[pause] PASSED [ 57%]
student-tests/test_storage_failures.py::test_upload_survives_failover_of_the_serving_replica PASSED [ 57%]
student-tests/test_storage_failures.py::test_bucket_is_private_outside_the_api PASSED [ 57%]
student-tests/test_storage_failures.py::test_s3_restart_keeps_objects PASSED [ 57%]
student-tests/unit/test_images.py::test_public_fixture_is_accepted PASSED [ 58%]
student-tests/unit/test_images.py::test_valid_png_kinds[rgba] PASSED [ 58%]
student-tests/unit/test_images.py::test_valid_png_kinds[palette] PASSED [ 58%]
student-tests/unit/test_images.py::test_valid_png_kinds[1bit] PASSED [ 58%]
student-tests/unit/test_images.py::test_valid_png_kinds[gray] PASSED [ 58%]
student-tests/unit/test_images.py::test_valid_png_kinds[noise] PASSED [ 59%]
student-tests/unit/test_images.py::test_valid_png_kinds[1x1] PASSED [ 59%]
student-tests/unit/test_images.py::test_interlaced_png_is_accepted PASSED [ 59%]
student-tests/unit/test_images.py::test_broken_png_is_415[first 33 bytes of the fixture] PASSED [ 59%]
student-tests/unit/test_images.py::test_broken_png_is_415[truncated (no IEND)] PASSED [ 60%]
student-tests/unit/test_images.py::test_broken_png_is_415[truncated in IDAT] PASSED [ 60%]
student-tests/unit/test_images.py::test_broken_png_is_415[flipped byte -> CRC error] PASSED [ 60%]
student-tests/unit/test_images.py::test_broken_png_is_415[garbage IDAT with valid CRC] PASSED [ 60%]
student-tests/unit/test_images.py::test_broken_png_is_415[fewer rows than IHDR] PASSED [ 61%]
student-tests/unit/test_images.py::test_broken_png_is_415[bytes after IEND (polyglot)] PASSED [ 61%]
student-tests/unit/test_images.py::test_broken_png_is_415[text] PASSED [ 61%]
student-tests/unit/test_images.py::test_broken_png_is_415[gif] PASSED [ 61%]
student-tests/unit/test_images.py::test_broken_png_is_415[two bytes of a signature] PASSED [ 62%]
student-tests/unit/test_images.py::test_pixel_limit_is_checked_from_the_header PASSED [ 62%]
student-tests/unit/test_images.py::test_png_verification_is_streaming_and_fast PASSED [ 62%]
student-tests/unit/test_images.py::test_jpeg_header_is_parsed_incrementally PASSED [ 62%]
student-tests/unit/test_images.py::test_valid_jpeg[base] SKIPPED (dj...) [ 62%]
student-tests/unit/test_images.py::test_valid_jpeg[prog] SKIPPED (dj...) [ 63%]
student-tests/unit/test_images.py::test_broken_jpeg_is_415[no scan data after SOS-] SKIPPED [ 63%]
student-tests/unit/test_images.py::test_broken_jpeg_is_415[truncated-] SKIPPED [ 63%]
student-tests/unit/test_images.py::test_good_filenames[photo.png] PASSED [ 63%]
student-tests/unit/test_images.py::test_good_filenames[\u0444\u043e\u0442\u043e \u043e\u0442\u043f\u0443\u0441\u043a\u0430.jpg] PASSED [ 64%]
student-tests/unit/test_images.py::test_good_filenames[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 64%]
student-tests/unit/test_images.py::test_good_filenames[emoji \U0001f468\u200d\U0001f469\u200d\U0001f467.png] PASSED [ 64%]
student-tests/unit/test_images.py::test_good_filenames[ x ] PASSED [ 64%]
student-tests/unit/test_images.py::test_good_filenames[..x] PASSED [ 65%]
student-tests/unit/test_images.py::test_bad_filenames[] PASSED [ 65%]
student-tests/unit/test_images.py::test_bad_filenames[ ] PASSED [ 65%]
student-tests/unit/test_images.py::test_bad_filenames[\u3000] PASSED [ 65%]
student-tests/unit/test_images.py::test_bad_filenames[.] PASSED [ 65%]
student-tests/unit/test_images.py::test_bad_filenames[..] PASSED [ 66%]
student-tests/unit/test_images.py::test_bad_filenames[a/b.png] PASSED [ 66%]
student-tests/unit/test_images.py::test_bad_filenames[a\\b.png] PASSED [ 66%]
student-tests/unit/test_images.py::test_bad_filenames[a\x00b] PASSED [ 66%]
student-tests/unit/test_images.py::test_bad_filenames[c1\x85.png] PASSED [ 67%]
student-tests/unit/test_images.py::test_bad_filenames[tab\t.png] PASSED [ 67%]
student-tests/unit/test_images.py::test_bad_filenames[del\x7f.png] PASSED [ 67%]
student-tests/unit/test_images.py::test_bad_filenames[x\u2028y] PASSED [ 67%]
student-tests/unit/test_images.py::test_bad_filenames[photo\u202egnp.exe] PASSED [ 68%]
student-tests/unit/test_images.py::test_bad_filenames[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 68%]
student-tests/unit/test_images.py::test_filename_must_be_single_and_present PASSED [ 68%]
student-tests/unit/test_images.py::test_query_must_be_valid_utf8 PASSED [ 68%]
student-tests/unit/test_lab7.py::test_dns_names_only_from_subject_alt_name PASSED [ 68%]
student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[sans0-True] PASSED [ 69%]
student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[sans1-False] PASSED [ 69%]
student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[sans2-False] PASSED [ 69%]
student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[sans3-False] PASSED [ 69%]
student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[None-False] PASSED [ 70%]
student-tests/unit/test_lab7.py::test_protocol_aborts_a_plaintext_transport PASSED [ 70%]
student-tests/unit/test_lab7.py::test_allowlist_cannot_be_empty PASSED [ 70%]
student-tests/unit/test_lab7.py::test_server_context_requires_client_certificates_of_the_internal_ca_only PASSED [ 70%]
student-tests/unit/test_lab7.py::test_argon2_parameters_are_configurable_but_never_below_the_minimum PASSED [ 71%]
student-tests/unit/test_lab7.py::test_hash_carries_the_configured_parameters_and_old_hashes_still_verify PASSED [ 71%]
student-tests/unit/test_lab7.py::test_limit_per_username_with_retry_after PASSED [ 71%]
student-tests/unit/test_lab7.py::test_limit_per_ip_and_reset_on_success PASSED [ 71%]
student-tests/unit/test_lab7.py::test_secrets_come_from_openbao_first PASSED [ 72%]
student-tests/unit/test_lab7.py::test_openbao_refusal_is_a_config_error_without_retry PASSED [ 72%]
student-tests/unit/test_lab7.py::test_pki_script_never_prints_key_material PASSED [ 72%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size0-256-expected0] PASSED [ 72%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size1-256-expected1] PASSED [ 72%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size2-256-expected2] PASSED [ 73%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size3-256-expected3] PASSED [ 73%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size4-256-expected4] PASSED [ 73%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size5-256-expected5] PASSED [ 73%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size6-256-expected6] PASSED [ 74%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size7-1280-expected7] PASSED [ 74%]
student-tests/unit/test_pipeline.py::test_center_square PASSED [ 74%]
student-tests/unit/test_pipeline.py::test_public_fixture_variants_match_the_contract PASSED [ 74%]
student-tests/unit/test_pipeline.py::test_small_image_is_not_upscaled_but_crop_is PASSED [ 75%]
student-tests/unit/test_pipeline.py::test_big_image_is_bounded_by_1280 PASSED [ 75%]
student-tests/unit/test_pipeline.py::test_exif_orientation_is_applied_and_dropped PASSED [ 75%]
student-tests/unit/test_pipeline.py::test_alpha_is_composited_on_white_for_jpeg_and_kept_for_webp PASSED [ 75%]
student-tests/unit/test_pipeline.py::test_metadata_is_not_copied PASSED [ 75%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[RGBA] PASSED [ 76%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[P] PASSED [ 76%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[1] PASSED [ 76%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[L] PASSED [ 76%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[LA] PASSED [ 77%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[RGB] PASSED [ 77%]
student-tests/unit/test_pipeline.py::test_16_bit_grey_is_scaled_not_clipped PASSED [ 77%]
student-tests/unit/test_pipeline.py::test_pipeline_versions_differ_in_bytes_not_in_geometry PASSED [ 77%]
student-tests/unit/test_pipeline.py::test_pixel_limit_is_checked_before_decoding PASSED [ 78%]
student-tests/unit/test_pipeline.py::test_child_process_protocol_round_trip PASSED [ 78%]
student-tests/unit/test_pipeline.py::test_encoded_message_matches_jobs_schema_and_carries_ids_only PASSED [ 78%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change0] PASSED [ 78%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change1] PASSED [ 79%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change2] PASSED [ 79%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change3] PASSED [ 79%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change4] PASSED [ 79%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change5] PASSED [ 79%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change6] PASSED [ 80%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change7] PASSED [ 80%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change8] PASSED [ 80%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change9] PASSED [ 80%]
student-tests/unit/test_pipeline.py::test_garbage_is_rejected PASSED [ 81%]
student-tests/unit/test_pipeline.py::test_backoff_is_full_jitter_and_capped PASSED [ 81%]
student-tests/unit/test_pipeline.py::test_pipeline_settings PASSED [ 81%]
student-tests/unit/test_telemetry.py::test_server_span_continues_incoming_traceparent PASSED [ 81%]
student-tests/unit/test_telemetry.py::test_without_traceparent_a_new_root_trace_is_started PASSED [ 82%]
student-tests/unit/test_telemetry.py::test_5xx_is_an_error_4xx_is_not PASSED [ 82%]
student-tests/unit/test_telemetry.py::test_health_probes_get_no_span_and_unknown_paths_one_label PASSED [ 82%]
student-tests/unit/test_telemetry.py::test_http_metric_attributes_are_low_cardinality_and_buckets_fit_seconds PASSED [ 82%]
student-tests/unit/test_telemetry.py::test_job_message_carries_traceparent_in_the_schema_field PASSED [ 82%]
student-tests/unit/test_telemetry.py::test_log_records_carry_trace_context_and_fields PASSED [ 83%]
student-tests/unit/test_telemetry.py::test_successful_probe_lines_are_not_exported_failed_ones_are PASSED [ 83%]
student-tests/unit/test_telemetry.py::test_child_span_only_inside_a_traced_operation PASSED [ 83%]
student-tests/unit/test_unit.py::test_valid_passwords[Twelve-chars] PASSED [ 83%]
student-tests/unit/test_unit.py::test_valid_passwords[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 84%]
student-tests/unit/test_unit.py::test_valid_passwords[\u043f\u0430\u0440\u043e\u043b\u044c:\u0441:\u0434\u0432\u043e\u0435\u0442\u043e\u0447\u0438\u044f\u043c\u0438] PASSED [ 84%]
student-tests/unit/test_unit.py::test_valid_passwords[\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600] PASSED [ 84%]
student-tests/unit/test_unit.py::test_valid_passwords[a b c d e f g] PASSED [ 84%]
student-tests/unit/test_unit.py::test_invalid_passwords[short-11ch] PASSED [ 85%]
student-tests/unit/test_unit.py::test_invalid_passwords[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 85%]
student-tests/unit/test_unit.py::test_invalid_passwords[ ] PASSED [ 85%]
student-tests/unit/test_unit.py::test_invalid_passwords[\t\n\u3000\t\n\u3000\t\n\u3000\t\n\u3000\t\n\u3000] PASSED [ 85%]
student-tests/unit/test_unit.py::test_invalid_passwords[\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800] PASSED [ 86%]
student-tests/unit/test_unit.py::test_invalid_passwords[None] PASSED [ 86%]
student-tests/unit/test_unit.py::test_invalid_passwords[123456789012] PASSED [ 86%]
student-tests/unit/test_unit.py::test_text_may_contain_nul_but_not_lone_surrogates PASSED [ 86%]
student-tests/unit/test_unit.py::test_cursor_roundtrip_and_binding PASSED [ 86%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|253402300800000000|11111111-1111-4111-8111-111111111111] PASSED [ 87%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|9999999999999999999|11111111-1111-4111-8111-111111111111] PASSED [ 87%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|-1|11111111-1111-4111-8111-111111111111] PASSED [ 87%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|1|not-a-uuid] PASSED [ 87%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|1|11111111-1111-4111-8111-11111111111G] PASSED [ 88%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v2|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|1|11111111-1111-4111-8111-111111111111] PASSED [ 88%]
student-tests/unit/test_unit.py::test_time_helpers_are_exact PASSED [ 88%]
student-tests/unit/test_unit.py::test_basic_is_parsed_and_password_may_contain_colons PASSED [ 88%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[None] PASSED [ 89%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[] PASSED [ 89%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic] PASSED [ 89%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic \xe9] PASSED [ 89%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic !!!!] PASSED [ 89%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic bm8tY29sb24=] PASSED [ 90%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic //46cHc=] PASSED [ 90%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic OnBhc3N3b3Jk] PASSED [ 90%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic YWxpY2U6] PASSED [ 90%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic 0JDQu9C40YHQsDpwdw==] PASSED [ 91%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 91%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA] PASSED [ 91%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[None] PASSED [ 91%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[] PASSED [ 92%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer] PASSED [ 92%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer short] PASSED [ 92%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!] PASSED [ 92%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Basic YWxpY2U6cGFzc3dvcmQtMTIz] PASSED [ 93%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Token aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 93%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer \xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9] PASSED [ 93%]
student-tests/unit/test_unit.py::test_bearer_ok PASSED [ 93%]
student-tests/unit/test_unit.py::test_argon2id_hash_and_verify PASSED [ 93%]
student-tests/unit/test_unit.py::test_s3_settings_are_validated_and_contract_limits_cannot_be_raised PASSED [ 94%]
student-tests/unit/test_unit.py::test_settings_read_secret_files_and_contract_names PASSED [ 94%]
student-tests/unit/test_unit.py::test_valid_idempotency_keys[a] PASSED [ 94%]
student-tests/unit/test_unit.py::test_valid_idempotency_keys[kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk] PASSED [ 94%]
student-tests/unit/test_unit.py::test_valid_idempotency_keys[A-Za-z0-9._:-] PASSED [ 95%]
student-tests/unit/test_unit.py::test_valid_idempotency_keys[2026-10-16T10:00:00.1] PASSED [ 95%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[None] PASSED [ 95%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[] PASSED [ 95%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk] PASSED [ 96%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[\u043a\u043b\u044e\u0447] PASSED [ 96%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a b] PASSED [ 96%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a/b] PASSED [ 96%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a,b] PASSED [ 96%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a\tb] PASSED [ 97%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a\x00b] PASSED [ 97%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[*] PASSED [ 97%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[\xe9] PASSED [ 97%]
student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[{"text":"a","text":"b"}] PASSED [ 98%]
student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[{"a":{"x":1,"x":2}}] PASSED [ 98%]
student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[\xff] PASSED [ 98%]
student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[{"text":"x"} {}] PASSED [ 98%]
student-tests/unit/test_unit.py::test_attachment_ids_absent_equals_empty_and_is_validated PASSED [ 99%]
student-tests/unit/test_unit.py::test_request_fingerprint_ignores_key_order_and_default_attachments PASSED [ 99%]
student-tests/unit/test_unit.py::test_instance_id_is_a_random_alias_stable_per_process_and_validated PASSED [ 99%]
student-tests/unit/test_unit.py::test_idempotency_ttl_cannot_be_below_24_hours PASSED [ 99%]
student-tests/unit/test_unit.py::test_message_write_path_setting PASSED [100%]
============================ slowest 15 durations =============================
61.16s call student-tests/test_balancing.py::test_full_restart_lb_rediscovers_all_replicas
60.93s call student-tests/test_sessions.py::test_restart_does_not_extend_ttl
56.99s call student-tests/test_storage_failures.py::test_s3_outage_is_503_and_text_keeps_working[stop]
55.48s call student-tests/test_sessions.py::test_postgres_session_store
54.64s call student-tests/test_observability.py::test_history_survives_restart_of_the_stores
52.70s call student-tests/test_pipeline_flow.py::test_worker_crash_after_s3_write_before_commit_republishes_without_duplicates
52.46s call student-tests/test_pipeline_flow.py::test_hung_worker_loses_its_lease_and_cannot_publish
50.53s call student-tests/test_pipeline_flow.py::test_worker_stopped_upload_202_content_409_restart_api_and_broker_then_ready
49.34s call student-tests/test_consistency.py::test_crash_after_staging_before_job_is_cleaned_by_janitor
48.36s call student-tests/test_pipeline_flow.py::test_memory_and_time_limits_of_the_worker
45.57s call student-tests/test_pipeline_flow.py::test_cleanup_racing_a_replay_never_deletes_the_replayed_source
43.27s call student-tests/test_pipeline_flow.py::test_graceful_worker_stop_finishes_the_running_attempt
41.90s call student-tests/test_pipeline_flow.py::test_queued_staging_is_never_deleted_even_after_retention
41.54s call student-tests/test_pipeline_flow.py::test_retry_exhausted_failed_registry_then_replay
41.46s call student-tests/test_storage_failures.py::test_s3_restart_keeps_objects
================= 425 passed, 4 skipped in 1919.83s (0:31:59) =================
[exit 0]
+7
View File
@@ -0,0 +1,7 @@
# make test-security (недоверенный CA)
# 2026-11-28T14:15:46+00:00
$ .venv\Scripts\python.exe tests/security.py --base-url https://localhost:8443 --ca-file secrets\pki\public-ca.crt
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
[exit 0]
+46
View File
@@ -0,0 +1,46 @@
# Телеметрия по mTLS: trace + logs
# 2026-11-28T14:19:09+00:00
$ .venv\Scripts\python.exe scripts/trace_demo.py
upload: HTTP 202, status=queued, X-Request-Id=trace-demo-68ea29f5, X-Instance-Id=i-83def22f481a, X-Trace-Id=fcefd6efe84d1bd8a5c933e4b6b7f66d
sent traceparent: 00-fcefd6efe84d1bd8a5c933e4b6b7f66d-69c3a1cf82244c3e-01
attachment f3fa88b3-5dbb-42b5-b1f5-a57d60c35f15: ready, variants=['thumbnail', 'crop', 'optimized']
Tempo: trace fcefd6efe84d1bd8a5c933e4b6b7f66d, 19 spans
+ 0.0 ms 37.6 ms [messenger-api] SERVER POST /api/v1/chats/{chat_id}/attachments {"http.route": "/api/v1/chats/{chat_id}/attachments", "http.response.status_code": "202"}
+ 1.2 ms 2.4 ms [messenger-api] CLIENT db ensure_member {"db.client.connection.wait_time_ms": 0.572}
+ 5.7 ms 5.1 ms [messenger-api] CLIENT db create_intent {"db.client.connection.wait_time_ms": 0.531}
+ 11.2 ms 16.0 ms [messenger-api] CLIENT s3 put
+ 27.6 ms 8.6 ms [messenger-api] CLIENT db enqueue {"db.client.connection.wait_time_ms": 0.651}
+ 88.4 ms 5.7 ms [messenger-relay] PRODUCER messenger.jobs publish {"messenger.job.attempt": "1"}
+ 94.5 ms 763.7 ms [messenger-worker] CONSUMER messenger.attachment-jobs process {"messenger.job.attempt": "1", "messenger.job.outcome": "succeeded"}
+ 94.7 ms 12.1 ms [messenger-worker] CLIENT db jobs.claim {"db.client.connection.wait_time_ms": 0.55}
+ 107.0 ms 9.7 ms [messenger-worker] INTERNAL s3 download
+ 107.1 ms 8.6 ms [messenger-worker] CLIENT s3 get
+ 117.0 ms 679.8 ms [messenger-worker] INTERNAL image render
+ 797.1 ms 27.9 ms [messenger-worker] CLIENT s3 put
+ 798.9 ms 25.6 ms [messenger-worker] CLIENT s3 put
+ 800.4 ms 23.1 ms [messenger-worker] CLIENT s3 put
+ 802.3 ms 23.5 ms [messenger-worker] CLIENT s3 put
+ 826.1 ms 17.9 ms [messenger-worker] CLIENT db jobs.complete {"db.client.connection.wait_time_ms": 0.641}
+ 844.3 ms 3.5 ms [messenger-worker] CLIENT db delete_staging {"db.client.connection.wait_time_ms": 0.581}
+ 848.0 ms 3.3 ms [messenger-worker] CLIENT s3 delete
+ 851.6 ms 5.6 ms [messenger-worker] CLIENT db delete_staging {"db.client.connection.wait_time_ms": 0.67}
Loki: 4 log records with trace_id=fcefd6efe84d1bd8a5c933e4b6b7f66d
messenger-api attachment_queued span_id=c63846abe775f110 request_id=trace-demo-68ea29f5
messenger-api request span_id=c63846abe775f110 request_id=trace-demo-68ea29f5 route=/api/v1/chats/{chat_id}/attachments status=202
messenger-worker staging_deleted span_id=c5745bf8195fd208
messenger-worker job_done span_id=c5745bf8195fd208 job_id=b42f1fef-a3aa-408f-a3af-f5383bcb587c outcome=succeeded
Checks:
[PASS] API SERVER span continues our traceparent (parent = our span id)
[PASS] relay PRODUCER is inside the upload trace (ancestor = API SERVER span)
[PASS] worker CONSUMER is a child of the PRODUCER
[PASS] worker wrote to S3 inside the job (s3 put spans)
[PASS] worker committed the result (db jobs.complete span)
[PASS] API log record of the request has this trace_id and our X-Request-Id
[PASS] worker log record (job_done) has this trace_id
services in logs: ['messenger-api', 'messenger-worker']
[exit 0]
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,16 @@
# Dashboards from JSON files in Git (infra/grafana/dashboards, mounted read-only). Editing in the
# UI is possible but not saved: the files are the source of truth (scripts/build_dashboard.py
# generates messenger.json).
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: true
allowUiUpdates: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,92 @@
# Grafana datasources, provisioned at start (nothing is clicked by hand). The UIDs are FIXED:
# the dashboard JSON, the trace->logs and logs->trace links refer to exactly these UIDs
# (prometheus / loki / tempo). A datasource without a fixed uid gets a random one and every
# reference to it breaks ("data source not found").
# Lab 7: every datasource is HTTPS with server verification (internal CA, serverName = the SAN)
# and Grafana's own client certificate (SAN grafana): the three backends require one, Prometheus
# also checks the SAN allowlist. The PEM files are read at provisioning time ($__file{}), from
# Docker secrets mounted only into Grafana.
apiVersion: 1
deleteDatasources:
- {name: Prometheus, orgId: 1}
- {name: Loki, orgId: 1}
- {name: Tempo, orgId: 1}
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
editable: false
secureJsonData: &tls_files
tlsCACert: $__file{/run/secrets/internal-ca.crt}
tlsClientCert: $__file{/run/secrets/grafana.crt}
tlsClientKey: $__file{/run/secrets/grafana.key}
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
serverName: prometheus
httpMethod: POST
timeInterval: 15s # = scrape/evaluation interval: $__rate_interval >= 4 x 15 s
prometheusType: Prometheus
prometheusVersion: 3.16.0
manageAlerts: true # show the Prometheus alert rules in Grafana's alert list
exemplarTraceIdDestinations: []
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
editable: false
secureJsonData: *tls_files
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
serverName: loki
maxLines: 1000
# log line -> its trace in Tempo (trace_id is structured metadata of the OTLP record)
derivedFields:
- name: trace_id
matcherType: label
matcherRegex: trace_id
datasourceUid: tempo
url: "$${__value.raw}"
urlDisplayLabel: "Trace in Tempo"
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
editable: false
secureJsonData: *tls_files
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
serverName: tempo
# span -> the log records of the same trace (and service) in Loki
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: "-5m"
spanEndTimeShift: "5m"
customQuery: true
query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__trace.traceId}"'
tracesToMetrics:
datasourceUid: prometheus
spanStartTimeShift: "-5m"
spanEndTimeShift: "5m"
tags:
- {key: service.name, value: job}
queries:
- name: HTTP p95 of this service
query: 'histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{$$__tags}[1m])))'
search:
hide: false
nodeGraph:
enabled: false
lokiSearch:
datasourceUid: loki
+132
View File
@@ -0,0 +1,132 @@
# HAProxy 3.2 LTS — the single public entry point of the lab 4 stand (compose service `lb`).
#
# Backend discovery: Docker DNS name `api` returns one A record per RUNNING replica of the
# compose service `api` (deploy.replicas / --scale). server-template keeps 8 slots and
# re-resolves every second, so scale up/down, a restarted container with a new IP and a
# full stack restart are picked up without restarting the LB. A stopped container drops
# out of DNS and its slot goes to MAINT.
#
# Readiness: an ACTIVE check `GET /health/ready` (PostgreSQL + Valkey + S3 reachable, not
# draining) every 1 s; 2 failures -> DOWN, 2 successes -> UP. Passive errors do not decide
# anything on their own, and there are NO fallback servers without checks: a replica that
# answers /health/live but not /health/ready never gets traffic while a fully ready one exists.
#
# Degraded mode (lab 4): S3 is a SHARED dependency. If it is down, /health/ready is 503 on
# every replica and backend `api` has no server. Instead of answering 503 to everything, the
# frontend then switches to backend `api_core`: the same replicas, checked by
# /health/ready/core (PostgreSQL + Valkey, not draining). Chats and text messages keep working,
# every attachment request is answered 503 by the API itself (fast, S3_TIMEOUT_SECONDS).
# A replica that alone lost S3 (e.g. its storage network) is DOWN in `api` while the others are
# UP, so it gets no traffic at all.
# Worst case detection of a failed replica (a check answered at once counts at once, a check
# that hangs counts only after `timeout check`):
# fast explicit 503 (drain after SIGTERM): inter 1 s + fastinter 0.5 s ~= 1.5 s;
# slow ready (PostgreSQL/Valkey unreachable: the answer takes ~1 s = timeout check)
# or frozen process: inter 1 s + 1 s + fastinter 0.5 s + 1 s ~= 3.5 s.
# Requests that could not even be SENT (connection refused/reset before the request)
# are retried on another replica (retry-on conn-failure + redispatch) - safe for POST,
# because the API has not seen them. Nothing that may have reached the API is retried by
# the LB: an uncertain POST is retried by the CLIENT with the same Idempotency-Key.
# No sticky sessions: sessions live in Valkey, every replica serves every user.
#
# Lab 7, LB -> API = mandatory mTLS (contracts/trust-matrix.md). Every server line (traffic AND the
# active health checks, which inherit `ssl`):
# ssl verify required ca-file internal-ca.crt verifyhost api the replica must present a certificate
# of the internal CA with SAN `api`: no MITM, no fake replica;
# crt lb.pem our client identity (internal CA, SAN `lb`, EKU clientAuth).
# The replica checks the chain AND the SAN allowlist (src/messenger/tls.py). Plaintext to the API is
# impossible: the replicas have no plaintext listener on the network.
global
log stdout format raw local0 info
maxconn 4096
# Runtime API for `show servers state` / `show stat` (scripts and tests, no network port).
stats socket /var/lib/haproxy/admin.sock mode 600 level admin
hard-stop-after 15s
resolvers docker
nameserver dns1 127.0.0.11:53
accepted_payload_size 8192
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold other 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
defaults
mode http
log global
option httplog
option dontlognull
option http-keep-alive
timeout connect 1s
timeout client 30s
timeout server 10s # > DB_TIMEOUT_SECONDS (3 s): the API answers 503 itself first
timeout http-request 10s
timeout http-keep-alive 10s
timeout queue 3s
timeout check 1s
retries 2
retry-on conn-failure
option redispatch 1
# Errors generated by the LB itself, in the contract error format with the same request id.
# They carry no X-Instance-Id: no API replica produced them. 502/504 = the outcome of the
# request is unknown (a replica died mid-request / did not answer in time): retry with the
# same Idempotency-Key. 503 = no ready replica at all.
http-error status 502 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API-реплика оборвала ответ; повторите с тем же Idempotency-Key\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]"
http-error status 503 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"Нет готовых API-реплик\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]"
http-error status 504 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API-реплика не ответила вовремя; повторите с тем же Idempotency-Key\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]"
frontend public
# Lab 7: the ONLY public listener is HTTPS. Certificate of the public CA (SAN localhost,
# 127.0.0.1, ::1; scripts/init_pki.py), TLS 1.2+. There is no plaintext listener to fall back to.
bind :8443 ssl crt /run/secrets/ingress.pem ssl-min-ver TLSv1.2 alpn http/1.1
# One request id end to end: keep a valid client X-Request-Id, otherwise create one; the
# API echoes it, and errors generated by the LB itself carry the same value.
http-request set-header X-Request-Id %[uuid()] unless { req.hdr(x-request-id) -m reg ^[A-Za-z0-9._:-]{1,128}$ }
http-request set-var(txn.request_id) req.hdr(x-request-id)
# Lab 7: the client address for the API's login rate limit. OVERWRITTEN (never appended to a
# client-supplied value), so a client cannot pick its own "IP"; the API trusts it only because
# nobody but this LB (mTLS identity lb) can connect to the API.
http-request set-header X-Forwarded-For %[src]
log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq rid=%[var(txn.request_id)] \"%HM %HPO\""
use_backend api if { nbsrv(api) gt 0 }
default_backend api_core
backend api
balance roundrobin
# Uploads (<= 10 MiB body + verification + S3 PUT): the API's own budget is
# UPLOAD_READ_TIMEOUT 30 s + IMAGE_VERIFY 10 s + S3; the LB must not cut it at 10 s (a 504
# after a successful upload would make the client upload a duplicate).
acl is_upload path_reg ^/api/v1/chats/[^/]+/attachments$
http-request set-timeout server 60s if is_upload METH_POST
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 ssl verify required ca-file /run/secrets/internal-ca.crt verifyhost api crt /run/secrets/lb.pem ssl-min-ver TLSv1.2
server-template api 8 api:8443
# Degraded mode only (see the header): used when NO replica is fully ready.
backend api_core
balance roundrobin
acl is_upload path_reg ^/api/v1/chats/[^/]+/attachments$
http-request set-timeout server 60s if is_upload METH_POST
option httpchk
http-check send meth GET uri /health/ready/core ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 ssl verify required ca-file /run/secrets/internal-ca.crt verifyhost api crt /run/secrets/lb.pem ssl-min-ver TLSv1.2
server-template core 8 api:8443
# Status page for the container healthcheck only: bound to the container's own loopback and NOT
# published (lab 7: only the TLS ingress leaves the host). Operators use the admin socket
# (`docker compose exec lb ...`, scripts/lbctl.py).
frontend stats
bind 127.0.0.1:8404
stats enable
stats uri /
stats refresh 2s
stats show-legends
+68
View File
@@ -0,0 +1,68 @@
# Loki 3.7 (grafana/loki:3.7.10), single binary, lab 6: the LOGS store.
#
# Logs arrive from the Collector over OTLP (POST /otlp/v1/logs). Loki turns a few RESOURCE
# attributes into index labels (service_name, service_instance_id, deployment_environment_name):
# few values, small index. Log-record attributes (event, request_id, job_id, trace_id, span_id,
# route, status...) are stored as STRUCTURED METADATA next to the line - searchable
# (`{service_name="messenger-api"} | trace_id="..."`) without creating a stream per value.
# That is why an id such as request_id/attachment_id never becomes a label (it would create a
# new stream - and index entries - per request, see docs/DEFENSE.md).
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
grpc_listen_address: 127.0.0.1
log_level: warn
# Lab 7: HTTPS + mandatory client certificate of the internal CA (otel-collector pushes,
# grafana queries, prometheus scrapes). gRPC is internal to the single binary: loopback only.
http_tls_config:
cert_file: /run/secrets/loki.crt
key_file: /run/secrets/loki.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/secrets/internal-ca.crt
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2026-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 168h # 7 days of logs, deleted by the compactor
ingestion_rate_mb: 8
ingestion_burst_size_mb: 16
max_query_lookback: 168h
volume_enabled: true
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
ingester:
wal:
dir: /loki/wal # on the named volume: a restart does not lose buffered logs
pattern_ingester:
enabled: false
analytics:
reporting_enabled: false
+39
View File
@@ -0,0 +1,39 @@
# OpenBao 2.7 server of the lab 7 stand (compose service `openbao`). NOT dev mode:
# * persistent storage: integrated storage (Raft, ONE node - OpenBao 2.7 has no "file" backend
# any more) on the named volume baodata (/openbao/file). Everything in it is encrypted by the
# barrier key; it starts SEALED after every start and is unsealed by the operator
# (scripts/bao_operator.py unseal). Single node = no replication: losing the volume loses the
# secrets (they can be re-created from ./secrets by `bootstrap` on a fresh instance).
# * TLS listener only (internal CA, SAN openbao + localhost/127.0.0.1 for the operator CLI inside
# the container), TLS 1.2+; no plaintext listener, no UI, port not published on the host. The
# Raft cluster port 8201 uses OpenBao's own automatic TLS and has no peers here.
# * disable_mlock: the container runs without IPC_LOCK (no extra capabilities). The trade-off -
# memory pages could be swapped - is accepted on this single-host lab stand: the container has
# memswap_limit = memory limit (no swap). See docs/OPERATOR.md.
ui = false
disable_mlock = true
api_addr = "https://openbao:8200"
cluster_addr = "https://openbao:8201"
log_level = "warn"
storage "raft" {
path = "/openbao/file"
node_id = "openbao-1"
}
# Audit log of every request and response (secret values HMAC'ed, never in clear) to the container
# stdout: `docker compose logs openbao` shows who read what and every denied request.
audit "file" "stdout" {
description = "lab 7 audit log"
options {
file_path = "stdout"
}
}
listener "tcp" {
address = "0.0.0.0:8200"
cluster_address = "0.0.0.0:8201"
tls_cert_file = "/run/secrets/openbao.crt"
tls_key_file = "/run/secrets/openbao.key"
tls_min_version = "tls12"
}
+16
View File
@@ -0,0 +1,16 @@
# Policy of the AppRole `api` (API replicas). Exactly one secret path, read only:
# messenger/data/api = database_url (role messenger_api), cache_url (Valkey ACL user api),
# s3_access_key_id / s3_secret_access_key (identity messenger-api: Write staging + Read final).
# No metadata/list/write, no other service's path, no sys/*, no policy management. The token is
# created with token_no_default_policy=true, so self-management is granted explicitly below.
path "messenger/data/api" {
capabilities = ["read"]
}
path "auth/token/lookup-self" {
capabilities = ["read"]
}
path "auth/token/revoke-self" {
capabilities = ["update"]
}
+13
View File
@@ -0,0 +1,13 @@
# Policy of the AppRole `relay`: messenger/data/relay = database_url (role messenger_relay) and
# broker_url (RabbitMQ user relay: publish to the jobs exchange only). Read only, nothing else.
path "messenger/data/relay" {
capabilities = ["read"]
}
path "auth/token/lookup-self" {
capabilities = ["read"]
}
path "auth/token/revoke-self" {
capabilities = ["update"]
}
+14
View File
@@ -0,0 +1,14 @@
# Policy of the AppRole `worker`: messenger/data/worker = database_url (role messenger_worker),
# broker_url (RabbitMQ user worker: consume the jobs queue only), s3 key pair messenger-worker
# (staging + final, no List, no Admin). No admin credentials of the API, the database or S3.
path "messenger/data/worker" {
capabilities = ["read"]
}
path "auth/token/lookup-self" {
capabilities = ["read"]
}
path "auth/token/revoke-self" {
capabilities = ["update"]
}
+113
View File
@@ -0,0 +1,113 @@
# OpenTelemetry Collector (otel/opentelemetry-collector-contrib 0.165.0), labs 6-7.
#
# API x2 / relay / worker --OTLP/HTTPS (mTLS) :4318--> [receiver otlp]
# -> memory_limiter -> batch -> exporters (all HTTPS + client certificate otel-collector):
# traces -> Tempo (otlp_http/tempo, https://tempo:4318/v1/traces)
# metrics -> Prometheus (otlp_http/prometheus, https://prometheus:9090/api/v1/otlp/v1/metrics)
# logs -> Loki (otlp_http/loki, https://loki:3100/otlp/v1/logs)
#
# Lab 7 (contracts/trust-matrix.md): the receiver speaks TLS only and REQUIRES a client certificate
# of the internal CA (client_ca_file): a process on the `telemetry` network without such a
# certificate cannot ingest anything. Every exporter verifies the backend (internal CA + hostname)
# and authenticates with the Collector's own certificate (SAN otel-collector); Prometheus also
# checks that SAN against its allowlist.
# The Collector stores nothing for long: it receives, limits, batches and forwards. When a backend
# is down, each exporter keeps a BOUNDED queue (sending_queue) and retries for at most
# max_elapsed_time; then the data is dropped and counted (otelcol_exporter_send_failed_*,
# otelcol_exporter_enqueue_failed_*). memory_limiter refuses new data above its limit.
# Its own metrics: PUSHED over OTLP/HTTPS to Prometheus (lab 7; the lab 6 pull endpoint :8888 had no
# TLS). health_check listens on the container's loopback only.
# Every span is kept (the lab 6 track 1 tail-sampling overlay is not part of lab 7).
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 per export request
tls:
cert_file: /run/secrets/otel-collector.crt
key_file: /run/secrets/otel-collector.key
client_ca_file: /run/secrets/internal-ca.crt # = RequireAndVerifyClientCert
min_version: "1.2"
processors:
# First in every pipeline. Container limit 512 MiB: soft limit = 400 - 80 = 320 MiB (start
# refusing + GC), hard limit 400 MiB (forced GC). The contrib binary alone is ~150 MiB RSS.
memory_limiter:
check_interval: 1s
limit_mib: 400
spike_limit_mib: 80
# Fewer, larger requests to the backends; at most 2 s of delay.
batch:
send_batch_size: 1024
send_batch_max_size: 2048
timeout: 2s
exporters:
otlp_http/tempo:
endpoint: https://tempo:4318
timeout: 5s
tls: &mtls
ca_file: /run/secrets/internal-ca.crt
cert_file: /run/secrets/otel-collector.crt
key_file: /run/secrets/otel-collector.key
min_version: "1.2"
sending_queue: &queue
enabled: true
num_consumers: 2
queue_size: 100 # batches (<= 2048 items each): bounded, in memory only
retry_on_failure: &retry
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 60s # then the batch is dropped (counted), never retried forever
otlp_http/prometheus:
endpoint: https://prometheus:9090/api/v1/otlp
timeout: 5s
tls: *mtls
sending_queue: *queue
retry_on_failure: *retry
otlp_http/loki:
endpoint: https://loki:3100/otlp
timeout: 5s
tls: *mtls
sending_queue: *queue
retry_on_failure: *retry
service:
extensions: [health_check]
telemetry:
resource:
service.name: otel-collector
logs:
level: warn
metrics:
level: normal
readers:
- periodic:
interval: 15000
exporter:
otlp:
protocol: http/protobuf
endpoint: https://prometheus:9090/api/v1/otlp/v1/metrics
certificate: /run/secrets/internal-ca.crt
client_certificate: /run/secrets/otel-collector.crt
client_key: /run/secrets/otel-collector.key
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/loki]
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# Runs ONCE, when the volume pgdata is initialised (docker-entrypoint-initdb.d), as OS user postgres
# over the local socket. Creates one login role per service; the passwords come from Docker secret
# files and are passed to psql as variables (never on a command line, never printed).
# messenger_migrate owns the database objects (applies migrations, service `migrate`)
# messenger_api / messenger_relay / messenger_worker GRANTs in migrations/0007_least_privilege.sql
# messenger_jobctl / messenger_auditor operator tools (profile tools)
# Nobody but `postgres` (no network login, see pg_hba.conf) is a superuser.
set -eu
for role in migrate api relay worker jobctl auditor; do
pw="$(tr -d '\r\n' < "/run/secrets/pg_${role}_password")"
psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres -v role="messenger_${role}" -v pw="$pw" <<'SQL'
CREATE ROLE :"role" LOGIN PASSWORD :'pw' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;
SQL
done
psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres <<'SQL'
ALTER DATABASE messenger OWNER TO messenger_migrate;
-- Only the service roles may connect to the application database.
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
GRANT CONNECT ON DATABASE messenger TO messenger_migrate, messenger_api, messenger_relay, messenger_worker,
messenger_jobctl, messenger_auditor;
SQL
psql -v ON_ERROR_STOP=1 --username postgres --dbname messenger <<'SQL'
-- PostgreSQL 15+: schema public belongs to pg_database_owner (= messenger_migrate now), and
-- PUBLIC has no CREATE on it. Make it explicit: only the owner creates objects.
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_relay, messenger_worker, messenger_jobctl, messenger_auditor;
SQL
echo "initdb: service roles created"
+18
View File
@@ -0,0 +1,18 @@
# PostgreSQL client authentication, lab 7 (passed with -c hba_file=..., compose service postgres).
# First matching line wins.
#
# Unix socket inside the container only (docker compose exec): the superuser `postgres` by peer
# (OS user postgres), everyone else by password. initdb scripts and the operator use this path.
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer
local all all scram-sha-256
# Network: TLS ONLY and only the service roles, password = SCRAM. The superuser never logs in
# over the network. Clients verify the server with sslmode=verify-full (internal CA, SAN postgres).
hostssl messenger messenger_migrate all scram-sha-256
hostssl messenger messenger_api all scram-sha-256
hostssl messenger messenger_relay all scram-sha-256
hostssl messenger messenger_worker all scram-sha-256
hostssl messenger messenger_jobctl all scram-sha-256
hostssl messenger messenger_auditor all scram-sha-256
# Everything else - any plaintext connection, any other role/database - is refused.
host all all all reject
+46
View File
@@ -0,0 +1,46 @@
# Prometheus 3.16 (prom/prometheus:v3.16.0), labs 6-7: the METRICS store.
#
# Application metrics AND the Collector's own metrics are PUSHED by the Collector over OTLP/HTTPS
# (flag --web.enable-otlp-receiver, endpoint /api/v1/otlp/v1/metrics). Prometheus derives
# `job` = service.name and `instance` = service.instance.id from the OTLP resource, and translates
# the OTel names with suffixes: http.server.request.duration (unit s) ->
# http_server_request_duration_seconds_bucket (mapping: docs/OBSERVABILITY.md).
#
# Lab 7: the web listener is HTTPS with a REQUIRED client certificate of the internal CA and a SAN
# allowlist (web-config.yml): only otel-collector (push), grafana (queries) and prometheus itself
# (self-scrape, promtool healthcheck) get in. Scrapes of Loki/Tempo use HTTPS + this server's
# own client certificate (they require one too).
global:
scrape_interval: 15s
evaluation_interval: 15s # alert rules: detection delay = condition + `for` + <= 15 s
otlp:
# deployment.environment.name=lab as a label on every series (low cardinality, one value).
promote_resource_attributes: [deployment.environment.name, service.version]
keep_identifying_resource_attributes: true
storage:
tsdb:
# OTLP pushes from several processes arrive slightly out of order; accept 10 min of it.
out_of_order_time_window: 10m
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: prometheus
scheme: https
tls_config: &mtls
ca_file: /run/secrets/internal-ca.crt
cert_file: /run/secrets/prometheus.crt
key_file: /run/secrets/prometheus.key
min_version: TLS12
static_configs: [{targets: ["localhost:9090"]}]
- job_name: loki
scheme: https
tls_config: *mtls
static_configs: [{targets: ["loki:3100"]}]
- job_name: tempo
scheme: https
tls_config: *mtls
static_configs: [{targets: ["tempo:3200"]}]
+7
View File
@@ -0,0 +1,7 @@
# HTTP client config of the container healthcheck (`promtool check healthy`): the same mTLS as any
# other client - Prometheus' own client certificate (SAN prometheus, in the allowlist).
tls_config:
ca_file: /run/secrets/internal-ca.crt
cert_file: /run/secrets/prometheus.crt
key_file: /run/secrets/prometheus.key
server_name: localhost
+90
View File
@@ -0,0 +1,90 @@
# Alert rules (evaluated by Prometheus every 15 s; state pending -> firing -> resolved is visible
# in Prometheus /api/v1/alerts, the ALERTS series and the Grafana dashboard "Alerts" panel).
# No delivery outside (no Alertmanager): the task asks for the local firing/resolved state only.
# Runbook of every alert: docs/RUNBOOK.md#<alert name>.
groups:
- name: messenger-alerts
rules:
- alert: MessengerApiHighErrorRate
# 5xx share of business requests over 1 min, summed over all API replicas. The traffic
# guard (> 0.2 req/s) keeps a single failed request on an idle stand from paging.
expr: messenger:http_error_ratio:rate1m > 0.05 and messenger:http_requests:rate1m > 0.2
for: 1m
labels:
severity: page
slo: api-availability
annotations:
summary: "API: {{ $value | humanizePercentage }} of business requests answer 5xx"
description: >-
More than 5 % of non-health API requests failed with 5xx for over a minute (SLO: 99 %
non-5xx over 1 h). Typical causes: PostgreSQL/Valkey/S3 unavailable or too slow (503),
pool exhausted, crash (500).
runbook: docs/RUNBOOK.md#messengerapihigherrorrate
- alert: MessengerQueueLagGrowing
# Oldest unfinished job older than 60 s while jobs are waiting: nobody processes the queue
# (worker stopped/stuck, broker unreachable) or processing is far slower than arrivals.
# Measured in PostgreSQL by the relay: retries and unpublished jobs count too.
expr: max(messenger_queue_oldest_age_seconds) > 60 and max(messenger_queue_depth{state="queued"}) > 0
for: 1m
labels:
severity: page
slo: time-to-ready
annotations:
summary: "Queue: the oldest job waits {{ $value | humanizeDuration }}"
description: >-
Accepted uploads are not becoming ready. Check messenger_worker_busy / capacity, the
worker container, messenger_outbox_oldest_age_seconds (broker) and job outcomes.
runbook: docs/RUNBOOK.md#messengerqueuelaggrowing
- alert: MessengerApiLatencyHigh
# p99 of business requests over 2 min, from the buckets of all replicas.
expr: messenger:http_latency:p99_2m > 1
for: 2m
labels:
severity: ticket
slo: api-latency
annotations:
summary: "API p99 = {{ $value | humanizeDuration }} (> 1 s)"
description: >-
Slow API. Compare db.client.operation.duration and the DB pool (pending requests) with
the HTTP duration: slow database vs slow handler code (docs/RUNBOOK.md).
runbook: docs/RUNBOOK.md#messengerapilatencyhigh
- alert: MessengerDbPoolSaturated
# Requests waiting for a database connection in any process, for 1 min.
expr: max by (job) (db_client_connection_pending_requests) > 0
for: 1m
labels:
severity: ticket
annotations:
summary: "{{ $labels.job }}: requests wait for a PostgreSQL connection"
description: The pool is exhausted - queries hold connections too long (slow DB, locks) or the pool is too small.
runbook: docs/RUNBOOK.md#messengerdbpoolsaturated
- alert: MessengerQueueMetricsAbsent
# The relay reports the backlog from PostgreSQL every 5 s; no value for 2 min means the
# relay is down or cannot read the database - the queue is then NOT observed at all.
expr: absent(messenger_queue_oldest_age_seconds)
for: 2m
labels:
severity: ticket
annotations:
summary: "No queue metrics (relay down or database unreachable)"
runbook: docs/RUNBOOK.md#messengerqueuemetricsabsent
- alert: TelemetryExportFailing
# The Collector cannot deliver to a backend (Tempo/Loki/Prometheus down): data is buffered
# in its bounded queue and then dropped. The application itself is not affected.
expr: |
sum by (exporter) (
rate(otelcol_exporter_send_failed_spans_total[2m])
or rate(otelcol_exporter_send_failed_log_records_total[2m])
or rate(otelcol_exporter_send_failed_metric_points_total[2m])
) > 0
for: 30s
labels:
severity: ticket
annotations:
summary: "Collector exporter {{ $labels.exporter }} fails to send"
runbook: docs/RUNBOOK.md#telemetryexportfailing
+38
View File
@@ -0,0 +1,38 @@
# Recording rules: SLIs of docs/SLO.md (lab windows). All ratios are computed from COUNTERS and
# histogram BUCKETS summed over every replica first, then divided - never an average of
# per-replica ratios or percentiles.
#
# Business requests = every API request except /health/* (load-balancer/Docker probes).
# "Bad" for availability = HTTP 5xx only: 4xx (wrong password, 404 of an outsider, 409) is a
# correct answer to a wrong request, not a failure of the service.
groups:
- name: messenger-sli
interval: 15s
rules:
- record: messenger:http_requests:rate1m
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[1m]))
- record: messenger:http_errors5xx:rate1m
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*", http_response_status_class="5xx"}[1m])) or vector(0)
- record: messenger:http_error_ratio:rate1m
expr: messenger:http_errors5xx:rate1m / messenger:http_requests:rate1m
- record: messenger:http_error_ratio:rate5m
expr: |
(sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*", http_response_status_class="5xx"}[5m])) or vector(0))
/ sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[5m]))
- record: messenger:http_error_ratio:rate1h
expr: |
(sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*", http_response_status_class="5xx"}[1h])) or vector(0))
/ sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[1h]))
# Latency SLI: share of business requests answered within 250 ms (bucket le="0.25").
- record: messenger:http_fast_ratio:rate5m
expr: |
sum(rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*", le="0.25"}[5m]))
/ sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[5m]))
# p50/p95/p99 over ALL replicas: buckets summed by le, then histogram_quantile.
- record: messenger:http_latency:p99_2m
expr: histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*"}[2m])))
# Time-to-ready SLI: share of uploads ready within 30 s (bucket le="30").
- record: messenger:ready_within_30s_ratio:rate1h
expr: |
sum(rate(messenger_attachment_time_to_ready_seconds_bucket{le="30"}[1h]))
/ sum(rate(messenger_attachment_time_to_ready_seconds_count[1h]))
+10
View File
@@ -0,0 +1,10 @@
# Prometheus web listener (--web.config.file), lab 7: HTTPS + mandatory client certificate of the
# internal CA + allowlist of client identities (SAN). A certificate of the same CA with another
# name (api, worker, loki, ...) is refused in the TLS handshake.
tls_server_config:
cert_file: /run/secrets/prometheus.crt
key_file: /run/secrets/prometheus.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/secrets/internal-ca.crt
client_allowed_sans: [otel-collector, grafana, prometheus]
min_version: TLS12
+1
View File
@@ -0,0 +1 @@
[].
+35
View File
@@ -0,0 +1,35 @@
# RabbitMQ 4.3 of the stand (compose service `broker`), mounted as conf.d/20-lab.conf.
# Lab 7: AMQP 0-9-1 over TLS ONLY (amqps, 5671) inside the internal network `queue`. The plaintext
# listener is off, there is no management UI and no Prometheus listener (enabled_plugins is
# empty), nothing is published on the host. Clients verify the server certificate (internal CA,
# SAN broker); their identity is the user relay / worker with its own permissions (grade 3: no
# client certificates; mTLS to the broker is grade 4).
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.cacertfile = /run/secrets/internal-ca.crt
ssl_options.certfile = /run/secrets/broker.crt
ssl_options.keyfile = /run/secrets/broker.key
ssl_options.verify = verify_none
ssl_options.fail_if_no_peer_cert = false
ssl_options.versions.1 = tlsv1.3
ssl_options.versions.2 = tlsv1.2
# Users, permissions and topology are imported from files at every boot (idempotent):
# /etc/rabbitmq/definitions.d/topology.json exchanges, quorum queues, bindings (this repo)
# /etc/rabbitmq/definitions.d/users.json users relay/worker + permissions (Docker secret,
# generated by scripts/init_secrets.py)
# With imported definitions no default `guest` user is created.
definitions.import_backend = local_filesystem
definitions.local.path = /etc/rabbitmq/definitions.d
definitions.skip_if_unchanged = false
# A delivery that stays unacked longer than this closes the consumer's channel and the message
# is returned to the queue (a worker that hangs while connected). Far above JOB_TIMEOUT_SECONDS.
consumer_timeout = 300000
# The container has a 512 MiB limit; flow control starts well before the cgroup OOM.
vm_memory_high_watermark.relative = 0.5
disk_free_limit.absolute = 200MB
log.console = true
log.console.level = info
+21
View File
@@ -0,0 +1,21 @@
{
"vhosts": [{"name": "/"}],
"exchanges": [
{"name": "messenger.jobs", "vhost": "/", "type": "direct", "durable": true, "auto_delete": false,
"internal": false, "arguments": {}},
{"name": "messenger.jobs.dlx", "vhost": "/", "type": "fanout", "durable": true, "auto_delete": false,
"internal": false, "arguments": {}}
],
"queues": [
{"name": "messenger.attachment-jobs", "vhost": "/", "durable": true, "auto_delete": false,
"arguments": {"x-queue-type": "quorum", "x-delivery-limit": 20, "x-dead-letter-exchange": "messenger.jobs.dlx"}},
{"name": "messenger.attachment-jobs.dlq", "vhost": "/", "durable": true, "auto_delete": false,
"arguments": {"x-queue-type": "quorum"}}
],
"bindings": [
{"source": "messenger.jobs", "vhost": "/", "destination": "messenger.attachment-jobs", "destination_type": "queue",
"routing_key": "attachment.process.v1", "arguments": {}},
{"source": "messenger.jobs.dlx", "vhost": "/", "destination": "messenger.attachment-jobs.dlq",
"destination_type": "queue", "routing_key": "", "arguments": {}}
]
}
+56
View File
@@ -0,0 +1,56 @@
#!/bin/sh
# Entry point of the compose service `s3` (SeaweedFS 4.46, one container: master + volume +
# filer + S3 gateway). Renders the S3 identities from Docker secrets, then execs `weed`.
#
# Two private buckets (lab 5): S3_STAGING_BUCKET holds originals accepted by the API before 202,
# S3_BUCKET holds the published originals and variants written by the worker.
# Identities (SeaweedFS s3.json, actions scoped to a bucket):
# bootstrap-admin Admin (create buckets) -> only s3-init has these keys
# messenger-api Write staging, Read final -> API replicas (no List, no Admin)
# messenger-worker Read + Write staging, Read + Write final -> worker (no List, no Admin)
# messenger-auditor Read + List both buckets (no Write) -> invariant checker (tools profile)
# There is NO anonymous identity, so every unsigned request is refused: the buckets are private.
#
# Exposure: master (9333), volume (8080), filer (8888) with their web UIs and gRPC listen on
# 127.0.0.1 INSIDE the container only (-ip.bind); only the S3 API port 8333 listens on the
# container network `storage` (internal, not published on the host). Telemetry is off.
# Lab 7: the S3 port speaks HTTPS only (-s3.cert.file/-s3.key.file: internal CA, SAN s3); the
# clients verify chain + hostname (aiobotocore verify=TLS_CA_FILE). The plaintext master/volume/filer
# hops stay on the container's own loopback (closed local hop, not reachable from the network).
set -eu
umask 077
secret() { tr -d '\r\n' < "/run/secrets/$1"; }
bucket="${S3_BUCKET:?S3_BUCKET is required}"
staging="${S3_STAGING_BUCKET:?S3_STAGING_BUCKET is required}"
cat > /tmp/s3.json <<EOF
{
"identities": [
{"name": "bootstrap-admin",
"credentials": [{"accessKey": "$(secret s3_admin_access_key_id)", "secretKey": "$(secret s3_admin_secret_access_key)"}],
"actions": ["Admin", "Read", "Write", "List", "Tagging"]},
{"name": "messenger-api",
"credentials": [{"accessKey": "$(secret s3_api_access_key_id)", "secretKey": "$(secret s3_api_secret_access_key)"}],
"actions": ["Write:${staging}", "Read:${bucket}"]},
{"name": "messenger-worker",
"credentials": [{"accessKey": "$(secret s3_worker_access_key_id)", "secretKey": "$(secret s3_worker_secret_access_key)"}],
"actions": ["Read:${staging}", "Write:${staging}", "Read:${bucket}", "Write:${bucket}"]},
{"name": "messenger-auditor",
"credentials": [{"accessKey": "$(secret s3_auditor_access_key_id)", "secretKey": "$(secret s3_auditor_secret_access_key)"}],
"actions": ["Read:${staging}", "List:${staging}", "Read:${bucket}", "List:${bucket}"]}
]
}
EOF
# Memory: by default SeaweedFS buffers every in-flight upload without a limit and the Go runtime
# keeps freed heap; measured ~1 GB under 16 parallel 9.4 MiB PUTs (lab 4). The upload limits make
# excess PUTs wait inside SeaweedFS instead of growing the heap, and GOMEMLIMIT (set in
# compose.yaml below the container limit) makes the Go GC return memory before the cgroup OOM.
exec weed server \
-dir=/data \
-ip=127.0.0.1 -ip.bind=127.0.0.1 \
-master.telemetry=false \
-master.volumeSizeLimitMB=1024 -volume.max=0 \
-filer -filer.disableDirListing -filer.concurrentUploadLimitMB=128 \
-volume.concurrentUploadLimitMB=128 \
-s3 -s3.ip.bind=0.0.0.0 -s3.port=8333 -s3.config=/tmp/s3.json -s3.concurrentUploadLimitMB=128 \
-s3.cert.file=/run/secrets/s3.crt -s3.key.file=/run/secrets/s3.key \
-s3.iam=false -s3.autoCreateBucket=false -s3.port.iceberg=0 -s3.port.lance=0
+47
View File
@@ -0,0 +1,47 @@
# Tempo 2.10 (grafana/tempo:2.10.10), single binary, lab 6: the TRACES store.
# Spans arrive from the Collector over OTLP/HTTP (:4318). Blocks + WAL on the named volume
# tempodata; traces are kept 72 h. Search by attributes (TraceQL), e.g.
# { resource.service.name = "messenger-worker" && span.messenger.job.outcome = "retry" }
stream_over_http_enabled: true
server:
http_listen_port: 3200
grpc_listen_address: 127.0.0.1
log_level: warn
# Lab 7: HTTPS + mandatory client certificate of the internal CA (otel-collector pushes,
# grafana queries, prometheus scrapes). gRPC is internal to the single binary: loopback only.
http_tls_config:
cert_file: /run/secrets/tempo.crt
key_file: /run/secrets/tempo.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/secrets/internal-ca.crt
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
tls: # only the Collector (client certificate of the internal CA)
cert_file: /run/secrets/tempo.crt
key_file: /run/secrets/tempo.key
client_ca_file: /run/secrets/internal-ca.crt
min_version: "1.2"
ingester:
max_block_duration: 5m # small blocks: a restart loses at most the WAL replay time
compactor:
compaction:
block_retention: 72h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
usage_report:
reporting_enabled: false
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# Entry point of the compose service `valkey` (lab 7). Writes the ACL file from the Docker secret and
# starts Valkey through the image's entrypoint (which drops root to the valkey user).
# user default off no anonymous/shared-password access at all
# user api SHA-256 of its password only (the plain password never lands in a file here),
# keys session:* (sessions.py) and ratelimit:* (login limit), commands it uses:
# GET/SET/DEL (sessions), INCR(BY)/PEXPIRE/PTTL in MULTI/EXEC (rate limit), PING
# (readiness), CLIENT SETINFO (sent by redis-py on connect). FLUSHALL, CONFIG,
# KEYS, DEBUG, ACL, ... are refused with NOPERM.
set -eu
umask 077
mkdir -p /tmp/valkey
hash="$(tr -d '\r\n' < /run/secrets/valkey_api_password | sha256sum | cut -d' ' -f1)"
printf 'user default off\n' > /tmp/valkey/users.acl
printf 'user api on #%s resetkeys ~session:* ~ratelimit:* resetchannels -@all +get +set +del +incr +incrby +pexpire +pttl +multi +exec +discard +ping +client|setinfo\n' \
"$hash" >> /tmp/valkey/users.acl
chown -R valkey /tmp/valkey
exec docker-entrypoint.sh valkey-server /etc/valkey/valkey.conf
+27
View File
@@ -0,0 +1,27 @@
# Valkey is the single store of sessions (SESSION_STORE=valkey), so it must be durable.
# AOF with fsync on every write: a confirmed login or logout survives a crash/restart,
# a logout can never be lost and "resurrect" a token. Sessions are small and rare
# writes, so the fsync cost is acceptable here (see REPORT.md).
appendonly yes
appendfsync always
appenddirname "appendonlydir"
# RDB snapshots are not needed on top of AOF.
save ""
dir /data
protected-mode yes
# Lab 7: TLS only. The plaintext port is closed (port 0); clients verify the server certificate
# (internal CA, SAN valkey). No client certificates at grade 3 (tls-auth-clients no): the client
# identity is the ACL user + password below.
port 0
tls-port 6379
tls-cert-file /run/secrets/valkey.crt
tls-key-file /run/secrets/valkey.key
tls-ca-cert-file /run/secrets/internal-ca.crt
tls-auth-clients no
tls-protocols "TLSv1.2 TLSv1.3"
# Sessions are never evicted silently: if memory is full, writes fail and login returns 503.
maxmemory 128mb
maxmemory-policy noeviction
# Lab 7: ACL users instead of one shared password (file written by infra/valkey/start.sh at start):
# `default` is off, `api` may touch only session:* / ratelimit:* keys with the commands it uses.
aclfile /tmp/valkey/users.acl
+65
View File
@@ -0,0 +1,65 @@
-- 0001: initial schema of the messenger (lab 2). Design rationale: docs/DATA_MODEL.md
-- Applied once by `python -m messenger.migrate`; the version is recorded in schema_migrations.
-- User-supplied free text (display_name, title, message text) is stored as UTF-8 in BYTEA:
-- the contract allows U+0000, and PostgreSQL TEXT cannot contain NUL bytes.
-- Lengths are limited in code points by the API; the CHECKs below are byte-level safety nets
-- (one code point is at most 4 bytes in UTF-8).
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name bytea NOT NULL,
password_hash text NOT NULL, -- Argon2id PHC string, never the password
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_len CHECK (octet_length(display_name) BETWEEN 1 AND 400)
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title bytea NOT NULL,
created_by uuid NOT NULL REFERENCES users (id),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
-- Per-chat clock: created_at of the newest message. Updating this row serialises writers
-- of one chat, so message timestamps strictly increase in commit order (see DATA_MODEL.md).
last_message_at timestamptz,
CONSTRAINT chats_title_len CHECK (octet_length(title) BETWEEN 1 AND 400)
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id),
user_id uuid NOT NULL REFERENCES users (id),
position smallint NOT NULL, -- order of member_ids sent by the creator
chat_created_at timestamptz NOT NULL, -- copy of chats.created_at for keyset listing
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_key UNIQUE (chat_id, position)
);
-- GET /chats of one user: (user_id, created_at, id) range scan, no sort.
CREATE INDEX chat_members_user_keyset ON chat_members (user_id, chat_created_at, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text bytea NOT NULL,
created_at timestamptz NOT NULL,
-- The sender must be a member of this chat: enforced by the database, not only by the API.
CONSTRAINT messages_sender_is_member FOREIGN KEY (chat_id, sender_id)
REFERENCES chat_members (chat_id, user_id),
CONSTRAINT messages_text_len CHECK (octet_length(text) BETWEEN 1 AND 16000)
);
-- History page: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT n
-- becomes an index range scan that starts exactly at the cursor.
CREATE INDEX messages_chat_keyset ON messages (chat_id, created_at, id);
-- Sessions for SESSION_STORE=postgres (the default store is Valkey; see docs/DATA_MODEL.md).
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY, -- SHA-256 of the token; the token is not stored
user_id uuid NOT NULL REFERENCES users (id),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
expires_at timestamptz NOT NULL,
CONSTRAINT sessions_token_hash_len CHECK (octet_length(token_hash) = 32)
);
CREATE INDEX sessions_expires_at ON sessions (expires_at);
+25
View File
@@ -0,0 +1,25 @@
-- 0002 (lab 3): shared idempotency of POST /chats/{chat_id}/messages.
-- Additive only (new table), so the lab 2 API keeps working while this runs: it is safe
-- to apply before a rolling update of the API replicas (see REPORT.md, "Миграции").
--
-- Scope of a key (contracts/README.md): current user + HTTP method + chat path + key.
-- The method (POST) and the path template are fixed for this table, so the scope
-- is (user_id, chat_id, key). The key row, the message and the result are written in
-- ONE transaction (repo.post_message): there is no "pending" state that a crash could
-- leave behind, and the stored result is the message row itself.
CREATE TABLE idempotency_keys (
user_id uuid NOT NULL REFERENCES users (id),
chat_id uuid NOT NULL REFERENCES chats (id),
key text NOT NULL,
request_hash bytea NOT NULL, -- SHA-256 of the canonical JSON body
-- Inserted before the message in the same transaction, hence checked at COMMIT.
message_id uuid NOT NULL REFERENCES messages (id) DEFERRABLE INITIALLY DEFERRED,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (user_id, chat_id, key),
CONSTRAINT idempotency_keys_key_format CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
CONSTRAINT idempotency_keys_hash_len CHECK (octet_length(request_hash) = 32),
CONSTRAINT idempotency_keys_message_key UNIQUE (message_id)
);
-- Housekeeping of keys older than IDEMPOTENCY_TTL_SECONDS (>= 24 h).
CREATE INDEX idempotency_keys_created_at ON idempotency_keys (created_at);
+50
View File
@@ -0,0 +1,50 @@
-- 0003 (lab 3, track 1 improvement): the whole idempotent "send message" as ONE statement.
-- Additive (a new function), so replicas of the previous version keep working while it is
-- applied, and the previous write path (MESSAGE_WRITE_PATH=multi) stays usable for A/B runs.
--
-- Same semantics and the same SQL as repo.post_message (multi-statement path), but executed
-- inside the server: the API sends one call instead of ~11 round trips in two transactions
-- (membership check, BEGIN, key claim, chat clock, message, COMMIT, pool checks). Called in
-- autocommit mode, so the function call IS the transaction: key row, chat clock and message
-- commit together or not at all. VOLATILE + READ COMMITTED: every statement inside takes a
-- fresh snapshot, so after waiting on a concurrent claim of the same key the stored result
-- of the winner is visible, exactly as in the multi-statement path.
--
-- o_status: created | replayed | conflict | not_found | retry (key vanished in between: cleanup)
CREATE FUNCTION post_message(p_user uuid, p_chat uuid, p_key text, p_hash bytea, p_message uuid,
p_text bytea, p_ttl_seconds integer)
RETURNS TABLE (o_status text, o_id uuid, o_text bytea, o_created_at timestamptz)
LANGUAGE plpgsql VOLATILE AS $$
DECLARE
v_created timestamptz;
BEGIN
PERFORM 1 FROM chat_members m WHERE m.chat_id = p_chat AND m.user_id = p_user;
IF NOT FOUND THEN
RETURN QUERY SELECT 'not_found'::text, NULL::uuid, NULL::bytea, NULL::timestamptz;
RETURN;
END IF;
INSERT INTO idempotency_keys AS k (user_id, chat_id, key, request_hash, message_id)
VALUES (p_user, p_chat, p_key, p_hash, p_message)
ON CONFLICT (user_id, chat_id, key) DO UPDATE
SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp()
WHERE k.created_at < clock_timestamp() - make_interval(secs => p_ttl_seconds);
IF FOUND THEN
-- Per-chat clock under the chat row lock (see migrations/0001 and docs/DATA_MODEL.md).
UPDATE chats c SET last_message_at = greatest(clock_timestamp(), c.last_message_at + interval '1 microsecond')
WHERE c.id = p_chat RETURNING c.last_message_at INTO v_created;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES (p_message, p_chat, p_user, p_text, v_created);
RETURN QUERY SELECT 'created'::text, p_message, p_text, v_created;
RETURN;
END IF;
RETURN QUERY
SELECT CASE WHEN k.request_hash = p_hash THEN 'replayed' ELSE 'conflict' END, m.id, m.text, m.created_at
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.key = p_key;
IF NOT FOUND THEN
RETURN QUERY SELECT 'retry'::text, NULL::uuid, NULL::bytea, NULL::timestamptz;
END IF;
END
$$;
+145
View File
@@ -0,0 +1,145 @@
-- 0004 (lab 4): attachments. Metadata live here, the bytes in the private S3 bucket.
-- Additive (new tables, a relaxed CHECK, a NEW function post_message_v2), so replicas of the
-- lab 3 version keep working while it is applied (they never send attachment_ids).
--
-- Consistency between the two stores (docs/CONSISTENCY.md):
-- 1. INSERT the row as status='pending' (intent: the server-generated object_key is known
-- BEFORE anything is written to S3) and COMMIT;
-- 2. PUT the object into S3;
-- 3. UPDATE status='ready' WHERE status='pending'; only then 201.
-- Invariant: an object never exists without a row that names its key (row first, object
-- second; on cleanup object first, row second). A crash/outage between the steps leaves a
-- 'pending' row; the janitor deletes its object (idempotent) and then the row once it is older
-- than PENDING_GRACE_SECONDS. The reconciler (python -m messenger.reconcile) checks the
-- invariant over the whole bucket.
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
owner_id uuid NOT NULL,
filename text NOT NULL, -- display name only, never a path or a key
content_type text NOT NULL, -- detected from the bytes, not from the header
size_bytes integer NOT NULL,
sha256 bytea NOT NULL,
width integer NOT NULL,
height integer NOT NULL,
-- Random server-generated key ("o/" + 128 random bits in hex), unrelated to id/filename.
-- COLLATE "C": byte order = S3 ListObjectsV2 order, the reconciler merge-joins both lists.
object_key text COLLATE "C" NOT NULL,
status text NOT NULL DEFAULT 'pending',
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
-- Set by the reconciler when the object of a READY row is missing or has the wrong size:
-- the row is quarantined (content -> 404, cannot be attached), never deleted, and the mark
-- is removed again if the object comes back (restore from backup).
lost_at timestamptz,
lost_reason text,
-- The uploader must be a member of the chat (enforced by the database too).
CONSTRAINT attachments_owner_is_member FOREIGN KEY (chat_id, owner_id)
REFERENCES chat_members (chat_id, user_id),
CONSTRAINT attachments_object_key_key UNIQUE (object_key),
CONSTRAINT attachments_object_key_format CHECK (object_key ~ '^o/[0-9a-f]{32}$'),
CONSTRAINT attachments_status CHECK (status IN ('pending', 'ready')),
CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256_len CHECK (octet_length(sha256) = 32),
CONSTRAINT attachments_pixels CHECK (width >= 1 AND height >= 1 AND width::bigint * height <= 40000000),
CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_lost CHECK ((lost_at IS NULL) = (lost_reason IS NULL) AND (lost_at IS NULL OR status = 'ready'))
);
-- Janitor: stale intents, oldest first; tiny partial index (only rows of unfinished uploads).
CREATE INDEX attachments_pending_created ON attachments (created_at) WHERE status = 'pending';
-- attachment_ids of a message, twice on purpose (both written in the message's transaction):
-- * messages.attachment_ids (ordered array): the history page reads it from the same row, so the
-- keyset range scan of messages stays ONE index scan, without a per-row sub-query;
-- * message_attachments: foreign keys (a referenced attachment can never be deleted) and the
-- reverse lookup "is this attachment used?" (janitor/reconciler) by an index on attachment_id.
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}';
ALTER TABLE messages ADD CONSTRAINT messages_attachment_ids_len CHECK (cardinality(attachment_ids) <= 10);
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages (id),
position smallint NOT NULL,
attachment_id uuid NOT NULL REFERENCES attachments (id),
PRIMARY KEY (message_id, position),
CONSTRAINT message_attachments_unique UNIQUE (message_id, attachment_id),
CONSTRAINT message_attachments_position CHECK (position BETWEEN 0 AND 9)
);
-- "Is this attachment used by any message?" (janitor/reconciler never touch used ones).
CREATE INDEX message_attachments_attachment ON message_attachments (attachment_id);
-- Lab 4: text may be "" when the message has attachments (the API enforces "text or files").
-- DROP CONSTRAINT takes a short exclusive lock on messages and the new CHECK scans the table
-- once, inside this migration's transaction (seconds for a lab-sized table; for a big table
-- this would be ADD ... NOT VALID + VALIDATE in a separate migration).
ALTER TABLE messages DROP CONSTRAINT messages_text_len;
ALTER TABLE messages ADD CONSTRAINT messages_text_len CHECK (octet_length(text) <= 16000);
-- post_message_v2: post_message (0003) + attachment_ids, still ONE statement and ONE transaction.
-- The attachments are checked BEFORE the key is claimed and the key is claimed only if they are
-- fine, so a failed check never leaves a key behind. A replay (same key, same body) returns the
-- stored message even if an attachment was quarantined since: the result of a key is final.
--
-- o_status: created | replayed | conflict | not_found | retry | attachment_not_found | attachment_conflict
CREATE FUNCTION post_message_v2(p_user uuid, p_chat uuid, p_key text, p_hash bytea, p_message uuid,
p_text bytea, p_ttl_seconds integer, p_attachments uuid[])
RETURNS TABLE (o_status text, o_id uuid, o_text bytea, o_created_at timestamptz, o_attachments uuid[])
LANGUAGE plpgsql VOLATILE AS $$
DECLARE
v_created timestamptz;
v_found integer;
v_usable integer;
v_check text := 'ok';
BEGIN
PERFORM 1 FROM chat_members m WHERE m.chat_id = p_chat AND m.user_id = p_user;
IF NOT FOUND THEN
RETURN QUERY SELECT 'not_found'::text, NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[];
RETURN;
END IF;
IF cardinality(p_attachments) > 0 THEN
-- Visible = ready attachment of THIS chat (pending, foreign or unknown -> 404).
-- Usable = visible and not quarantined (lost -> 409, like a failed attachment).
-- FOR SHARE: a concurrent quarantine waits until this message is committed.
SELECT count(*), count(*) FILTER (WHERE a.lost_at IS NULL) INTO v_found, v_usable
FROM (SELECT a.lost_at FROM attachments a
WHERE a.id = ANY (p_attachments) AND a.chat_id = p_chat AND a.status = 'ready'
FOR SHARE) a;
IF v_found <> cardinality(p_attachments) THEN
v_check := 'attachment_not_found';
ELSIF v_usable <> v_found THEN
v_check := 'attachment_conflict';
END IF;
END IF;
IF v_check = 'ok' THEN
INSERT INTO idempotency_keys AS k (user_id, chat_id, key, request_hash, message_id)
VALUES (p_user, p_chat, p_key, p_hash, p_message)
ON CONFLICT (user_id, chat_id, key) DO UPDATE
SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp()
WHERE k.created_at < clock_timestamp() - make_interval(secs => p_ttl_seconds);
IF FOUND THEN
UPDATE chats c SET last_message_at = greatest(clock_timestamp(), c.last_message_at + interval '1 microsecond')
WHERE c.id = p_chat RETURNING c.last_message_at INTO v_created;
INSERT INTO messages (id, chat_id, sender_id, text, created_at, attachment_ids)
VALUES (p_message, p_chat, p_user, p_text, v_created, p_attachments);
INSERT INTO message_attachments (message_id, position, attachment_id)
SELECT p_message, (a.ord - 1)::smallint, a.id
FROM unnest(p_attachments) WITH ORDINALITY AS a(id, ord);
RETURN QUERY SELECT 'created'::text, p_message, p_text, v_created, p_attachments;
RETURN;
END IF;
END IF;
RETURN QUERY
SELECT CASE WHEN k.request_hash = p_hash THEN 'replayed' ELSE 'conflict' END, m.id, m.text, m.created_at,
m.attachment_ids
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.key = p_key;
IF NOT FOUND THEN
RETURN QUERY SELECT CASE WHEN v_check = 'ok' THEN 'retry' ELSE v_check END,
NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[];
END IF;
END
$$;
+260
View File
@@ -0,0 +1,260 @@
-- 0005 (lab 5): asynchronous processing of attachments. Details: docs/PIPELINE.md.
--
-- Upload (API): INSERT attachment 'pending' (intent: the staging key is known before the PUT)
-- -> PUT original into the PRIVATE STAGING bucket
-- -> ONE transaction: attachment 'queued' + jobs row + outbox row -> 202.
-- Relay: outbox row -> publish to RabbitMQ with publisher confirm -> outbox.published_at.
-- Worker: claim job (lease + attempt token) -> variants into the final bucket under keys of
-- THIS attempt -> ONE transaction: variants + attachment 'ready' (fenced by the
-- lease token, never downgrading published_version) -> ack -> staging deleted.
--
-- PostgreSQL is the source of truth for the work: state, attempts, lease, backoff (available_at)
-- and the failed registry. The broker only delivers job ids (at least once).
-- ------------------------------------------------------------------ attachments
ALTER TABLE attachments DROP CONSTRAINT attachments_status;
ALTER TABLE attachments ADD CONSTRAINT attachments_status
CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed'));
-- object_key = key of the ORIGINAL in the final bucket. NULL until the worker publishes it.
-- Keys of lab 4 ('o/<hex>') stay valid; lab 5 writes 'a/<attachment>/<attempt token>/original'.
ALTER TABLE attachments ALTER COLUMN object_key DROP NOT NULL;
ALTER TABLE attachments DROP CONSTRAINT attachments_object_key_format;
ALTER TABLE attachments ADD CONSTRAINT attachments_object_key_format
CHECK (object_key ~ '^(o/[0-9a-f]{32}|a/[0-9a-f-]{36}/[0-9a-f]{32}/original)$');
ALTER TABLE attachments
-- Key of the original in the staging bucket ('s/<128 random bits>'), written by the API.
ADD COLUMN staging_key text COLLATE "C",
-- none (lab 4 row) | present | deleting (marked, S3 DELETE pending) | deleted
ADD COLUMN staging_state text NOT NULL DEFAULT 'none',
-- pipeline version whose variants are published (GET shows them); only ever grows.
ADD COLUMN published_version integer,
ADD COLUMN error_code text,
ADD COLUMN failed_at timestamptz,
ADD CONSTRAINT attachments_staging_key_key UNIQUE (staging_key),
ADD CONSTRAINT attachments_staging_key_format CHECK (staging_key ~ '^s/[0-9a-f]{32}$'),
ADD CONSTRAINT attachments_staging_state CHECK (staging_state IN ('none', 'present', 'deleting', 'deleted')),
ADD CONSTRAINT attachments_staging_has_key CHECK (staging_state = 'none' OR staging_key IS NOT NULL),
ADD CONSTRAINT attachments_published_version CHECK (published_version >= 1),
ADD CONSTRAINT attachments_error_code CHECK (error_code ~ '^[a-z_]{1,64}$');
-- Lab 4 rows: a 'pending' intent of lab 4 never got its object confirmed and has no staging copy;
-- it becomes a failed upload (invisible: its id was never returned). A lab 4 'ready' row has its
-- original in the final bucket but no thumbnail yet: it is queued for pipeline 1 (below).
UPDATE attachments SET status = 'failed', error_code = 'upload_incomplete', failed_at = clock_timestamp()
WHERE status = 'pending';
UPDATE attachments SET status = 'queued' WHERE status = 'ready';
-- Structural guarantees (the database refuses a buggy cleanup or worker):
-- * work that is queued/processing always has a source: the published original or the staging
-- copy - the cleanup can never mark the staging of an accepted upload as deleting;
-- * ready = published original + published pipeline version; failed = error code.
ALTER TABLE attachments
ADD CONSTRAINT attachments_pending_staging CHECK (status <> 'pending' OR staging_state = 'present'),
ADD CONSTRAINT attachments_active_has_source
CHECK (status NOT IN ('queued', 'processing') OR object_key IS NOT NULL OR staging_state = 'present'),
ADD CONSTRAINT attachments_ready_published
CHECK (status <> 'ready' OR (object_key IS NOT NULL AND published_version IS NOT NULL)),
ADD CONSTRAINT attachments_failed_code
CHECK ((status = 'failed') = (error_code IS NOT NULL AND failed_at IS NOT NULL));
-- Janitor of the API: the lab 4 partial index on pending rows stays as is.
-- Cleanup of the worker: staging copies that may be deleted (ready: at once; failed: after retention).
CREATE INDEX attachments_staging_cleanup ON attachments (updated_at)
WHERE staging_state IN ('present', 'deleting') AND status IN ('ready', 'failed');
-- ------------------------------------------------------------------ jobs
-- One row = one logical piece of work: "build pipeline version V for attachment A".
-- job_id never changes on redelivery; `attempt` counts claims by workers (managed attempts).
CREATE TABLE jobs (
id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments (id),
pipeline_version integer NOT NULL,
kind text NOT NULL, -- upload | replay | reprocess | migrate
replay_of uuid REFERENCES jobs (id),
state text NOT NULL DEFAULT 'queued',
attempt integer NOT NULL DEFAULT 0,
max_attempts integer NOT NULL,
available_at timestamptz NOT NULL DEFAULT clock_timestamp(), -- backoff: not before
lease_token uuid, -- token of the attempt that holds the job
lease_owner text,
lease_until timestamptz,
error_code text,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
finished_at timestamptz,
CONSTRAINT jobs_pipeline_version CHECK (pipeline_version >= 1),
CONSTRAINT jobs_kind CHECK (kind IN ('upload', 'replay', 'reprocess', 'migrate')),
CONSTRAINT jobs_replay CHECK ((kind = 'replay') = (replay_of IS NOT NULL)),
CONSTRAINT jobs_state CHECK (state IN ('queued', 'processing', 'succeeded', 'failed', 'superseded')),
CONSTRAINT jobs_attempts CHECK (attempt >= 0 AND max_attempts BETWEEN 1 AND 100 AND attempt <= max_attempts),
-- A lease exists exactly while the job is processing.
CONSTRAINT jobs_lease CHECK ((state = 'processing') = (lease_token IS NOT NULL AND lease_until IS NOT NULL)),
CONSTRAINT jobs_finished CHECK ((state IN ('succeeded', 'failed', 'superseded')) = (finished_at IS NOT NULL)),
CONSTRAINT jobs_failed_code CHECK (state <> 'failed' OR error_code IS NOT NULL),
CONSTRAINT jobs_error_code CHECK (error_code ~ '^[a-z_]{1,64}$')
);
-- At most ONE active job per effect set (attachment, pipeline version): a second upload job,
-- replay or reprocess of the same version cannot exist while one is queued/processing.
CREATE UNIQUE INDEX jobs_one_active ON jobs (attachment_id, pipeline_version) WHERE state IN ('queued', 'processing');
CREATE INDEX jobs_attachment ON jobs (attachment_id, created_at);
CREATE INDEX jobs_lease_expiry ON jobs (lease_until) WHERE state = 'processing'; -- reaper
CREATE INDEX jobs_queued ON jobs (updated_at) WHERE state = 'queued'; -- lost-message guard
CREATE INDEX jobs_failed ON jobs (finished_at) WHERE state = 'failed'; -- failed registry
-- One row per claim of a job by a worker. The token is part of every object key the attempt
-- writes, so the keys of an attempt are known without listing the bucket (planned_keys), and an
-- attempt that is no longer the lease holder can never publish (fencing by token).
CREATE TABLE job_attempts (
token uuid PRIMARY KEY,
job_id uuid NOT NULL REFERENCES jobs (id),
attempt integer NOT NULL,
worker text NOT NULL,
source text NOT NULL, -- staging | original
planned_keys text[] NOT NULL,
outcome text NOT NULL DEFAULT 'running',
error_code text,
started_at timestamptz NOT NULL DEFAULT clock_timestamp(),
finished_at timestamptz,
objects_cleaned_at timestamptz,
CONSTRAINT job_attempts_number UNIQUE (job_id, attempt),
CONSTRAINT job_attempts_source CHECK (source IN ('staging', 'original')),
CONSTRAINT job_attempts_outcome
CHECK (outcome IN ('running', 'succeeded', 'retry', 'failed', 'abandoned', 'superseded')),
CONSTRAINT job_attempts_finished CHECK ((outcome = 'running') = (finished_at IS NULL)),
-- Objects of a successful attempt are published: they are never cleaned.
CONSTRAINT job_attempts_cleaned CHECK (objects_cleaned_at IS NULL OR outcome NOT IN ('running', 'succeeded'))
);
CREATE INDEX job_attempts_cleanup ON job_attempts (finished_at)
WHERE outcome IN ('retry', 'failed', 'abandoned', 'superseded') AND objects_cleaned_at IS NULL;
-- Published variants. The primary key is the idempotency key of the EFFECT from the contract:
-- (attachment_id, pipeline_version, variant) exists at most once, whatever the deliveries.
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments (id),
pipeline_version integer NOT NULL,
name text NOT NULL,
object_key text COLLATE "C" NOT NULL,
content_type text NOT NULL,
size_bytes integer NOT NULL,
width integer NOT NULL,
height integer NOT NULL,
sha256 bytea NOT NULL,
attempt_token uuid NOT NULL REFERENCES job_attempts (token),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (attachment_id, pipeline_version, name),
CONSTRAINT attachment_variants_key UNIQUE (object_key),
CONSTRAINT attachment_variants_key_format CHECK (object_key ~ '^a/[0-9a-f-]{36}/[0-9a-f]{32}/(thumbnail|crop|optimized)$'),
CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')),
CONSTRAINT attachment_variants_type CHECK (content_type IN ('image/jpeg', 'image/webp')),
CONSTRAINT attachment_variants_size CHECK (size_bytes >= 1 AND width >= 1 AND height >= 1),
CONSTRAINT attachment_variants_sha256 CHECK (octet_length(sha256) = 32)
);
-- Transactional outbox: written in the SAME transaction as the job (upload, retry, replay,
-- reprocess, lease expiry). The relay publishes due rows and marks them; a crash after the
-- publish but before the mark publishes again (a duplicate the worker ignores).
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES jobs (id),
attempt integer NOT NULL, -- the attempt this delivery is meant for
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
published_at timestamptz,
publish_failures integer NOT NULL DEFAULT 0,
CONSTRAINT outbox_attempt CHECK (attempt >= 1)
);
CREATE INDEX outbox_due ON outbox (available_at, id) WHERE published_at IS NULL;
CREATE INDEX outbox_job ON outbox (job_id);
CREATE INDEX outbox_published ON outbox (published_at) WHERE published_at IS NOT NULL; -- purge
-- Audit of every transition (no secrets, no file names): replay/reprocess requests with the
-- operator and reason, claims, retries with their delay, lease expiries, results.
CREATE TABLE job_events (
id bigint GENERATED ALWAYS AS IDENTITY 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 NOT NULL,
error_code text,
detail jsonb NOT NULL DEFAULT '{}'
);
CREATE INDEX job_events_job ON job_events (job_id, id);
-- Failed registry for the operator (jobctl list-failed).
CREATE VIEW failed_jobs AS
SELECT j.id AS job_id, j.attachment_id, j.pipeline_version, j.kind, j.attempt, j.max_attempts, j.error_code,
j.finished_at, a.status AS attachment_status, a.staging_state
FROM jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE j.state = 'failed';
-- Lab 4 'ready' rows (now queued): a job for pipeline 1 from their published original.
WITH queued AS (
SELECT a.id, gen_random_uuid() AS job_id FROM attachments a WHERE a.status = 'queued'
), created AS (
INSERT INTO jobs (id, attachment_id, pipeline_version, kind, max_attempts)
SELECT q.job_id, q.id, 1, 'migrate', 5 FROM queued q RETURNING id
)
INSERT INTO outbox (job_id, attempt) SELECT c.id, 1 FROM created c;
-- post_message_v3 = post_message_v2 (0004) with the lab 5 attachment states: queued, processing
-- and ready attachments of this chat may be attached; failed (or quarantined) -> 409; pending,
-- foreign or unknown -> 404. Everything else (key claim, chat clock, one transaction) unchanged.
CREATE FUNCTION post_message_v3(p_user uuid, p_chat uuid, p_key text, p_hash bytea, p_message uuid,
p_text bytea, p_ttl_seconds integer, p_attachments uuid[])
RETURNS TABLE (o_status text, o_id uuid, o_text bytea, o_created_at timestamptz, o_attachments uuid[])
LANGUAGE plpgsql VOLATILE AS $$
DECLARE
v_created timestamptz;
v_found integer;
v_usable integer;
v_check text := 'ok';
BEGIN
PERFORM 1 FROM chat_members m WHERE m.chat_id = p_chat AND m.user_id = p_user;
IF NOT FOUND THEN
RETURN QUERY SELECT 'not_found'::text, NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[];
RETURN;
END IF;
IF cardinality(p_attachments) > 0 THEN
-- FOR SHARE: a concurrent transition to failed/quarantine waits until this message commits.
SELECT count(*), count(*) FILTER (WHERE a.lost_at IS NULL AND a.status <> 'failed') INTO v_found, v_usable
FROM (SELECT a.lost_at, a.status FROM attachments a
WHERE a.id = ANY (p_attachments) AND a.chat_id = p_chat AND a.status <> 'pending'
FOR SHARE) a;
IF v_found <> cardinality(p_attachments) THEN
v_check := 'attachment_not_found';
ELSIF v_usable <> v_found THEN
v_check := 'attachment_conflict';
END IF;
END IF;
IF v_check = 'ok' THEN
INSERT INTO idempotency_keys AS k (user_id, chat_id, key, request_hash, message_id)
VALUES (p_user, p_chat, p_key, p_hash, p_message)
ON CONFLICT (user_id, chat_id, key) DO UPDATE
SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp()
WHERE k.created_at < clock_timestamp() - make_interval(secs => p_ttl_seconds);
IF FOUND THEN
UPDATE chats c SET last_message_at = greatest(clock_timestamp(), c.last_message_at + interval '1 microsecond')
WHERE c.id = p_chat RETURNING c.last_message_at INTO v_created;
INSERT INTO messages (id, chat_id, sender_id, text, created_at, attachment_ids)
VALUES (p_message, p_chat, p_user, p_text, v_created, p_attachments);
INSERT INTO message_attachments (message_id, position, attachment_id)
SELECT p_message, (a.ord - 1)::smallint, a.id
FROM unnest(p_attachments) WITH ORDINALITY AS a(id, ord);
RETURN QUERY SELECT 'created'::text, p_message, p_text, v_created, p_attachments;
RETURN;
END IF;
END IF;
RETURN QUERY
SELECT CASE WHEN k.request_hash = p_hash THEN 'replayed' ELSE 'conflict' END, m.id, m.text, m.created_at,
m.attachment_ids
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.key = p_key;
IF NOT FOUND THEN
RETURN QUERY SELECT CASE WHEN v_check = 'ok' THEN 'retry' ELSE v_check END,
NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[];
END IF;
END
$$;
+19
View File
@@ -0,0 +1,19 @@
-- Lab 6: trace context of a job and an index for the queue gauges.
--
-- jobs.traceparent / jobs.tracestate: W3C trace context of the request that created the job
-- (the upload, taken inside its HTTP server span). The relay publishes every outbox row of the
-- job (first attempt, retries, lease expiry, republish) as a PRODUCER span whose parent is this
-- context, and puts the producer's own context into the message (`traceparent` of
-- contracts/jobs.schema.json). One upload is therefore ONE trace: HTTP POST -> db enqueue ->
-- publish (relay) -> process (worker) -> S3/DB ... -> publish of the retry -> process ...
-- A job created by the operator CLI (jobctl replay/reprocess) has no context: NULL, and the relay
-- starts a new trace for it. The value is a 55-character technical id, never user data.
ALTER TABLE jobs
ADD COLUMN traceparent text COLLATE "C",
ADD COLUMN tracestate text COLLATE "C",
ADD CONSTRAINT jobs_traceparent CHECK (traceparent IS NULL OR traceparent ~ '^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$'),
ADD CONSTRAINT jobs_tracestate CHECK (tracestate IS NULL OR length(tracestate) <= 512);
-- Queue gauges of the relay (messenger.queue.depth / messenger.queue.oldest_age, every 5 s):
-- unfinished jobs by age. Partial index = only the few active rows, not the whole history.
CREATE INDEX jobs_active_age ON jobs (created_at) WHERE state IN ('queued', 'processing');
+53
View File
@@ -0,0 +1,53 @@
-- Lab 7: least privilege in PostgreSQL. The roles are created once by
-- infra/postgres/initdb/10-roles.sh; this migration (run by the owner messenger_migrate) gives
-- every service exactly the table privileges its code uses (src/messenger/*.py) and nothing else:
-- no DDL, no TRUNCATE, no DELETE where the service never deletes, no access to other services'
-- tables. Matrix with the reasons: contracts/trust-matrix.md ("PostgreSQL").
-- API: users, chats, messages, idempotency, sessions (SESSION_STORE=postgres), upload intents,
-- the job + outbox row of an accepted upload (one transaction with the attachment, lab 5).
GRANT SELECT, INSERT ON users TO messenger_api;
GRANT SELECT, INSERT, UPDATE ON chats TO messenger_api; -- per-chat clock (0001)
GRANT SELECT, INSERT ON chat_members TO messenger_api;
GRANT SELECT, INSERT ON messages TO messenger_api;
GRANT SELECT, INSERT ON message_attachments TO messenger_api;
GRANT SELECT, INSERT, UPDATE, DELETE ON idempotency_keys TO messenger_api; -- purge after 24 h
GRANT SELECT, INSERT, DELETE ON sessions TO messenger_api; -- logout = DELETE
GRANT SELECT, INSERT, UPDATE, DELETE ON attachments TO messenger_api; -- janitor: stale intents
GRANT SELECT ON attachment_variants TO messenger_api;
GRANT SELECT, INSERT ON jobs TO messenger_api;
GRANT INSERT ON outbox, job_events TO messenger_api;
-- Relay: outbox -> broker, lease reaper, republish of stale jobs, queue statistics.
GRANT SELECT, INSERT, UPDATE, DELETE ON outbox TO messenger_relay; -- purge published rows
GRANT SELECT, UPDATE ON jobs, job_attempts, attachments TO messenger_relay;
GRANT INSERT ON job_events TO messenger_relay;
-- Worker: claim/lease/complete/retry of jobs, variants, staging/attempt cleanup bookkeeping.
-- No access to users, chats, messages, sessions or idempotency keys.
GRANT SELECT, UPDATE ON jobs, attachments TO messenger_worker;
GRANT SELECT, INSERT, UPDATE ON job_attempts TO messenger_worker;
GRANT SELECT, INSERT ON attachment_variants TO messenger_worker;
GRANT INSERT ON outbox, job_events TO messenger_worker;
-- Operator CLI (jobctl): failed registry, replay/reprocess = new job + outbox row + audit event.
GRANT SELECT ON jobs, job_attempts, job_events, outbox, attachments, attachment_variants, failed_jobs TO messenger_jobctl;
GRANT INSERT ON jobs, outbox, job_events TO messenger_jobctl;
GRANT UPDATE ON jobs, attachments TO messenger_jobctl;
-- Auditor: read-only checker of the pipeline invariants.
GRANT SELECT ON jobs, job_attempts, job_events, outbox, attachments, attachment_variants TO messenger_auditor;
-- job_events (pipeline audit log, no user data): the failure-injection points of the experiments
-- (service.crash_once, FAULT_POINTS) look up their own "fault_injected" marker before crashing, so
-- the services that can crash on purpose may read it.
GRANT SELECT ON job_events TO messenger_api, messenger_relay, messenger_worker;
-- Identity columns of outbox/job_events: inserting roles need the sequences.
GRANT USAGE ON SEQUENCE outbox_id_seq, job_events_id_seq
TO messenger_api, messenger_relay, messenger_worker, messenger_jobctl;
-- Functions are executable by PUBLIC by default; only the API sends messages.
REVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC;
GRANT EXECUTE ON FUNCTION post_message, post_message_v2, post_message_v3 TO messenger_api;
ALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;
+8
View File
@@ -0,0 +1,8 @@
# Student tests (in-process, via Starlette TestClient). Runtime deps come from requirements.txt.
pytest==9.1.1
httpx2==2.13.1
jsonschema==4.26.0
# Lab 4 tests: generate PNG/JPEG fixtures (valid, corrupt, oversized) on the fly.
pillow==12.3.0
# Lab 7: local PKI (scripts/init_pki.py): CA and service certificates, run on the operator's host.
cryptography==50.0.2
+30
View File
@@ -0,0 +1,30 @@
# Direct runtime dependencies. The pinned lock with hashes is requirements.txt:
# docker run --rm -v "$PWD:/w" -w /w python:3.13.16-slim-bookworm \
# sh -c "pip install -q pip-tools==7.6.1 && pip-compile --generate-hashes --strip-extras --no-emit-index-url -o requirements.txt requirements.in"
starlette==1.7.0
uvicorn==0.54.0
# Fast C parser/event loop used by uvicorn in the container (Linux only).
httptools==0.9.0
uvloop==0.23.0 ; sys_platform != "win32"
# PostgreSQL driver (libpq bundled in the binary wheel) and its async connection pool.
psycopg==3.3.6
psycopg-binary==3.3.6
psycopg-pool==3.3.3
# Valkey client (Valkey speaks the Redis protocol).
redis==8.1.0
# Argon2id password KDF.
argon2-cffi==25.1.0
# Lab 4: S3 client (async botocore over aiohttp; requests are cancellable, unlike libpq cancel).
aiobotocore==3.9.2
# Lab 5: AMQP 0-9-1 client for RabbitMQ (publisher confirms, consumer acks, prefetch); last 9.x line.
aio-pika==9.6.2
# Lab 5: image variants in the worker only (thumbnail/crop JPEG, WebP). Same version as the tests.
pillow==12.3.0
# Uploads are still checked without Pillow: PNG by src/messenger/images.py, JPEG by libjpeg-turbo
# `djpeg -strict` (Debian package libjpeg-turbo-progs, see Dockerfile).
# Lab 6: OpenTelemetry SDK (traces, metrics, logs) and the OTLP/HTTP (protobuf) exporter to the
# Collector. Instrumentation is written by hand in telemetry.py/app.py/db.py/storage.py/relay/worker
# (no auto-instrumentation packages): span names, attributes and buckets are under our control.
opentelemetry-api==1.45.2
opentelemetry-sdk==1.45.2
opentelemetry-exporter-otlp-proto-http==1.45.2
+1709
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper: runs scripts\bao_check.sh (OpenBao allow/deny, no root credential in apps) with Git Bash.
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0bao_check.sh"
exit /b %ERRORLEVEL%
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""OpenBao allow/deny check, run INSIDE a service container with that service's own credentials:
docker compose exec -T api python - < scripts/bao_check.py (wrapper: scripts/bao_check.sh)
Uses exactly what the service has: BAO_ADDR, BAO_CACERT (server verified), BAO_ROLE_ID_FILE,
BAO_SECRET_ID_FILE, BAO_SECRET_PATH. Prints status codes and key NAMES only, never values or tokens.
Expected for service S (api | relay | worker):
allow AppRole login; read messenger/data/S; token lookup-self; revoke-self
deny read messenger/data/<other services>; write/patch messenger/data/S; list metadata;
write a policy; read the policy list; create a token; enable an auth method; read sys/mounts
deny the revoked token afterwards; a login with a wrong secret_id
"""
import json
import os
import ssl
import sys
import urllib.error
import urllib.request
ADDR = os.environ["BAO_ADDR"].rstrip("/")
CTX = ssl.create_default_context(cafile=os.environ["BAO_CACERT"])
PATH = os.environ["BAO_SECRET_PATH"]
SERVICE = PATH.rsplit("/", 1)[-1]
OTHERS = [s for s in ("api", "relay", "worker") if s != SERVICE]
def call(method, path, token=None, body=None):
data = json.dumps(body).encode() if body is not None else (b"{}" if method in ("POST", "PUT") else None)
req = urllib.request.Request(f"{ADDR}/v1/{path}", data=data, method=method,
headers={"Content-Type": "application/json", **({"X-Vault-Token": token} if token else {})})
try:
with urllib.request.urlopen(req, timeout=5, context=CTX) as r:
raw = r.read()
return r.status, (json.loads(raw) if raw else {})
except urllib.error.HTTPError as exc:
return exc.code, {}
def read(name):
with open(os.environ[name], encoding="utf-8") as f:
return f.read().strip()
failures = 0
def expect(label, status, allowed):
global failures
ok = (200 <= status < 300) if allowed else status in (400, 403)
failures += not ok
print(f" {'PASS' if ok else 'FAIL'} {'allow' if allowed else 'deny '} {label:58s} -> HTTP {status}")
print(f"service {SERVICE}: OpenBao {ADDR} (TLS verified against {os.environ['BAO_CACERT']})")
status, body = call("POST", "auth/approle/login", body={"role_id": read("BAO_ROLE_ID_FILE"), "secret_id": read("BAO_SECRET_ID_FILE")})
expect("AppRole login with the service's role_id/secret_id", status, True)
auth = body.get("auth") or {}
token = auth.get("client_token", "")
print(f" token policies={auth.get('token_policies')} ttl={auth.get('lease_duration')}s renewable={auth.get('renewable')}")
status, body = call("GET", PATH, token)
expect(f"read own path {PATH}", status, True)
print(f" keys: {sorted((body.get('data') or {}).get('data') or {})}")
status, _ = call("GET", "auth/token/lookup-self", token)
expect("token lookup-self", status, True)
for other in OTHERS:
expect(f"read other service's path messenger/data/{other}", call("GET", f"messenger/data/{other}", token)[0], False)
expect(f"write own path {PATH}", call("POST", PATH, token, {"data": {"x": "y"}})[0], False)
expect("list messenger/metadata", call("LIST", "messenger/metadata", token)[0], False)
expect(f"write policy sys/policies/acl/{SERVICE}", call("PUT", f"sys/policies/acl/{SERVICE}", token, {"policy": 'path "*" {capabilities=["sudo"]}'})[0], False)
expect("read policy list sys/policies/acl", call("LIST", "sys/policies/acl", token)[0], False)
expect("create a child token auth/token/create", call("POST", "auth/token/create", token, {"policies": ["api"]})[0], False)
expect("enable an auth method sys/auth/userpass", call("POST", "sys/auth/userpass", token, {"type": "userpass"})[0], False)
expect("read sys/mounts", call("GET", "sys/mounts", token)[0], False)
expect("revoke-self", call("POST", "auth/token/revoke-self", token)[0], True)
expect("use the token after revoke-self (lookup-self)", call("GET", "auth/token/lookup-self", token)[0], False)
expect("read own path with the revoked token", call("GET", PATH, token)[0], False)
expect("AppRole login with a wrong secret_id", call("POST", "auth/approle/login", body={"role_id": read("BAO_ROLE_ID_FILE"), "secret_id": "00000000-0000-0000-0000-000000000000"})[0], False)
print(f"{'PASS' if failures == 0 else 'FAIL'}: OpenBao policy of {SERVICE}, {failures} failure(s)")
sys.exit(1 if failures else 0)
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# OpenBao proof (README defense step 4): policy allow/deny for every service + no root credential
# in the application containers. Prints PASS/FAIL lines, never a token, share or secret value.
# sh scripts/bao_check.sh (Windows: scripts\bao_check.cmd)
set -u
cd "$(dirname "$0")/.."
export MSYS_NO_PATHCONV=1 # Git Bash: keep /run/secrets as a container path
OPERATOR_DIR="${OPERATOR_DIR:-$HOME/.mtusi-lab7-operator/${COMPOSE_PROJECT_NAME:-mtusi-lab7}}"
rc=0
for svc in api relay worker; do
echo "== $svc"
docker compose exec -T "$svc" python - < scripts/bao_check.py || rc=1
done
echo
echo "== root credential / unseal material in the application containers (values compared, never printed)"
for svc in api relay worker; do
# 1. no token-like variable in the container configuration
names="$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$(docker compose ps -q "$svc" | head -1)" \
| cut -d= -f1 | grep -iE 'TOKEN|UNSEAL|ROOT' || true)"
if [ -n "$names" ]; then echo " FAIL $svc: token-like env names: $names"; rc=1; else echo " PASS $svc: no *TOKEN*/*UNSEAL*/*ROOT* environment variable"; fi
# 2. the operator's root token and unseal shares do not occur anywhere in the container's
# secrets, code, temp files or process environment (fed via stdin, compared inside)
# Positive control: the same search MUST find a value that is there (the service's own role_id),
# otherwise "absent" below would prove nothing.
found="$(docker compose exec -T "$svc" sh -c 'read -r v; grep -rlsF -- "$v" /run/secrets | head -1' < "secrets/bao/${svc}_role_id")"
if [ -n "$found" ]; then echo " PASS control: own role_id found by the same search ($found)"; else echo " FAIL control search found nothing"; rc=1; fi
for f in root-token unseal-share-1 unseal-share-2 unseal-share-3; do
if [ ! -f "$OPERATOR_DIR/$f" ]; then echo " FAIL operator file $f missing in $OPERATOR_DIR"; rc=1; continue; fi
found="$(docker compose exec -T "$svc" sh -c 'read -r v; for p in /run/secrets /app /tmp /proc/1/environ; do grep -rqsF -- "$v" "$p" && echo "$p"; done; true' < "$OPERATOR_DIR/$f")"
if [ -n "$found" ]; then echo " FAIL $svc: $f found in $found"; rc=1; else echo " PASS $svc: $f absent (/run/secrets, /app, /tmp, PID 1 environment)"; fi
done
echo " $svc /run/secrets: $(docker compose exec -T "$svc" ls /run/secrets | tr '\n' ' ')"
done
[ "$rc" = 0 ] && echo "PASS: OpenBao allow/deny and no root credential in the application" || echo "FAIL"
exit "$rc"
+183
View File
@@ -0,0 +1,183 @@
#!/usr/bin/env python3
"""OpenBao operator actions of the lab 7 stand (docs/OPERATOR.md). Stdlib only; run on the host.
python scripts/bao_operator.py bootstrap # init (once) + unseal + configure + issue AppRole creds
python scripts/bao_operator.py unseal # after every OpenBao (re)start: it starts SEALED
python scripts/bao_operator.py status # initialized / sealed / mounts / roles (no secrets)
python scripts/bao_operator.py new-secret-id api # issue a new SecretID for one service
Who holds what:
* unseal shares (3, threshold 2) and the root token: the OPERATOR, in OPERATOR_DIR, outside the
repository (default ~/.mtusi-lab7-operator/<compose project>/, files 0600). Never in Git, never
in a container of the application, never printed. In a real team the 3 shares go to 3 people.
* role_id + secret_id of api / relay / worker: ./secrets/bao/ (git-ignored), each pair mounted as
a Docker secret ONLY into its own service - the "first secret" the service logs in with.
* the root token is used only by this script, for configuration.
Every secret travels to the OpenBao CLI over the STDIN of `docker compose exec` (never as a command
line argument or an environment variable of a process): the root token is the first stdin line,
read by `read -r BAO_TOKEN`; KV values and policies follow as JSON/HCL on stdin (`-`).
The CLI runs inside the openbao container against https://127.0.0.1:8200 with the internal CA
(BAO_ADDR/BAO_CACERT in compose.yaml): the server certificate is verified.
Idempotent: init only if not initialized; mounts/auth/policies/roles/KV are (re)written to the
state described here; an existing secret_id file is kept unless `new-secret-id` is asked.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / "secrets"
POLICIES = ROOT / "infra" / "openbao" / "policies"
PROJECT = os.environ.get("COMPOSE_PROJECT_NAME", "mtusi-lab7")
OPERATOR_DIR = Path(os.environ.get("OPERATOR_DIR") or Path.home() / ".mtusi-lab7-operator" / PROJECT)
SHARES, THRESHOLD = 3, 2
# Token of a service: 1 h, at most 4 h with renewals; the services revoke it right after reading.
# SecretID: valid 30 days, unlimited logins (every restart of a replica logs in again).
ROLE_SETTINGS = ["token_ttl=1h", "token_max_ttl=4h", "token_type=service", "token_no_default_policy=true",
"secret_id_ttl=720h", "secret_id_num_uses=0"]
# What each service may read: KV v2 messenger/data/<service>. Values come from ./secrets.
SERVICE_SECRETS = {
"api": {"database_url": "database_url_api", "cache_url": "cache_url",
"s3_access_key_id": "s3_api_access_key_id", "s3_secret_access_key": "s3_api_secret_access_key"},
"relay": {"database_url": "database_url_relay", "broker_url": "broker_url_relay"},
"worker": {"database_url": "database_url_worker", "broker_url": "broker_url_worker",
"s3_access_key_id": "s3_worker_access_key_id", "s3_secret_access_key": "s3_worker_secret_access_key"},
}
def say(text: str) -> None:
print(f"bao-operator: {text}", flush=True)
def bao(*args: str, token: str | None = None, stdin: bytes = b"", check: bool = True) -> subprocess.CompletedProcess:
"""Run `bao <args>` inside the openbao container; the token (if any) is the first stdin line."""
script = 'read -r BAO_TOKEN; export BAO_TOKEN; exec bao "$@"' if token else 'exec bao "$@"'
data = ((token + "\n").encode() if token else b"") + stdin
result = subprocess.run(["docker", "compose", "exec", "-T", "openbao", "sh", "-c", script, "sh", *args],
input=data, capture_output=True, cwd=ROOT)
if check and result.returncode != 0:
# stderr of the CLI names the failing path/permission; it never contains our stdin data.
raise SystemExit(f"bao-operator: `bao {' '.join(args)}` failed: {result.stderr.decode(errors='replace').strip()[:400]}")
return result
def status() -> dict:
result = bao("status", "-format=json", check=False) # exit 2 = sealed, still prints JSON
if result.returncode not in (0, 2):
raise SystemExit("bao-operator: OpenBao is not reachable (is `docker compose up -d openbao` running?): "
+ result.stderr.decode(errors="replace").strip()[:300])
return json.loads(result.stdout)
def private_write(path: Path, value: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(value + "\n", encoding="utf-8", newline="\n")
os.chmod(path, 0o600)
def operator_file(name: str) -> str:
path = OPERATOR_DIR / name
if not path.exists():
raise SystemExit(f"bao-operator: {path} is missing: the operator material of this OpenBao is not here")
return path.read_text(encoding="utf-8").strip()
def init() -> None:
if status()["initialized"]:
say("already initialized")
return
if (OPERATOR_DIR / "root-token").exists():
raise SystemExit(f"bao-operator: OpenBao is NOT initialized but {OPERATOR_DIR} has material of an older "
"instance; move it away first (it does not belong to this storage)")
out = json.loads(bao("operator", "init", f"-key-shares={SHARES}", f"-key-threshold={THRESHOLD}", "-format=json").stdout)
for i, share in enumerate(out["unseal_keys_b64"], 1):
private_write(OPERATOR_DIR / f"unseal-share-{i}", share)
private_write(OPERATOR_DIR / "root-token", out["root_token"])
os.chmod(OPERATOR_DIR, 0o700)
say(f"initialized: {SHARES} unseal shares (threshold {THRESHOLD}) and the root token saved to {OPERATOR_DIR} "
"(outside the repository; not printed)")
def unseal() -> None:
state = status()
if not state["initialized"]:
raise SystemExit("bao-operator: not initialized yet: run `bootstrap`")
if not state["sealed"]:
say("already unsealed")
return
for i in range(1, THRESHOLD + 1):
bao("write", "-format=json", "sys/unseal", "key=-", stdin=operator_file(f"unseal-share-{i}").encode())
state = status()
if state["sealed"]:
raise SystemExit("bao-operator: still sealed after the threshold of shares")
say(f"unsealed with {THRESHOLD} of {SHARES} shares")
def secret(name: str) -> str:
return (SECRETS / name).read_text(encoding="utf-8").strip()
def configure() -> None:
token = operator_file("root-token")
mounts = json.loads(bao("secrets", "list", "-format=json", token=token).stdout)
if "messenger/" not in mounts:
bao("secrets", "enable", "-path=messenger", "-version=2", "kv", token=token)
say("KV v2 mounted at messenger/")
auths = json.loads(bao("auth", "list", "-format=json", token=token).stdout)
if "approle/" not in auths:
bao("auth", "enable", "approle", token=token)
say("auth method approle enabled")
# The audit device (file -> container stdout) is declared in infra/openbao/config.hcl:
# OpenBao 2.7 refuses to enable audit devices over the API.
for service, values in SERVICE_SECRETS.items():
bao("policy", "write", service, "-", token=token, stdin=(POLICIES / f"{service}.hcl").read_bytes())
bao("write", f"auth/approle/role/{service}", f"token_policies={service}", *ROLE_SETTINGS, token=token)
data = {key: secret(source) for key, source in values.items()}
bao("kv", "put", "-mount=messenger", service, "-", token=token, stdin=json.dumps(data).encode())
role_id = json.loads(bao("read", "-format=json", f"auth/approle/role/{service}/role-id", token=token).stdout)["data"]["role_id"]
private_write(SECRETS / "bao" / f"{service}_role_id", role_id)
os.chmod(SECRETS / "bao" / f"{service}_role_id", 0o644) # readable by the container user (bind mount)
if not (SECRETS / "bao" / f"{service}_secret_id").exists():
issue_secret_id(service, token)
say(f"{service}: policy {service} (read messenger/data/{service}), AppRole, KV keys {sorted(data)}")
def issue_secret_id(service: str, token: str | None = None) -> None:
token = token or operator_file("root-token")
out = json.loads(bao("write", "-f", "-format=json", f"auth/approle/role/{service}/secret-id", token=token).stdout)
path = SECRETS / "bao" / f"{service}_secret_id"
private_write(path, out["data"]["secret_id"])
os.chmod(path, 0o644) # the service reads it through the bind mount (folder ./secrets is 0700)
say(f"{service}: new SecretID written to secrets/bao/{service}_secret_id (TTL 720h; not printed)")
def main(argv: list[str]) -> int:
command = argv[0] if argv else "status"
if command == "bootstrap":
init()
unseal()
configure()
say("done; start the stand: docker compose up -d --build --wait")
elif command == "unseal":
unseal()
elif command == "status":
state = status()
say(f"initialized={state['initialized']} sealed={state['sealed']} storage={state.get('storage_type')} "
f"version={state.get('version')} operator_dir={OPERATOR_DIR}")
elif command == "new-secret-id" and len(argv) == 2 and argv[1] in SERVICE_SECRETS:
issue_secret_id(argv[1])
say(f"restart the service to use it: docker compose up -d --force-recreate {argv[1]}")
else:
print(__doc__)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+11
View File
@@ -0,0 +1,11 @@
# Run a long command as a separate Windows process that survives the calling shell/session.
# powershell -File scripts/bg.ps1 -Log evidence/run.log -Cmd "docker compose up -d --build --wait"
# The command runs in Git Bash (same syntax as the Makefile/hooks); the exit code is the last
# line of the log ("exit=N"). Nothing secret is printed by the commands used with it.
param([Parameter(Mandatory)][string]$Log, [Parameter(Mandatory)][string]$Cmd)
$bash = Join-Path $env:ProgramFiles "Git\bin\bash.exe"
$root = Split-Path -Parent $PSScriptRoot
$logPath = if ([IO.Path]::IsPathRooted($Log)) { $Log } else { Join-Path $root $Log }
New-Item -ItemType Directory -Force (Split-Path -Parent $logPath) | Out-Null
$inner = "cd '$($root -replace '\\','/')' && export PYTHONUTF8=1 && { $Cmd ; } > '$($logPath -replace '\\','/')' 2>&1; echo exit=`$? >> '$($logPath -replace '\\','/')'"
Start-Process -FilePath $bash -ArgumentList @('-lc', "`"$inner`"") -WindowStyle Hidden
+294
View File
@@ -0,0 +1,294 @@
#!/usr/bin/env python3
"""Generate the Grafana dashboard infra/grafana/dashboards/messenger.json (provisioned at start).
python scripts/build_dashboard.py
Every panel names its query and unit here, in one place (docs/OBSERVABILITY.md copies the list).
Percentiles are ALWAYS histogram_quantile over buckets summed `by (le)` across every replica -
never an average of per-replica percentiles. Datasource UIDs are the fixed provisioned ones.
"""
from __future__ import annotations
import json
import sys
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"}
BUSINESS = 'job="messenger-api", http_route!~"/health/.*"'
panels: list[dict] = []
_next_id = [1]
_y = [0]
def _id() -> int:
_next_id[0] += 1
return _next_id[0]
def row(title: str) -> None:
panels.append({"type": "row", "title": title, "id": _id(), "collapsed": False, "panels": [],
"gridPos": {"h": 1, "w": 24, "x": 0, "y": _y[0]}})
_y[0] += 1
class Grid:
"""Places panels left to right, wrapping at 24 columns."""
def __init__(self) -> None:
self.x = 0
self.h = 0
def place(self, w: int, h: int) -> dict:
if self.x + w > 24:
_y[0] += self.h
self.x, self.h = 0, 0
pos = {"h": h, "w": w, "x": self.x, "y": _y[0]}
self.x += w
self.h = max(self.h, h)
return pos
def end(self) -> None:
_y[0] += self.h
self.x, self.h = 0, 0
grid = Grid()
def ts(title: str, targets: list[tuple[str, str]], unit: str, description: str, *, w: int = 8, h: int = 8,
stack: bool = False, minimum: float | None = 0, maximum: float | None = None, thresholds=None) -> None:
defaults: dict = {"unit": unit, "custom": {"lineWidth": 1, "fillOpacity": 10 if not stack else 40,
"showPoints": "never",
"stacking": {"mode": "normal" if stack else "none", "group": "A"}}}
if minimum is not None:
defaults["min"] = minimum
if maximum is not None:
defaults["max"] = maximum
if thresholds:
defaults["thresholds"] = {"mode": "absolute", "steps": thresholds}
defaults["custom"]["thresholdsStyle"] = {"mode": "line+area"}
panels.append({
"type": "timeseries", "title": title, "id": _id(), "datasource": PROM,
"description": description + f"\n\nUnit: {unit}.",
"gridPos": grid.place(w, h),
"fieldConfig": {"defaults": defaults, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom", "showLegend": True},
"tooltip": {"mode": "multi", "sort": "desc"}},
"targets": [{"refId": chr(65 + i), "datasource": PROM, "expr": expr, "legendFormat": legend, "range": True}
for i, (expr, legend) in enumerate(targets)],
})
def stat(title: str, expr: str, unit: str, description: str, steps, *, w: int = 6, h: int = 5, decimals: int = 2) -> None:
panels.append({
"type": "stat", "title": title, "id": _id(), "datasource": PROM,
"description": description + f"\n\nUnit: {unit}.",
"gridPos": grid.place(w, h),
"fieldConfig": {"defaults": {"unit": unit, "decimals": decimals,
"thresholds": {"mode": "absolute", "steps": steps}}, "overrides": []},
"options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False},
"colorMode": "background", "graphMode": "area", "textMode": "value"},
"targets": [{"refId": "A", "datasource": PROM, "expr": expr, "instant": False, "range": True}],
})
def q(phi: float, metric: str, selector: str, window: str = "$__rate_interval", by: str = "") -> str:
group = f"le{', ' + by if by else ''}"
return f"histogram_quantile({phi}, sum by ({group}) (rate({metric}_bucket{{{selector}}}[{window}])))"
# =============================================================================== API
row("API: requests, errors, latency (all replicas)")
ts("Requests per second by route",
[(f"sum by (http_route) (rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "{{http_route}}")],
"reqps", "Business requests (no /health/*) per second, summed over the API replicas. "
"Counter = _count of the histogram http.server.request.duration (no second instrument).", stack=True)
ts("Error ratio (5xx and 4xx / all business requests)",
[(f"(sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}, http_response_status_class=\"5xx\"}}[$__rate_interval])) or vector(0)) "
f"/ sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "5xx (SLI: server failures)"),
(f"(sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}, http_response_status_class=\"4xx\"}}[$__rate_interval])) or vector(0)) "
f"/ sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "4xx (client errors, not in the SLI)")],
"percentunit", "Numerator: 5xx (or 4xx) business requests; denominator: all business requests. "
"Alert MessengerApiHighErrorRate: 5xx > 5 % for 1 min.",
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 0.05}])
ts("Latency p50 / p95 / p99 (all routes, all replicas)",
[(q(0.50, "http_server_request_duration_seconds", BUSINESS), "p50"),
(q(0.95, "http_server_request_duration_seconds", BUSINESS), "p95"),
(q(0.99, "http_server_request_duration_seconds", BUSINESS), "p99")],
"s", "histogram_quantile over the buckets of http.server.request.duration summed by le across replicas "
"(buckets 1 ms ... 10 s). Not an average, not per-replica p99s averaged.")
ts("p95 by route",
[(q(0.95, "http_server_request_duration_seconds", BUSINESS, by="http_route"), "{{http_route}}")],
"s", "Per route template, buckets of all replicas.", w=12)
ts("Requests in flight by replica",
[("sum by (instance) (http_server_active_requests{job=\"messenger-api\"})", "{{instance}}")],
"short", "UpDownCounter http.server.active_requests per API replica (saturation of the HTTP layer).", w=12)
grid.end()
# =============================================================================== worker
row("Worker and queue")
ts("Jobs handled per second by outcome",
[("sum by (outcome) (rate(messenger_jobs_processed_total[$__rate_interval]))", "{{outcome}}")],
"ops", "messenger.jobs.processed: succeeded / retry / failed / fenced / superseded / noop_* / deferred / rejected.",
stack=True)
ts("Job duration p50 / p95 / p99 (succeeded)",
[(q(0.50, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p50"),
(q(0.95, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p95"),
(q(0.99, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p99")],
"s", "One delivery in the worker: claim -> S3 read -> variants -> S3 writes -> COMMIT -> ack.")
ts("Time to ready p50 / p95 / p99 (uploads)",
[(q(0.50, "messenger_attachment_time_to_ready_seconds", ""), "p50"),
(q(0.95, "messenger_attachment_time_to_ready_seconds", ""), "p95"),
(q(0.99, "messenger_attachment_time_to_ready_seconds", ""), "p99")],
"s", "From the durable acceptance (job COMMIT before 202) to the COMMIT of status ready. "
"Includes queue wait and retries. SLO: 99 % within 30 s.")
ts("Queue depth (PostgreSQL) and outbox",
[("max by (state) (messenger_queue_depth)", "jobs {{state}}"),
("max by (state) (messenger_outbox_pending)", "outbox {{state}}")],
"short", "messenger.queue.depth: unfinished jobs (queued incl. retry wait / processing); "
"messenger.outbox.pending: unpublished messages (due / delayed). Reported by the relay every 5 s.")
ts("Oldest job age / oldest due outbox row",
[("max(messenger_queue_oldest_age_seconds)", "oldest unfinished job"),
("max(messenger_outbox_oldest_age_seconds)", "oldest due outbox row (broker)")],
"s", "Age of the oldest unfinished job (now - acceptance). Grows when nobody processes the queue. "
"Alert MessengerQueueLagGrowing: > 60 s for 1 min with queued jobs.",
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 60}])
ts("Worker saturation (busy / capacity)",
[("sum(messenger_worker_busy) / sum(messenger_worker_capacity)", "busy share")],
"percentunit", "messenger.worker.busy (attempts running) / messenger.worker.capacity (WORKER_CONCURRENCY), "
"all worker processes. 100 % for long = the worker is the bottleneck.", maximum=1)
grid.end()
# =============================================================================== DB and resources
row("Database pool and resources")
ts("DB pool: used / max, waiting requests",
[("sum by (job) (db_client_connection_count{db_client_connection_state=\"used\"})", "{{job}} used"),
("sum by (job) (db_client_connection_max)", "{{job}} max"),
("sum by (job) (db_client_connection_pending_requests)", "{{job}} waiting")],
"short", "psycopg_pool counters per service (all replicas summed). Waiting > 0 = pool exhausted.")
ts("DB unit of work p95 by service",
[(q(0.95, "db_client_operation_duration_seconds", "", by="job"), "{{job}}")],
"s", "db.client.operation.duration: pool wait + statements + COMMIT of one Database.run().")
ts("DB pool wait p95 by service",
[(q(0.95, "db_client_connection_wait_time_seconds", "", by="job"), "{{job}}")],
"s", "db.client.connection.wait_time: time to get a connection from the pool.")
ts("Container CPU (cores)",
[("sum by (job, instance) (rate(container_cpu_time_seconds_total[$__rate_interval]))", "{{job}} {{instance}}"),
("rate(otelcol_process_cpu_seconds_total[$__rate_interval])", "otel-collector")],
"short", "cgroup cpu.stat of each application container (1 = one full core); Collector: its own counter.", w=12)
ts("Container memory",
[("sum by (job, instance) (container_memory_usage_bytes)", "{{job}} {{instance}}"),
("otelcol_process_memory_rss_bytes", "otel-collector RSS")],
"bytes", "cgroup memory.current of each application container; Collector RSS (memory_limiter: 400 MiB).", w=12)
grid.end()
# =============================================================================== SLO
row("SLO (docs/SLO.md) and alerts")
stat("Availability, last 1 h (target 99 %)", "1 - messenger:http_error_ratio:rate1h", "percentunit",
"1 - 5xx/all business requests over 1 h.",
[{"color": "red", "value": None}, {"color": "orange", "value": 0.99}, {"color": "green", "value": 0.995}], decimals=3)
stat("Requests under 250 ms, last 5 min (target 95 %)", "messenger:http_fast_ratio:rate5m", "percentunit",
"Share of business requests in buckets le=0.25.",
[{"color": "red", "value": None}, {"color": "green", "value": 0.95}], decimals=3)
stat("Uploads ready within 30 s, last 1 h (target 99 %)", "messenger:ready_within_30s_ratio:rate1h", "percentunit",
"Share of uploads with time_to_ready <= 30 s.",
[{"color": "red", "value": None}, {"color": "green", "value": 0.99}], decimals=3)
stat("Alerts firing", "count(ALERTS{alertstate=\"firing\"}) or vector(0)", "none",
"Number of firing Prometheus alerts (table below).", [{"color": "green", "value": None}, {"color": "red", "value": 1}],
decimals=0)
panels.append({
"type": "table", "title": "Alerts (pending / firing)", "id": _id(), "datasource": PROM,
"description": "ALERTS series of Prometheus (rules: infra/prometheus/rules/alerts.yml, runbook: docs/RUNBOOK.md).",
"gridPos": grid.place(24, 6),
"targets": [{"refId": "A", "datasource": PROM, "expr": "ALERTS", "instant": True, "format": "table"}],
"transformations": [{"id": "organize", "options": {"excludeByName": {"Time": True, "Value": True, "__name__": True},
"indexByName": {}, "renameByName": {}}}],
"fieldConfig": {"defaults": {}, "overrides": []}, "options": {"showHeader": True},
})
grid.end()
# =============================================================================== telemetry pipeline
row("Telemetry pipeline (Collector, SDK)")
ts("Collector: spans accepted / sent / failed per second",
[("sum(rate(otelcol_receiver_accepted_spans_total[$__rate_interval]))", "accepted"),
("sum(rate(otelcol_receiver_refused_spans_total[$__rate_interval]))", "refused (memory_limiter)"),
("sum(rate(otelcol_exporter_sent_spans_total[$__rate_interval]))", "sent to Tempo"),
("sum(rate(otelcol_exporter_send_failed_spans_total[$__rate_interval]))", "send failed (dropped)")],
"ops", "otelcol_* self-metrics, pushed over OTLP/HTTPS (lab 7). sent < accepted with tail sampling (dropped by policy).")
ts("Collector: logs and metric points per second",
[("sum(rate(otelcol_receiver_accepted_log_records_total[$__rate_interval]))", "logs accepted"),
("sum(rate(otelcol_exporter_send_failed_log_records_total[$__rate_interval]))", "logs failed"),
("sum(rate(otelcol_receiver_accepted_metric_points_total[$__rate_interval]))", "metric points accepted"),
("sum(rate(otelcol_exporter_send_failed_metric_points_total[$__rate_interval]))", "metric points failed")],
"ops", "Same for the logs and metrics pipelines.")
ts("Collector: exporter queues",
[("max by (exporter) (otelcol_exporter_queue_size)", "{{exporter}} size"),
("max by (exporter) (otelcol_exporter_queue_capacity)", "{{exporter}} capacity")],
"short", "Bounded sending_queue (batches) per exporter: fills while a backend is down, never above capacity.")
ts("SDK: spans recorded vs exported (all processes)",
[("sum by (job) (rate(messenger_telemetry_spans_ended_total[$__rate_interval]))", "{{job}} recorded"),
("sum by (job, result) (rate(messenger_telemetry_spans_exported_total[$__rate_interval]))", "{{job}} export {{result}}")],
"ops", "Spans finished in the process (sampled) and handed to the OTLP exporter: success / failure (Collector down).",
w=12)
ts("Telemetry components up",
[("up{job=~\"prometheus|loki|tempo\"}", "{{job}}")],
"short", "1 = the scrape succeeded.", w=12, maximum=1)
grid.end()
# =============================================================================== logs and traces
row("Logs and traces")
panels.append({
"type": "logs", "title": "Application logs (Loki): warnings and errors", "id": _id(), "datasource": LOKI,
"description": "OTLP log records of api/relay/worker. Expand a line: trace_id links to Tempo. "
"Query: {service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\".",
"gridPos": grid.place(12, 10),
"targets": [{"refId": "A", "datasource": LOKI, "expr": "{service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\"",
"queryType": "range"}],
"options": {"showTime": True, "wrapLogMessage": True, "enableLogDetails": True, "sortOrder": "Descending",
"dedupStrategy": "none", "prettifyLogMessage": False},
})
panels.append({
"type": "table", "title": "Recent upload traces (Tempo)", "id": _id(), "datasource": TEMPO,
"description": "TraceQL: POST of an attachment. Click a trace id: upload -> enqueue -> publish -> process -> S3/DB.",
"gridPos": grid.place(12, 10),
"targets": [{"refId": "A", "datasource": TEMPO, "queryType": "traceql", "limit": 20, "tableType": "traces",
"query": "{ span.http.route = \"/api/v1/chats/{chat_id}/attachments\" }"}],
"fieldConfig": {"defaults": {}, "overrides": []}, "options": {"showHeader": True},
})
grid.end()
dashboard = {
"uid": "messenger-lab6",
"title": "Messenger lab 6: API, worker, queue, SLO",
"description": "Generated by scripts/build_dashboard.py - edit the script, not the JSON.",
"tags": ["messenger", "lab6"],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"editable": False,
"graphTooltip": 1,
"refresh": "10s",
"time": {"from": "now-30m", "to": "now"},
"templating": {"list": []},
"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,
}
def main() -> int:
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(dashboard, indent=1, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n")
print(f"written {OUT.relative_to(OUT.parents[3])}: {len(panels)} panels")
return 0
if __name__ == "__main__":
sys.exit(main())
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Run EVERY query of the provisioned dashboard through Grafana (/api/ds/query) and report, per
panel: error / no data / number of series. Proves that the dashboard refers to metric names,
labels and datasource UIDs that really exist (not only that the JSON was imported).
python scripts/check_dashboard.py [--minutes 30] [--output evidence/dashboard-check.txt]
Exit code 1 if a query fails. "no data" is reported, not failed: an incident-only series
(5xx, failed spans) is legitimately empty on a healthy stand.
"""
from __future__ import annotations
import argparse
import json
import sys
import time
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import obs # noqa: E402
def post(path: str, body: dict) -> dict:
request = urllib.request.Request(obs.GRAFANA + path, data=json.dumps(body).encode(), method="POST",
headers={"Authorization": obs._auth(), "Content-Type": "application/json"})
try:
with urllib.request.urlopen(request, timeout=60, context=obs.TLS) as response:
return json.loads(response.read())
except urllib.error.HTTPError as exc:
return json.loads(exc.read() or b"{}") | {"_status": exc.code}
def get(path: str) -> dict:
request = urllib.request.Request(obs.GRAFANA + path, headers={"Authorization": obs._auth()})
with urllib.request.urlopen(request, timeout=30, context=obs.TLS) as response:
return json.loads(response.read())
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--minutes", type=int, default=30)
parser.add_argument("--output")
args = parser.parse_args()
dashboard = get("/api/dashboards/uid/messenger-lab6")["dashboard"]
now = int(time.time() * 1000)
lines, failed = [], 0
lines.append(f"dashboard {dashboard['uid']} \"{dashboard['title']}\" (provisioned), window {args.minutes} min")
for panel in dashboard["panels"]:
if panel["type"] == "row":
lines.append(f"== {panel['title']}")
continue
results = []
for target in panel.get("targets", []):
query = {k: v for k, v in target.items()}
query.setdefault("datasource", panel["datasource"])
query["intervalMs"], query["maxDataPoints"] = 15000, 200
if query["datasource"]["type"] == "tempo":
query.update({"queryType": "traceql", "tableType": "traces"})
response = post("/api/ds/query", {"queries": [query], "from": str(now - args.minutes * 60000), "to": str(now)})
result = response.get("results", {}).get(target["refId"], {})
if "_status" in response or result.get("error"):
failed += 1
results.append(f"{target['refId']}: ERROR {result.get('error') or response.get('message')}")
continue
frames = result.get("frames", [])
rows = sum(len(f.get("data", {}).get("values", [[]])[0]) if f.get("data", {}).get("values") else 0 for f in frames)
results.append(f"{target['refId']}: {len(frames)} series/{rows} points" if rows else f"{target['refId']}: no data")
lines.append(f" [{panel['type']}] {panel['title']}: " + "; ".join(results))
lines.append(f"queries failed: {failed}")
text = "\n".join(lines)
print(text)
if args.output:
Path(args.output).write_text(text + "\n", encoding="utf-8", newline="\n")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env python3
"""Collect the lab 7 evidence on a RUNNING stand into evidence/ (README defense scenario steps 1-4).
python scripts/collect_evidence.py [--skip-student-tests]
Each step writes its own file and goes on after a failure; evidence/SUMMARY.md lists every step with
its command, exit code and file. Nothing secret is printed by the commands used (they print status
codes, key NAMES, PASS/FAIL). Long: start it detached on Windows (scripts/bg.ps1).
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import os
import ssl
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence"
PY = sys.executable
CA = str(ROOT / "secrets" / "pki" / "public-ca.crt")
WIN = os.name == "nt"
ENV = {**os.environ, "PYTHONUTF8": "1", "MSYS_NO_PATHCONV": "1", "CA_FILE": CA}
results: list[tuple[str, str, int, str, float]] = []
def hook(name: str) -> str:
return str(ROOT / "scripts" / (name + (".cmd" if WIN else ".sh")))
def sh(script: str) -> list[str]:
bash = os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe") if WIN else "sh"
return [bash, str(ROOT / "scripts" / script)]
def step(title: str, filename: str, *commands: list[str], timeout: float = 900, append: bool = False) -> int:
path = EVIDENCE / filename
path.parent.mkdir(parents=True, exist_ok=True)
started = time.monotonic()
code = 0
with path.open("a" if append else "w", encoding="utf-8", newline="\n") as out:
if not append:
out.write(f"# {title}\n# {dt.datetime.now(dt.timezone.utc).isoformat(timespec='seconds')}\n")
for command in commands:
out.write(f"\n$ {' '.join(command)}\n")
out.flush()
try:
result = subprocess.run(command, cwd=ROOT, env=ENV, capture_output=True, timeout=timeout)
text = (result.stdout + result.stderr).decode("utf-8", "replace").replace("\r\n", "\n")
out.write(text)
out.write(f"\n[exit {result.returncode}]\n")
code = code or result.returncode
except subprocess.TimeoutExpired:
out.write(f"\n[timeout after {timeout} s]\n")
code = code or 124
elapsed = time.monotonic() - started
results.append((title, " && ".join(" ".join(c) for c in commands), code, filename, elapsed))
print(f"{'PASS' if code == 0 else 'FAIL'} {title} ({elapsed:.0f} s) -> evidence/{filename}", flush=True)
return code
def compose_json(*args: str):
return json.loads(subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True,
env=ENV, check=True).stdout)
def stand_report() -> None:
"""Versions, images, per-service hardening/secrets/ports/limits, running state (no values)."""
config = compose_json("config", "--format", "json")
lines = ["# Стенд: версии, образы, hardening, секреты по сервисам (только имена)", ""]
commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
lines.append(f"commit: {commit}")
lines.append("docker: " + subprocess.run(["docker", "version", "--format", "{{.Server.Version}} ({{.Server.Os}}/{{.Server.Arch}})"],
capture_output=True, text=True).stdout.strip())
info = subprocess.run(["docker", "info", "--format", "{{.NCPU}} CPU, {{.MemTotal}} bytes RAM"], capture_output=True, text=True)
lines.append("docker VM: " + info.stdout.strip())
lines.append(f"compose project: {config.get('name')}")
lines.append("")
lines.append("| service | image | cap_drop | cap_add | no-new-priv | cpus | memory | published | secrets (names) |")
lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- |")
for name, svc in sorted(config["services"].items()):
limits = svc.get("deploy", {}).get("resources", {}).get("limits", {})
ports = [f"{p.get('host_ip')}:{p.get('published')}" for p in svc.get("ports", [])]
secrets = sorted(s["source"] for s in svc.get("secrets", []))
lines.append(f"| {name} | {svc.get('image')} | {svc.get('cap_drop')} | {svc.get('cap_add', '')} | "
f"{'no-new-privileges:true' in svc.get('security_opt', [])} | {limits.get('cpus')} | "
f"{int(limits.get('memory', 0)) // 2**20} MiB | {ports} | {', '.join(secrets)} |")
lines.append("")
ps = subprocess.run(["docker", "compose", "ps", "-a", "--format", "{{.Service}}\t{{.Status}}\t{{.Ports}}"],
cwd=ROOT, capture_output=True, text=True, env=ENV).stdout
lines += ["## docker compose ps -a", "", "```", ps.strip(), "```", ""]
users = []
for service in ("api", "relay", "worker", "lb", "openbao", "otel-collector", "prometheus", "grafana", "loki", "tempo"):
for cid in subprocess.run(["docker", "compose", "ps", "-q", service], cwd=ROOT, capture_output=True, text=True,
env=ENV).stdout.split():
uid = subprocess.run(["docker", "exec", cid, "id", "-u"], capture_output=True, text=True).stdout.strip()
caps = subprocess.run(["docker", "exec", cid, "sh", "-c", "grep CapEff /proc/1/status"], capture_output=True,
text=True).stdout.split()
alias = subprocess.run(["docker", "exec", cid, "cat", "/tmp/instance_id"], capture_output=True,
text=True, env=ENV).stdout.strip()
users.append(f"| {service} | {cid[:12]} | uid {uid or '? (no shell)'} | CapEff {caps[-1] if caps else '? (distroless)'} | {alias or '-'} |")
lines += ["## Пользователь и capabilities PID 1 (запущенные контейнеры)", "",
"| service | container | user | capabilities | X-Instance-Id alias |", "| --- | --- | --- | --- | --- |", *users, ""]
(EVIDENCE / "stand.md").write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
results.append(("стенд: версии/hardening/секреты по сервисам", "docker compose config/ps/inspect/exec", 0, "stand.md", 0))
print("PASS stand report -> evidence/stand.md", flush=True)
def failover_both() -> None:
"""test-failover until BOTH replicas have been the stopped one (README: последовательный отказ)."""
stopped: set[str] = set()
filename = "failover.txt"
(EVIDENCE / filename).write_text("# make test-failover: последовательный отказ реплик API\n", encoding="utf-8")
code = 0
for attempt in range(1, 6):
# The test stops the replica that served its first message. After a restore HAProxy's
# round robin is in the same position, so the same replica would be hit every time: shift it
# by `attempt - 1` extra requests through the LB (the public test itself is not touched).
for _ in range(attempt - 1):
try:
urllib.request.urlopen("https://localhost:8443/health/live", timeout=5,
context=ssl.create_default_context(cafile=CA)).read()
except OSError:
pass
before = {c for c in subprocess.run(["docker", "compose", "ps", "-q", "api"], cwd=ROOT, capture_output=True,
text=True, env=ENV).stdout.split()}
rc = step(f"failover run {attempt}", filename,
[PY, "tests/resilience.py", "--mode", "failover", "--action-script", hook("stop-one"), "--ca-file", CA],
["docker", "compose", "ps", "-a", "api"], append=True)
results.pop()
code = code or rc
after = {c for c in subprocess.run(["docker", "compose", "ps", "-q", "api"], cwd=ROOT, capture_output=True,
text=True, env=ENV).stdout.split()}
stopped |= {c[:12] for c in before - after}
step("restore", filename, sh("restore-api.sh"), [PY, "scripts/lbctl.py", "wait-up", "2"], append=True)
results.pop()
if len(stopped) >= 2:
break
with (EVIDENCE / filename).open("a", encoding="utf-8") as out:
out.write(f"\nstopped containers over the runs: {sorted(stopped)}\n")
results.append(("make test-failover x N, обе реплики по очереди", "tests/resilience.py --mode failover + restore",
0 if code == 0 and len(stopped) >= 2 else 1, filename, 0))
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--skip-student-tests", action="store_true")
parser.add_argument("--only-failover", action="store_true",
help="re-run only the failover series and update its row in SUMMARY.md")
args = parser.parse_args()
EVIDENCE.mkdir(exist_ok=True)
if args.only_failover:
failover_both()
title, command, code, filename, _ = results[-1]
summary = EVIDENCE / "SUMMARY.md"
row = f"| {title} | `{command}` | {code} | [{filename}]({filename}) | — |"
lines = [row if line.startswith(f"| {title} |") else line
for line in summary.read_text(encoding="utf-8").splitlines()]
summary.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
print(f"{'PASS' if code == 0 else 'FAIL'} failover series; SUMMARY.md updated")
return code
stand_report()
step("make check", "check.txt", [PY, "scripts/check_contract.py"])
step("make test (HTTPS, public CA)", "smoke.txt", [PY, "tests/smoke.py", "--base-url", "https://localhost:8443", "--ca-file", CA])
step("make test-security (недоверенный CA)", "test-security.txt", [PY, "tests/security.py", "--base-url", "https://localhost:8443", "--ca-file", CA])
step("mTLS LB->API: без cert / чужой CA / неверная identity / lb", "mtls-check.txt", sh("mtls_check.sh"))
step("OpenBao allow/deny, root credential отсутствует в app", "bao-check.txt", sh("bao_check.sh"),
[PY, "scripts/bao_operator.py", "status"])
step("make test-persistence (рестарт всех процессов, unseal)", "persistence.txt",
["docker", "compose", "ps", "-a"],
[PY, "tests/resilience.py", "--mode", "persistence", "--action-script", hook("restart"), "--ca-file", CA],
["docker", "compose", "ps", "-a"], timeout=600)
failover_both()
argon2_bench()
step("Телеметрия по mTLS: trace + logs", "trace-demo.txt", [PY, "scripts/trace_demo.py"])
step("Dashboard: все запросы через Grafana (HTTPS)", "dashboard-check.txt", [PY, "scripts/check_dashboard.py"])
if not args.skip_student_tests:
step("Свои тесты (unit + стенд, в т.ч. test_security.py)", "student-tests.txt",
[PY, "-m", "pytest", "student-tests", "-v", "-p", "no:cacheprovider", "--durations=15"], timeout=14400)
lines = ["# Сводка доказательств lab7", "", f"Собрано: {dt.datetime.now(dt.timezone.utc).isoformat(timespec='seconds')}", "",
"| Шаг | Команда | Код | Файл | Время, с |", "| --- | --- | --- | --- | --- |"]
for title, command, code, filename, elapsed in results:
lines.append(f"| {title} | `{command[:160]}` | {code} | [{filename}]({filename}) | {elapsed:.0f} |")
(EVIDENCE / "SUMMARY.md").write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
failed = [r for r in results if r[2] != 0]
print(f"done: {len(results) - len(failed)}/{len(results)} steps OK; evidence/SUMMARY.md")
return 1 if failed else 0
def argon2_bench() -> None:
"""bench/argon2_bench.py inside an API replica (its CPU/RAM limits) -> evidence/argon2/bench.json."""
target = EVIDENCE / "argon2" / "bench.json"
target.parent.mkdir(parents=True, exist_ok=True)
started = time.monotonic()
with (ROOT / "bench" / "argon2_bench.py").open("rb") as script:
result = subprocess.run(["docker", "compose", "exec", "-T", "api", "python", "-"], cwd=ROOT, env=ENV,
stdin=script, capture_output=True, timeout=900)
target.write_bytes(result.stdout)
results.append(("Argon2id: замер в контейнере API (1 CPU)", "docker compose exec -T api python - < bench/argon2_bench.py",
result.returncode, "argon2/bench.json", time.monotonic() - started))
print(f"{'PASS' if result.returncode == 0 else 'FAIL'} argon2 bench -> evidence/argon2/bench.json", flush=True)
if __name__ == "__main__":
sys.exit(main())
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""EXPLAIN (ANALYZE, BUFFERS) of the history query on >= 10 000 messages (level 4).
python scripts/explain_history.py --output evidence/explain-history.txt
Creates (once, idempotent) a synthetic chat with 20 000 messages plus 30 000 messages in
30 other chats, then explains the EXACT statements of src/messenger/repo.py:
1. first page (HISTORY_FIRST)
2. late page via cursor (HISTORY_AFTER) — generic plan forced, as a prepared statement
reused by the driver would get it
3. the rejected variant `($2 IS NULL OR (created_at, id) > ...)` — generic plan
4. the rejected OFFSET pagination for the same late page
Runs psql inside the postgres container; no database port is published.
"""
from __future__ import annotations
import argparse
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from messenger.repo import HISTORY_AFTER, HISTORY_FIRST # noqa: E402 (the app's real SQL)
CHAT = "00000000-0000-4000-8000-00000000e002"
USER = "00000000-0000-4000-8000-00000000e001"
TARGET = 20_000
LATE = 19_950 # cursor position: the 50 newest messages remain
SEED = f"""
\\set ON_ERROR_STOP on
BEGIN;
INSERT INTO users (id, username, display_name, password_hash)
VALUES ('{USER}', 'explain_seed', convert_to('Explain seed', 'UTF8'), 'not-a-login') ON CONFLICT DO NOTHING;
INSERT INTO chats (id, title, created_by, created_at)
SELECT ('00000000-0000-4000-8000-0000000' || lpad(to_hex(n), 5, '0'))::uuid, convert_to('explain ' || n, 'UTF8'),
'{USER}', timestamptz '2026-01-01 00:00:00+00'
FROM generate_series(57346::int, 57376::int) AS n -- e002 .. e020: target + 30 noise chats
ON CONFLICT DO NOTHING;
INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
SELECT id, '{USER}', 0, created_at FROM chats WHERE created_by = '{USER}' ON CONFLICT DO NOTHING;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '{CHAT}', '{USER}', convert_to('synthetic message ' || g, 'UTF8'),
timestamptz '2026-01-01 00:00:00+00' + g * interval '1 second'
FROM generate_series(1::int, {TARGET}::int) AS g
WHERE NOT EXISTS (SELECT 1 FROM messages WHERE chat_id = '{CHAT}');
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), c.id, '{USER}', convert_to('noise ' || g, 'UTF8'),
timestamptz '2026-01-01 00:00:00+00' + g * interval '1 second'
FROM chats c CROSS JOIN generate_series(1::int, 1000::int) AS g
WHERE c.created_by = '{USER}' AND c.id <> '{CHAT}'
AND NOT EXISTS (SELECT 1 FROM messages m WHERE m.chat_id = c.id);
COMMIT;
ANALYZE messages;
"""
def pg(sql_param: str) -> str:
"""Turn psycopg %s placeholders into $1..$n for a PREPARE statement."""
parts = sql_param.split("%s")
return "".join(p + (f"${i + 1}" if i < len(parts) - 1 else "") for i, p in enumerate(parts))
EXPLAIN = f"""
\\set ON_ERROR_STOP on
\\pset pager off
SELECT count(*) AS messages_total, count(*) FILTER (WHERE chat_id = '{CHAT}') AS messages_in_target_chat FROM messages;
SELECT created_at AS cur_ts, id AS cur_id FROM messages WHERE chat_id = '{CHAT}'
ORDER BY created_at, id OFFSET {LATE - 1} LIMIT 1 \\gset
SET plan_cache_mode = force_generic_plan;
PREPARE first_page(uuid, int) AS {pg(HISTORY_FIRST)};
PREPARE after_page(uuid, timestamptz, uuid, int) AS {pg(HISTORY_AFTER)};
PREPARE or_page(uuid, timestamptz, uuid, int) AS
SELECT id, sender_id, text, created_at FROM messages
WHERE chat_id = $1 AND ($2 IS NULL OR (created_at, id) > ($2, $3)) ORDER BY created_at, id LIMIT $4;
PREPARE offset_page(uuid, int, int) AS
SELECT id, sender_id, text, created_at FROM messages WHERE chat_id = $1 ORDER BY created_at, id OFFSET $2 LIMIT $3;
\\echo '=== 1. first page, app query HISTORY_FIRST, generic plan'
EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE first_page('{CHAT}', 51);
\\echo '=== 2. late page (cursor at {LATE}), app query HISTORY_AFTER, generic plan'
EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE after_page('{CHAT}', :'cur_ts', :'cur_id', 51);
\\echo '=== 3. REJECTED: one query with ($2 IS NULL OR ...), same late page, generic plan'
EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE or_page('{CHAT}', :'cur_ts', :'cur_id', 51);
\\echo '=== 4. REJECTED: OFFSET pagination, same late page'
EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE offset_page('{CHAT}', {LATE}, 51);
"""
def psql(script: str) -> str:
result = subprocess.run(
["docker", "compose", "exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger", "-X", "-q", "-f", "-"],
cwd=ROOT, input=script, capture_output=True, text=True, encoding="utf-8", check=True)
return result.stdout
def run() -> str:
psql(SEED)
return psql(EXPLAIN)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--output", default=None)
args = parser.parse_args()
text = run()
print(text)
if args.output:
Path(args.output).write_text(text, encoding="utf-8", newline="\n")
return 0
if __name__ == "__main__":
sys.exit(main())
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Local PKI of the lab 7 stand: two CAs and one leaf certificate per service, in ./secrets/pki.
.venv/Scripts/python scripts/init_pki.py (also called by scripts/init_secrets.py)
Needs the `cryptography` package (requirements-test.txt). Idempotent: existing files are kept,
so re-running never replaces a CA that already signed the running stand. Prints file names
only, never key material. ./secrets is git-ignored and docker-ignored; nothing here is committed
or baked into an image. Delete ./secrets/pki to start a new PKI (then recreate the containers).
Two trust domains (contracts/trust-matrix.md):
public-ca signs ONLY what people connect to: the HTTPS ingress (HAProxy, :8443) and the
Grafana UI, SAN localhost / 127.0.0.1 / ::1. Its certificate is the CA_FILE of the
public tests; it may be given to anyone. It is trusted by NO service.
internal-ca signs the service identities. SAN = the compose service name (the DNS name the
peer dials), EKU serverAuth and/or clientAuth by role. Services trust only it.
The CA private keys (*-ca.key) are mounted into no container: only this script uses them.
Test-only material (never trusted by the stand): `foreign-ca` and a client certificate signed by
it with the allowed SAN `lb` - proves that the right name from a wrong CA is refused.
"""
from __future__ import annotations
import datetime as dt
import ipaddress
import os
import sys
from pathlib import Path
try:
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
except ImportError: # pragma: no cover - message for a missing venv
sys.exit("init_pki.py needs `cryptography`: python -m venv .venv && "
".venv/Scripts/python -m pip install -r requirements-test.txt")
ROOT = Path(__file__).resolve().parents[1]
PKI = ROOT / "secrets" / "pki"
CA_DAYS = 5 * 365
LEAF_DAYS = 365
SERVER, CLIENT = ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH
LOCAL = ["localhost", "127.0.0.1"] # only for services whose own healthcheck/CLI dials loopback over TLS
# name -> (CA, extra SANs besides the name itself, EKUs). The name is the identity: CN and SAN.
LEAVES = {
# Public trust domain: what the user's client verifies (hostname localhost, both loopbacks).
"ingress": ("public-ca", ["127.0.0.1", "::1"], [SERVER], "localhost"),
"grafana-ui": ("public-ca", ["127.0.0.1", "::1"], [SERVER], "localhost"),
# Internal trust domain.
"lb": ("internal-ca", [], [CLIENT], None), # client of every API replica
"api": ("internal-ca", [], [SERVER, CLIENT], None), # server for lb, client of collector
"relay": ("internal-ca", [], [CLIENT], None),
"worker": ("internal-ca", [], [CLIENT], None),
"postgres": ("internal-ca", LOCAL, [SERVER], None),
"valkey": ("internal-ca", LOCAL, [SERVER], None),
"s3": ("internal-ca", LOCAL, [SERVER], None),
"broker": ("internal-ca", LOCAL, [SERVER], None),
"otel-collector": ("internal-ca", [], [SERVER, CLIENT], None), # server for apps, client of backends
"prometheus": ("internal-ca", LOCAL, [SERVER, CLIENT], None), # client: scrapes loki/tempo
"loki": ("internal-ca", LOCAL, [SERVER], None),
"tempo": ("internal-ca", LOCAL, [SERVER], None),
"grafana": ("internal-ca", [], [CLIENT], None), # client of the three datasources
"openbao": ("internal-ca", LOCAL, [SERVER], None),
# Test only: right SAN, wrong CA.
"foreign-lb": ("foreign-ca", [], [CLIENT], "lb"),
}
CAS = {"public-ca": "MTUSI lab7 public CA", "internal-ca": "MTUSI lab7 internal CA",
"foreign-ca": "Foreign CA (test only, trusted by nobody)"}
def now() -> dt.datetime:
return dt.datetime.now(dt.timezone.utc)
def save(path: Path, data: bytes) -> None:
path.write_bytes(data) # bytes: PEM keeps LF on Windows too
# Readable by the unprivileged container users through the bind mount (postgres copies its
# key to a 0600 file at start). The folder ./secrets itself is 0700 for the host user.
os.chmod(path, 0o644)
print(f"created secrets/pki/{path.name}")
def pem_key(key) -> bytes:
return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
serialization.NoEncryption())
def load(name: str):
cert = x509.load_pem_x509_certificate((PKI / f"{name}.crt").read_bytes())
key = serialization.load_pem_private_key((PKI / f"{name}.key").read_bytes(), None)
return cert, key
def make_ca(name: str) -> None:
if (PKI / f"{name}.crt").exists():
print(f"keep secrets/pki/{name}.crt")
return
key = ec.generate_private_key(ec.SECP256R1())
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, CAS[name])])
cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(subject)
.public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now() - dt.timedelta(minutes=5)).not_valid_after(now() + dt.timedelta(days=CA_DAYS))
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
.add_extension(x509.KeyUsage(digital_signature=False, content_commitment=False, key_encipherment=False,
data_encipherment=False, key_agreement=False, key_cert_sign=True,
crl_sign=True, encipher_only=False, decipher_only=False), critical=True)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False)
.sign(key, hashes.SHA256()))
save(PKI / f"{name}.key", pem_key(key))
save(PKI / f"{name}.crt", cert.public_bytes(serialization.Encoding.PEM))
def san_entry(value: str) -> x509.GeneralName:
try:
return x509.IPAddress(ipaddress.ip_address(value))
except ValueError:
return x509.DNSName(value)
def make_leaf(name: str, ca_name: str, extra: list[str], ekus: list, dns_name: str | None) -> None:
if (PKI / f"{name}.crt").exists():
print(f"keep secrets/pki/{name}.crt")
return
ca_cert, ca_key = load(ca_name)
identity = dns_name or name
key = ec.generate_private_key(ec.SECP256R1())
sans = [san_entry(v) for v in dict.fromkeys([identity, *extra])]
cert = (x509.CertificateBuilder()
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, identity)]))
.issuer_name(ca_cert.subject).public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now() - dt.timedelta(minutes=5)).not_valid_after(now() + dt.timedelta(days=LEAF_DAYS))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.KeyUsage(digital_signature=True, content_commitment=False, key_encipherment=False,
data_encipherment=False, key_agreement=True, key_cert_sign=False,
crl_sign=False, encipher_only=False, decipher_only=False), critical=True)
.add_extension(x509.ExtendedKeyUsage(ekus), critical=False)
.add_extension(x509.SubjectAlternativeName(sans), critical=False)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False)
.sign(ca_key, hashes.SHA256()))
cert_pem = cert.public_bytes(serialization.Encoding.PEM)
save(PKI / f"{name}.key", pem_key(key))
save(PKI / f"{name}.crt", cert_pem)
def bundle(name: str) -> None:
"""HAProxy wants certificate + key in one PEM file."""
target = PKI / f"{name}.pem"
if target.exists():
print(f"keep secrets/pki/{target.name}")
return
save(target, (PKI / f"{name}.crt").read_bytes() + (PKI / f"{name}.key").read_bytes())
def main() -> int:
PKI.mkdir(parents=True, exist_ok=True)
os.chmod(PKI.parent, 0o700)
for ca in CAS:
make_ca(ca)
for name, (ca, extra, ekus, dns_name) in LEAVES.items():
make_leaf(name, ca, extra, ekus, dns_name)
bundle("ingress") # HAProxy :8443 server certificate
bundle("lb") # HAProxy client certificate towards the API replicas
print("CA_FILE for the public tests:", (PKI / "public-ca.crt").as_posix())
return 0
if __name__ == "__main__":
sys.exit(main())
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Create local synthetic credentials and the PKI of the stand in ./secrets (ignored by Git).
.venv/Scripts/python scripts/init_secrets.py (Linux/macOS: .venv/bin/python)
Idempotent: existing files are kept, so re-running never changes passwords of a
database that already has data. Prints only file names, never values.
Delete ./secrets together with the volumes (`docker compose down -v`) to start over.
Lab 7: one credential per service and role (contracts/trust-matrix.md):
PostgreSQL postgres (superuser: initdb + operator via `docker compose exec`, never over the
network), messenger_migrate (owner of the schema), messenger_api / _relay / _worker
(GRANT only what the service does, migrations/0007_least_privilege.sql),
messenger_jobctl / _auditor (operator tools). Every URL has sslmode=verify-full.
Valkey ACL user `api` (session:* and ratelimit:* keys, a few commands), `default` user off.
S3 admin (s3-init only) / api / worker / auditor key pairs.
RabbitMQ relay (publish only) / worker (consume only), amqps:// (TLS 5671).
The application services do not mount these files from lab 7 step 5 on: they read their own
values from OpenBao (scripts/bao_operator.py copies them there), see docs/OPERATOR.md.
"""
from __future__ import annotations
import base64
import hashlib
import json
import os
import secrets
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / "secrets"
CA = "/run/secrets/internal-ca.crt" # path INSIDE the containers
DB_ROLES = ("migrate", "api", "relay", "worker", "jobctl", "auditor")
def write(name: str, value: str) -> None:
path = SECRETS / name
if path.exists():
print(f"keep secrets/{name}")
return
path.write_text(value + "\n", encoding="utf-8", newline="\n")
# Readable by the container users (postgres, valkey, seaweedfs, rabbitmq, app uid 10001)
# through the compose bind mount; the folder ./secrets itself is 0700 for the host user.
os.chmod(path, 0o644)
print(f"created secrets/{name}")
def read(name: str) -> str:
return (SECRETS / name).read_text(encoding="utf-8").strip()
def rabbit_hash(password: str) -> str:
"""RabbitMQ `rabbit_password_hashing_sha256`: base64(salt + sha256(salt + password)), 4-byte salt.
The broker stores and compares only this hash; the plain password is in the client's URL."""
salt = secrets.token_bytes(4)
return base64.b64encode(salt + hashlib.sha256(salt + password.encode("utf-8")).digest()).decode("ascii")
def main() -> int:
SECRETS.mkdir(exist_ok=True)
os.chmod(SECRETS, 0o700)
# PostgreSQL: superuser (no network login, pg_hba) + one login role per service.
write("postgres_password", secrets.token_urlsafe(24)) # [A-Za-z0-9_-]: safe inside URLs
for role in DB_ROLES:
write(f"pg_{role}_password", secrets.token_urlsafe(24))
write(f"database_url_{role}", f"postgresql://messenger_{role}:{read(f'pg_{role}_password')}@postgres:5432/"
f"messenger?sslmode=verify-full&sslrootcert={CA}")
# Valkey: ACL user `api` (infra/valkey/start.sh); TLS only (rediss).
write("valkey_api_password", secrets.token_urlsafe(24))
write("cache_url", f"rediss://api:{read('valkey_api_password')}@valkey:6379/0")
# S3 key pairs (SeaweedFS identities, infra/seaweedfs/start.sh): admin = bucket bootstrap only;
# api = Write staging + Read final; worker = Read/Write both; auditor = Read + List (no Write).
for who in ("admin", "api", "worker", "auditor"):
write(f"s3_{who}_access_key_id", "AK" + secrets.token_hex(9).upper())
write(f"s3_{who}_secret_access_key", secrets.token_hex(20))
# RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume the jobs
# queue; neither may declare/delete anything (configure "^$").
write("rabbitmq_relay_password", secrets.token_urlsafe(24))
write("rabbitmq_worker_password", secrets.token_urlsafe(24))
users = {
"users": [{"name": who, "password_hash": rabbit_hash(read(f"rabbitmq_{who}_password")),
"hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []} for who in ("relay", "worker")],
"permissions": [
{"user": "relay", "vhost": "/", "configure": "^$", "write": "^messenger\\.jobs$", "read": "^$"},
{"user": "worker", "vhost": "/", "configure": "^$", "write": "^$", "read": "^messenger\\.attachment-jobs$"},
],
}
write("rabbitmq_users.json", json.dumps(users, indent=1))
for who in ("relay", "worker"):
# AMQP heartbeat 10 s: a frozen client loses its connection after ~2 missed heartbeats, and
# the broker returns its unacked messages to the queue for the other consumers.
write(f"broker_url_{who}", f"amqps://{who}:{read(f'rabbitmq_{who}_password')}@broker:5671/?heartbeat=10")
# Grafana admin (UI on https://localhost:3000 and the evidence scripts, via its datasource proxy).
write("grafana_admin_password", secrets.token_urlsafe(18))
# Lab 7: local PKI (two CAs + service certificates) in ./secrets/pki.
sys.path.insert(0, str(Path(__file__).resolve().parent))
import init_pki
return init_pki.main()
if __name__ == "__main__":
sys.exit(main())
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""What the load balancer thinks right now, mapped to real containers.
python scripts/lbctl.py status # table: HAProxy slot, IP, UP/DOWN/MAINT, container, X-Instance-Id
python scripts/lbctl.py wait-up 2 # wait until exactly 2 API replicas are UP in HAProxy
python scripts/lbctl.py replicas # api containers of this compose project: name, hostname, state
Reads HAProxy's runtime API (`show servers state api`) through `docker compose exec lb socat`,
so no admin port is published. Container hostname = X-Instance-Id of that replica.
Prints no secrets. Used by student-tests and bench scripts as a library as well.
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
# srv_op_state of HAProxy (src/server.h): 0 stopped, 1 starting, 2 running, 3 stopping.
OP_STATE = {0: "DOWN", 1: "STARTING", 2: "UP", 3: "STOPPING"}
ADMIN_RMAINT = 0x20 # slot without a resolved address (no running container behind it)
def run(*args: str, timeout: float = 60) -> str:
result = subprocess.run(list(args), cwd=ROOT, capture_output=True, text=True, encoding="utf-8",
timeout=timeout)
if result.returncode != 0:
raise RuntimeError(f"{' '.join(args[:3])}... failed: {result.stderr.strip()[:300]}")
return result.stdout
def instance_alias(container_id: str) -> str | None:
"""X-Instance-Id of the process running in the container (lab 7: random alias, not the hostname)."""
result = subprocess.run(["docker", "exec", container_id, "cat", "/tmp/instance_id"], capture_output=True,
text=True, timeout=30, env={**os.environ, "MSYS_NO_PATHCONV": "1"})
return (result.stdout.strip() or None) if result.returncode == 0 else None
def replicas(all_states: bool = True) -> list[dict]:
"""API containers of this compose project (running and stopped)."""
ids = run("docker", "compose", "ps", "-q", *(["-a"] if all_states else []), "api").split()
if not ids:
return []
data = json.loads(run("docker", "inspect", *ids))
result = []
for item in data:
networks = item["NetworkSettings"]["Networks"] or {}
result.append({
"id": item["Id"][:12],
"name": item["Name"].lstrip("/"),
"hostname": item["Config"]["Hostname"],
# Lab 7: X-Instance-Id is a random alias the process writes to /tmp/instance_id.
"instance": instance_alias(item["Id"][:12]) if item["State"]["Status"] == "running" else None,
"state": item["State"]["Status"],
"health": (item["State"].get("Health") or {}).get("Status", "-"),
"exit_code": item["State"]["ExitCode"],
"started_at": item["State"]["StartedAt"],
"pid": item["State"]["Pid"],
"ips": sorted(n["IPAddress"] for n in networks.values() if n.get("IPAddress")),
# compose network name without the project prefix -> IP, e.g. {"edge": ..., "data": ...}
"networks": {name.split("_", 1)[-1]: n["IPAddress"] for name, n in networks.items() if n.get("IPAddress")},
})
return sorted(result, key=lambda r: r["name"])
def lb_servers() -> list[dict]:
raw = run("docker", "compose", "exec", "-T", "lb", "sh", "-c",
'echo "show servers state api" | socat stdio /var/lib/haproxy/admin.sock')
by_ip = {ip: r for r in replicas() for ip in r["ips"]}
servers = []
for line in raw.splitlines():
parts = line.split()
if len(parts) < 7 or not parts[0].isdigit():
continue
name, addr, op, admin = parts[3], parts[4], int(parts[5]), int(parts[6])
if admin & ADMIN_RMAINT or addr == "-":
state = "MAINT"
else:
state = OP_STATE.get(op, str(op))
container = by_ip.get(addr)
servers.append({"slot": name, "addr": addr, "state": state,
"container": container["name"] if container else None,
"instance_id": container["instance"] if container else None})
return servers
def up_instances() -> set[str]:
return {s["instance_id"] or s["addr"] for s in lb_servers() if s["state"] == "UP"}
def wait_up(count: int, timeout: float = 60) -> float:
"""Seconds until exactly `count` servers are UP (raises TimeoutError otherwise)."""
started = time.monotonic()
while True:
try:
if len(up_instances()) == count:
return time.monotonic() - started
except RuntimeError:
pass # lb restarting
if time.monotonic() - started > timeout:
raise TimeoutError(f"HAProxy does not report {count} UP API replicas after {timeout:.0f} s")
time.sleep(0.25)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("status")
sub.add_parser("replicas")
wait = sub.add_parser("wait-up")
wait.add_argument("count", type=int)
wait.add_argument("--timeout", type=float, default=60)
args = parser.parse_args()
if args.command == "status":
for s in lb_servers():
if s["state"] != "MAINT" or s["container"]:
print(f"{s['slot']:6} {s['addr']:15} {s['state']:8} {s['container'] or '-':24} X-Instance-Id={s['instance_id'] or '-'}")
print(f"(other slots: MAINT, no container)")
elif args.command == "replicas":
for r in replicas():
print(f"{r['name']:24} X-Instance-Id={r['hostname']} {r['state']:8} health={r['health']:9} "
f"pid={r['pid']} started={r['started_at'][:23]} ip={','.join(r['ips']) or '-'}")
else:
took = wait_up(args.count, args.timeout)
print(f"{args.count} API replica(s) UP in HAProxy after {took:.1f} s: {sorted(up_instances())}")
return 0
if __name__ == "__main__":
sys.exit(main())
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper: runs scripts\mtls_check.sh (LB -> API mTLS proof) with Git Bash.
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0mtls_check.sh"
exit /b %ERRORLEVEL%
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Negative/positive proof of the LB -> API mTLS, against EVERY API replica directly (no LB).
Runs inside the compose network `edge` (the LB's network), as the tools service `mtls-check`:
docker compose run --rm mtls-check (wrappers: make mtls-check, scripts/mtls_check.cmd)
For every IP of the DNS name `api` (one per running replica) it opens fresh connections that
always verify the SERVER (internal CA, hostname `api`) and present, as the client:
1. no certificate -> refused in the TLS handshake
2. certificate of a foreign CA, SAN `lb` (right name) -> refused in the TLS handshake (unknown CA)
3. certificate of OUR CA, SAN `worker` (wrong role) -> handshake OK, connection closed by the
API before any HTTP response (allowlist)
4. certificate of OUR CA, SAN `lb` (the LB identity) -> HTTP 200 from GET /health/ready
plus two bypass probes: plaintext HTTP to the mTLS port and the loopback health port from another
container (both must fail). Case 4 on the same address proves the refusals are not "network down".
Which check refused: the API logs `mtls_identity_rejected` (with the client SAN) ONLY for the
allowlist (case 3); cases 1-2 never reach the application - the TLS layer drops them. The wrapper
scripts/mtls_check.sh prints those log lines after the run.
Exit 0 only if every expectation holds. Prints no key material. Test-only: this container mounts the
LB's client key (to prove the positive case) and the worker's certificate (a trusted but wrong role).
"""
from __future__ import annotations
import os
import socket
import ssl
import sys
PORT = int(os.environ.get("API_PORT", "8443"))
HEALTH_PORT = int(os.environ.get("API_HEALTH_PORT", "8081"))
CA = os.environ.get("INTERNAL_CA", "/run/secrets/internal-ca.crt")
CERTS = {
"none": None,
"foreign-ca SAN=lb": ("/run/secrets/foreign-lb.crt", "/run/secrets/foreign-lb.key"),
"internal-ca SAN=worker": ("/run/secrets/worker.crt", "/run/secrets/worker.key"),
"internal-ca SAN=lb": ("/run/secrets/lb.crt", "/run/secrets/lb.key"),
}
EXPECT = {"none": "refused", "foreign-ca SAN=lb": "refused", "internal-ca SAN=worker": "refused",
"internal-ca SAN=lb": "200"}
REQUEST = b"GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n"
def attempt(ip: str, cert, version: ssl.TLSVersion) -> tuple[str, str]:
"""(outcome, detail): outcome is the HTTP status code, or 'refused'/'error'.
TLS 1.3: the client finishes its side of the handshake BEFORE the server has checked the client
certificate, so a refusal shows up as an alert/EOF on the first read. TLS 1.2: the server
checks the client certificate inside the handshake, so the alert names the reason
(certificate required / unknown CA). Both versions must refuse; the identity allowlist always
acts after a successful handshake (the chain is fine there).
"""
ctx = ssl.create_default_context(cafile=CA) # server verification is ALWAYS on
ctx.check_hostname = True
ctx.minimum_version = ctx.maximum_version = version
if cert:
ctx.load_cert_chain(*cert)
stage = "tcp"
try:
with socket.create_connection((ip, PORT), timeout=5) as raw:
stage = "handshake"
with ctx.wrap_socket(raw, server_hostname="api") as tls:
stage = "http"
tls.sendall(REQUEST)
data = tls.recv(4096)
if not data:
return "refused", "closed by the server after the handshake (no HTTP response)"
status = data.split(b" ", 2)[1].decode("ascii", "replace")
return status, f"HTTP {status}; server cert SAN api verified"
except ssl.SSLCertVerificationError as exc:
return "error", f"SERVER certificate not trusted: {exc.verify_message}"
except ssl.SSLError as exc:
if exc.reason == "UNEXPECTED_EOF_WHILE_READING":
return "refused", f"server closed the connection during the {stage} (no HTTP response)"
return "refused", f"TLS alert at {stage}: {exc.reason or exc}"
except (ConnectionResetError, BrokenPipeError, ConnectionAbortedError) as exc:
return "refused", f"connection reset at {stage}: {type(exc).__name__}"
except OSError as exc:
return "error", f"{stage}: {type(exc).__name__}: {exc}" # unreachable etc. is NOT a refusal
def plaintext(ip: str, port: int) -> tuple[bool, str]:
"""True if a plaintext HTTP request got an HTTP answer (= a bypass)."""
try:
with socket.create_connection((ip, port), timeout=3) as s:
s.sendall(REQUEST)
data = s.recv(64)
if data.startswith(b"HTTP/"):
return True, "answered plaintext HTTP: " + data.split(b"\r\n")[0].decode("latin-1")
return False, "no HTTP answer (TLS-only listener)"
except OSError as exc:
return False, f"{type(exc).__name__}"
def main() -> int:
ips = sorted({info[4][0] for info in socket.getaddrinfo("api", PORT, socket.AF_INET, socket.SOCK_STREAM)})
print(f"API replicas behind DNS name `api`: {len(ips)}")
failures = 0
for ip in ips:
print(f"\nreplica {ip}:{PORT}")
for version in (ssl.TLSVersion.TLSv1_3, ssl.TLSVersion.TLSv1_2):
tag = "1.3" if version == ssl.TLSVersion.TLSv1_3 else "1.2"
for label, cert in CERTS.items():
outcome, detail = attempt(ip, cert, version)
good = outcome == EXPECT[label]
failures += not good
print(f" {'PASS' if good else 'FAIL'} TLS {tag} client cert {label:24s} -> {outcome:8s} {detail}")
for port, what in ((PORT, "plaintext HTTP to the mTLS port"), (HEALTH_PORT, "loopback health port from outside")):
bypass, detail = plaintext(ip, port)
failures += bypass
print(f" {'FAIL' if bypass else 'PASS'} {what:51s} -> {detail}")
if not ips:
failures += 1
print(f"\n{'PASS' if failures == 0 else 'FAIL'}: mTLS LB->API, {len(ips)} replica(s), {failures} failure(s)")
return 0 if failures == 0 else 1
if __name__ == "__main__":
sys.exit(main())
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# LB -> API mTLS proof: scripts/mtls_check.py in the `edge` network + the API's own record of the
# identity refusals (event mtls_identity_rejected, SAN of the refused client) since the run started.
set -eu
cd "$(dirname "$0")/.."
since="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
rc=0
docker compose run --rm mtls-check 2>/dev/null || rc=$?
echo
echo "API log since $since, identity allowlist refusals (cases 1-2 are dropped by TLS and never logged):"
docker compose logs --no-log-prefix --since "$since" api 2>/dev/null | grep mtls_identity_rejected || echo " (none)"
exit "$rc"
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/env python3
"""Read the stored observations (Prometheus, Loki, Tempo) through Grafana's datasource proxy.
Only Grafana is published (127.0.0.1:3000); the stores stay on the internal network. The admin
password comes from secrets/grafana_admin_password and is never printed.
python scripts/obs.py promql 'sum(rate(http_server_request_duration_seconds_count[1m]))'
python scripts/obs.py alerts # Prometheus alerts: state, since
python scripts/obs.py trace <trace_id> # span tree of one trace (Tempo)
python scripts/obs.py logs <trace_id> # log records of one trace (Loki)
python scripts/obs.py search '{ span.messenger.job.outcome = "retry" }' # TraceQL
Used as a library by student-tests/test_observability.py and bench/*.py.
"""
from __future__ import annotations
import base64
import json
import os
import ssl
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
GRAFANA = os.environ.get("GRAFANA_URL", "https://localhost:3000").rstrip("/")
# Lab 7: Grafana is HTTPS with a public-CA certificate (SAN localhost); verified, never skipped.
TLS = ssl.create_default_context(cafile=os.environ.get("CA_FILE") or str(ROOT / "secrets" / "pki" / "public-ca.crt"))
def _auth() -> str:
password = os.environ.get("GRAFANA_PASSWORD") or (ROOT / "secrets" / "grafana_admin_password").read_text(
encoding="utf-8").strip()
return "Basic " + base64.b64encode(f"admin:{password}".encode()).decode()
def get(uid: str, path: str, params: dict | None = None, timeout: float = 30) -> dict:
url = f"{GRAFANA}/api/datasources/proxy/uid/{uid}/{path.lstrip('/')}"
if params:
url += "?" + urllib.parse.urlencode(params)
request = urllib.request.Request(url, headers={"Authorization": _auth(), "Accept": "application/json"})
with urllib.request.urlopen(request, timeout=timeout, context=TLS) as response:
return json.loads(response.read())
# ----------------------------------------------------------------------------- Prometheus
def promql(expr: str, at: float | None = None) -> list[dict]:
params = {"query": expr}
if at is not None:
params["time"] = f"{at:.3f}"
return get("prometheus", "api/v1/query", params)["data"]["result"]
def scalar(expr: str, default: float | None = None) -> float | None:
"""Single value of an instant query (first series), or `default` when there is none."""
result = promql(expr)
if not result:
return default
value = float(result[0]["value"][1])
return default if value != value else value # NaN -> default
def series(expr: str, start: float, end: float, step: float = 5) -> list[dict]:
return get("prometheus", "api/v1/query_range",
{"query": expr, "start": f"{start:.3f}", "end": f"{end:.3f}", "step": str(step)})["data"]["result"]
def alerts() -> list[dict]:
"""Active alerts (pending/firing) of Prometheus: [{name, state, activeAt, value, labels}]."""
data = get("prometheus", "api/v1/alerts")["data"]["alerts"]
return [{"name": a["labels"].get("alertname"), "state": a["state"], "activeAt": a.get("activeAt"),
"value": a.get("value"), "labels": a["labels"]} for a in data]
def alert_state(name: str) -> str:
"""inactive | pending | firing (highest of the alert's series)."""
states = {a["state"] for a in alerts() if a["name"] == name}
return "firing" if "firing" in states else "pending" if "pending" in states else "inactive"
# ----------------------------------------------------------------------------- Tempo
def trace_spans(trace_id: str) -> list[dict]:
"""Flat list of spans: {service, name, kind, span_id, parent_id, start, end, duration_ms, status, attrs}."""
data = get("tempo", f"api/v2/traces/{trace_id}")
spans = []
for rs in data.get("trace", data).get("resourceSpans", []):
rattrs = _attrs(rs.get("resource", {}).get("attributes", []))
for ss in rs.get("scopeSpans", []):
for sp in ss.get("spans", []):
start, end = int(sp["startTimeUnixNano"]), int(sp["endTimeUnixNano"])
spans.append({
"service": rattrs.get("service.name"), "instance": rattrs.get("service.instance.id"),
"name": sp["name"], "kind": sp.get("kind", "").replace("SPAN_KIND_", ""),
"span_id": _hex(sp.get("spanId", "")), "parent_id": _hex(sp.get("parentSpanId", "")),
"start": start, "end": end, "duration_ms": (end - start) / 1e6,
"status": sp.get("status", {}).get("code", "STATUS_CODE_UNSET").replace("STATUS_CODE_", ""),
"attrs": _attrs(sp.get("attributes", [])),
})
return sorted(spans, key=lambda s: s["start"])
def wait_trace(trace_id: str, predicate, timeout: float = 60) -> list[dict]:
"""Poll Tempo until predicate(spans) is true (spans arrive within a few seconds)."""
deadline = time.monotonic() + timeout
spans: list[dict] = []
while time.monotonic() < deadline:
try:
spans = trace_spans(trace_id)
if spans and predicate(spans):
return spans
except urllib.error.HTTPError as exc:
if exc.code != 404:
raise
time.sleep(2)
raise AssertionError(f"trace {trace_id}: condition not met within {timeout} s; {len(spans)} spans")
def search(traceql: str, minutes: int = 60, limit: int = 20) -> list[dict]:
end = int(time.time())
return get("tempo", "api/search", {"q": traceql, "start": end - minutes * 60, "end": end,
"limit": limit}).get("traces", [])
def _hex(value: str) -> str:
if not value:
return ""
if all(c in "0123456789abcdef" for c in value.lower()) and len(value) in (16, 32):
return value.lower()
return base64.b64decode(value).hex() # OTLP JSON may carry ids base64-encoded
def _attrs(items: list) -> dict:
out = {}
for item in items:
value = item.get("value", {})
out[item["key"]] = next(iter(value.values())) if value else None
return out
def tree(spans: list[dict]) -> str:
"""Indented text tree (parent -> children), times relative to the first span."""
by_parent: dict[str, list[dict]] = {}
ids = {s["span_id"] for s in spans}
for s in spans:
by_parent.setdefault(s["parent_id"] if s["parent_id"] in ids else "", []).append(s)
t0 = spans[0]["start"] if spans else 0
lines: list[str] = []
def walk(parent: str, depth: int) -> None:
for s in by_parent.get(parent, []):
extra = {k: v for k, v in s["attrs"].items() if k in (
"http.route", "http.response.status_code", "messenger.job.attempt", "messenger.job.outcome",
"messenger.job.error_code", "db.client.connection.wait_time_ms", "error.type")}
lines.append(f"{' ' * depth}+{(s['start'] - t0) / 1e6:9.1f} ms {s['duration_ms']:8.1f} ms "
f"[{s['service']}] {s['kind']:<8} {s['name']} {s['status'] if s['status'] != 'UNSET' else ''} "
f"{json.dumps(extra, ensure_ascii=False) if extra else ''}".rstrip())
walk(s["span_id"], depth + 1)
walk("", 0)
return "\n".join(lines)
# ----------------------------------------------------------------------------- Loki
def logs(query: str, minutes: int = 60, limit: int = 200) -> list[dict]:
"""Records of a LogQL query: {ts, service, line, metadata} (oldest first)."""
end = time.time_ns()
data = get("loki", "loki/api/v1/query_range", {"query": query, "start": end - minutes * 60 * 10**9, "end": end,
"limit": limit, "direction": "backward"})
out = []
for stream in data["data"]["result"]:
labels = stream["stream"]
for value in stream["values"]:
ts, line = value[0], value[1]
meta = value[2].get("structuredMetadata", {}) if len(value) > 2 and isinstance(value[2], dict) else {}
out.append({"ts": int(ts), "service": labels.get("service_name"), "line": line,
"metadata": {**{k: v for k, v in labels.items()}, **meta}})
return sorted(out, key=lambda r: r["ts"])
def trace_logs(trace_id: str, minutes: int = 60) -> list[dict]:
return logs(f'{{service_name=~"messenger-.+"}} | trace_id="{trace_id}"', minutes)
# ----------------------------------------------------------------------------- CLI
def main(argv: list[str]) -> int:
if len(argv) < 2:
print(__doc__)
return 2
cmd, args = argv[1], argv[2:]
if cmd == "promql":
for s in promql(args[0]):
print(json.dumps(s["metric"], ensure_ascii=False), s["value"][1])
elif cmd == "alerts":
for a in alerts():
print(f"{a['name']:<32} {a['state']:<8} since {a['activeAt']} value={a['value']}")
elif cmd == "trace":
print(tree(trace_spans(args[0])))
elif cmd == "logs":
for r in trace_logs(args[0]):
meta = r["metadata"]
print(f"{r['service']:<17} {meta.get('detected_level', meta.get('severity_text', '')):<6} {r['line']:<22} "
f"span={meta.get('span_id', '')} " + " ".join(
f"{k}={meta[k]}" for k in ("request_id", "route", "status", "job_id", "outcome", "attempt")
if k in meta))
elif cmd == "search":
for t in search(args[0]):
print(t.get("traceID"), t.get("rootServiceName"), t.get("rootTraceName"), t.get("durationMs"), "ms")
else:
print(__doc__)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+6
View File
@@ -0,0 +1,6 @@
@echo off
rem Windows wrapper: tests/resilience.py starts the hook as a program, and Windows
rem cannot execute a .sh file directly. Runs the same scripts\restart.sh with Git Bash.
rem python tests/resilience.py --mode persistence --action-script scripts/restart.cmd
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0restart.sh"
exit /b %ERRORLEVEL%
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`.
# Restarts EVERY process of the stand: LB, all API replicas, relay, worker(s), PostgreSQL, Valkey,
# S3 (SeaweedFS), the broker (RabbitMQ) and OpenBao. Volumes, schema, data, queued messages and the
# OpenBao storage are preserved: no `down -v`, no FLUSH, no purge, no re-seed.
# Lab 7: OpenBao comes back SEALED; the operator unseal step (scripts/bao_operator.py unseal, shares
# from the operator directory outside the repository) runs before the services that need secrets.
# Output is suppressed by the test; run it by hand to see the steps (no secret is printed).
set -eu
cd "$(dirname "$0")/.."
PY="${PYTHON:-python}"
# 1. Entry point, API and the pipeline processes first: nothing is served or processed while the
# stores restart underneath.
docker compose stop lb api relay worker
# 2. Stores: clean shutdown (PostgreSQL checkpoint, Valkey AOF fsync, SeaweedFS volume/filer
# flush, RabbitMQ quorum log, OpenBao raft), then start again.
docker compose restart postgres valkey s3 broker openbao
# 3. Operator: unseal (OpenBao is sealed after every start).
"$PY" scripts/bao_operator.py unseal
# 4. API replicas (log in to OpenBao again, read their secrets), relay, worker and the LB in ONE
# command: compose starts them in dependency order (lb after api is healthy) and waits for the
# health conditions once, relay/worker in parallel with api (three separate `start` calls cost
# 3 x ~23 s on Windows and exceeded the test's 90 s budget). HAProxy re-resolves the replicas.
docker compose start api relay worker lb
echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3, broker and openbao restarted with volumes preserved; openbao unsealed"
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
# Start every stopped API replica again (after scripts/stop-one.sh) and wait until Docker
# reports them healthy. The LB picks them up by itself (DNS re-resolution + checks, ~2-3 s);
# `python scripts/lbctl.py wait-up 2` waits for that explicitly.
set -eu
cd "$(dirname "$0")/.."
docker compose up -d --no-recreate --no-deps --wait api
docker compose ps api --format '{{.Name}} {{.Status}}'
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
# Rolling update of the API without downtime (Compose has no built-in one for a scaled service).
# 1. build the new image from the working tree;
# 2. run migrations ONCE with the new image (they must be additive / compatible with the
# running old version: expand first, contract in a later release);
# 3. for every OLD replica: start one NEW replica (scale N+1, old ones untouched), wait until
# Docker says healthy AND HAProxy has N+1 replicas UP, then stop the old one gracefully
# (SIGTERM -> readiness 503 -> HAProxy DOWN -> drain -> exit) and remove it.
# At every moment at least N replicas serve traffic. Stops on the first error (set -e);
# the old replicas that were not replaced yet keep running.
set -eu
cd "$(dirname "$0")/.."
PY="${PYTHON:-$(command -v python3 || command -v python)}"
# New image = new revision label (git commit + UTC time), visible in docker inspect and logs.
BUILD_REVISION="${BUILD_REVISION:-$(git rev-parse --short HEAD 2>/dev/null || echo dev)-$(date -u +%Y%m%dT%H%M%SZ)}"
export BUILD_REVISION
replicas="$(docker compose ps -q api | wc -l | tr -d ' ')"
[ "$replicas" -ge 1 ] || { echo "rolling-update: no running api replica" >&2; exit 2; }
old="$(docker compose ps -q api)"
echo "rolling-update: $replicas replica(s) to replace, new revision $BUILD_REVISION"
docker compose build api
docker compose run --rm --no-deps migrate
for id in $old; do
name="$(docker inspect -f '{{.Name}}' "$id" | tr -d '/')"
docker compose up -d --no-deps --no-recreate --wait --scale "api=$((replicas + 1))" api
"$PY" scripts/lbctl.py wait-up "$((replicas + 1))" --timeout 60
docker stop --time 15 "$id" >/dev/null
docker rm "$id" >/dev/null
"$PY" scripts/lbctl.py wait-up "$replicas" --timeout 60
echo "rolling-update: replaced $name"
done
for id in $(docker compose ps -q api); do
docker inspect -f '{{.Name}} revision={{index .Config.Labels "org.opencontainers.image.revision"}} {{.State.Status}}' "$id"
done
+7
View File
@@ -0,0 +1,7 @@
@echo off
rem Windows wrapper: tests/resilience.py starts the hook as a program, and Windows
rem cannot execute a .sh file directly. Runs the same scripts\stop-one.sh with Git Bash;
rem TARGET_INSTANCE_ID and STOP_MODE are inherited from the environment.
rem python tests/resilience.py --mode failover --action-script scripts/stop-one.cmd
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0stop-one.sh"
exit /b %ERRORLEVEL%
+51
View File
@@ -0,0 +1,51 @@
#!/bin/sh
# Failover hook for `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`.
# Stops exactly ONE API replica: the container whose X-Instance-Id is TARGET_INSTANCE_ID.
# Lab 7: X-Instance-Id is a random alias (no hostname/IP, src/messenger/config.py); each replica
# writes its alias to /tmp/instance_id inside its own container, which is how the operator maps
# alias -> container. DB, Valkey, LB, OpenBao and volumes are not touched. The replica is LEFT
# STOPPED (`docker stop` = no restart by the policy); restore it explicitly afterwards:
# scripts/restore-api.sh (make restore).
# STOP_MODE=stop (default) SIGTERM: readiness 503, 3 s drain, graceful exit (~4 s)
# STOP_MODE=kill SIGKILL at once (`docker stop -t 0`): crash of the process
# The test requires the hook to return within 10 s. On Windows one `docker exec` costs ~1.8 s, so
# the aliases are read IN PARALLEL, and `docker stop` runs in the background: Docker marks the
# container as stopped by the user at once (the restart policy will not bring it back), the drain
# and exit happen while the test is already sending requests. WAIT=1 waits for the stop (by hand).
# The test hides the output; run by hand to see it (no secrets printed).
set -eu
cd "$(dirname "$0")/.."
export MSYS_NO_PATHCONV=1 # Git Bash: keep /tmp/instance_id a container path
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!A-Za-z0-9._-]*) echo "stop-one: invalid TARGET_INSTANCE_ID" >&2; exit 2 ;;
esac
mode="${STOP_MODE:-stop}"
case "$mode" in
stop) grace=15 ;;
kill) grace=0 ;;
*) echo "stop-one: STOP_MODE must be stop or kill" >&2; exit 2 ;;
esac
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
# Only RUNNING containers of THIS compose project's service `api` are candidates.
for id in $(docker compose ps -q api); do
(docker exec "$id" cat /tmp/instance_id 2>/dev/null | tr -d '\r\n' > "$tmp/$id") &
done
wait
target=""
for f in "$tmp"/*; do
[ -f "$f" ] && [ "$(cat "$f")" = "$TARGET_INSTANCE_ID" ] && target="$(basename "$f")"
done
if [ -z "$target" ]; then
echo "stop-one: no running api replica with X-Instance-Id=$TARGET_INSTANCE_ID" >&2
exit 3
fi
if [ "${WAIT:-0}" = 1 ]; then
docker stop --time "$grace" "$target" >/dev/null
echo "stop-one: $mode $target (X-Instance-Id=$TARGET_INSTANCE_ID) -> $(docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}}' "$target")"
else
nohup docker stop --time "$grace" "$target" >/dev/null 2>&1 &
echo "stop-one: $mode $target (X-Instance-Id=$TARGET_INSTANCE_ID) requested; the container stops in the background"
fi
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Controlled request -> its trace and logs (defense scenario, steps 2-3; evidence/trace-demo.txt).
python scripts/trace_demo.py [--base-url https://localhost:8443] [--output evidence/trace-demo.txt]
1. creates a synthetic user and chat, uploads tests/fixtures/sample.png with OUR OWN W3C
`traceparent` header (trace id chosen here) and X-Request-Id;
2. waits until the attachment is ready;
3. reads the trace from Tempo and the log records of that trace from Loki (through Grafana);
4. checks: the API continued OUR trace (same trace id, the SERVER span's parent = our span id),
the chain upload -> db enqueue -> relay PRODUCER -> worker CONSUMER -> s3/db spans exists,
and api + worker log records carry this trace_id. Prints the span tree and the log lines.
No token, password or image bytes are printed.
"""
from __future__ import annotations
import argparse
import base64
import json
import secrets
import sys
import time
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import obs # noqa: E402
def call(base: str, method: str, path: str, body=None, headers=None, raw: bytes | None = None):
h = dict(headers or {})
data = raw
if body is not None:
data = json.dumps(body).encode()
h["Content-Type"] = "application/json"
request = urllib.request.Request(base + path, data=data, method=method, headers=h)
with urllib.request.urlopen(request, timeout=30, context=obs.TLS) as response:
return response.status, response.headers, json.loads(response.read() or b"null")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="https://localhost:8443")
parser.add_argument("--output")
args = parser.parse_args()
base = args.base_url.rstrip("/") + "/api/v1"
out: list[str] = []
def say(line: str = "") -> None:
print(line)
out.append(line)
username = "trace_" + uuid.uuid4().hex[:10]
password = "Trace-demo-" + secrets.token_hex(8)
_, _, user = call(base, "POST", "/users", {"username": username, "display_name": "Trace demo", "password": password})
auth = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()
_, _, session = call(base, "POST", "/auth/sessions", headers={"Authorization": auth})
bearer = {"Authorization": "Bearer " + session["token"]}
_, _, chat = call(base, "POST", "/chats", {"title": "trace demo", "member_ids": [user["id"]]}, bearer)
trace_id, parent_span = secrets.token_hex(16), secrets.token_hex(8)
request_id = "trace-demo-" + uuid.uuid4().hex[:8]
image = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
status, headers, att = call(base, "POST", f"/chats/{chat['id']}/attachments?filename=sample.png", raw=image,
headers={**bearer, "Content-Type": "image/png", "X-Request-Id": request_id,
"traceparent": f"00-{trace_id}-{parent_span}-01"})
say(f"upload: HTTP {status}, status={att['status']}, X-Request-Id={headers.get('X-Request-Id')}, "
f"X-Instance-Id={headers.get('X-Instance-Id')}, X-Trace-Id={headers.get('X-Trace-Id')}")
say(f"sent traceparent: 00-{trace_id}-{parent_span}-01")
assert headers.get("X-Trace-Id") == trace_id, "the API must continue the caller's trace"
deadline = time.monotonic() + 60
while att["status"] not in ("ready", "failed"):
assert time.monotonic() < deadline, "not ready within 60 s"
time.sleep(0.5)
_, _, att = call(base, "GET", f"/attachments/{att['id']}", headers=bearer)
say(f"attachment {att['id']}: {att['status']}, variants={[v['name'] for v in att['variants']]}")
def complete(spans):
kinds = {(s["service"], s["kind"]) for s in spans}
return (("messenger-api", "SERVER") in kinds and ("messenger-relay", "PRODUCER") in kinds
and ("messenger-worker", "CONSUMER") in kinds
and any(s["name"] == "db jobs.complete" for s in spans))
spans = obs.wait_trace(trace_id, complete, timeout=90)
say(f"\nTempo: trace {trace_id}, {len(spans)} spans")
say(obs.tree(spans))
server = next(s for s in spans if s["service"] == "messenger-api" and s["kind"] == "SERVER")
producer = next(s for s in spans if s["kind"] == "PRODUCER")
consumer = next(s for s in spans if s["kind"] == "CONSUMER")
ids = {s["span_id"]: s for s in spans}
checks = {
"API SERVER span continues our traceparent (parent = our span id)": server["parent_id"] == parent_span,
"relay PRODUCER is inside the upload trace (ancestor = API SERVER span)": _ancestor(producer, server, ids),
"worker CONSUMER is a child of the PRODUCER": consumer["parent_id"] == producer["span_id"],
"worker wrote to S3 inside the job (s3 put spans)": any(
s["name"] == "s3 put" and _ancestor(s, consumer, ids) for s in spans),
"worker committed the result (db jobs.complete span)": any(
s["name"] == "db jobs.complete" and _ancestor(s, consumer, ids) for s in spans),
}
time.sleep(3)
records = obs.trace_logs(trace_id)
say(f"\nLoki: {len(records)} log records with trace_id={trace_id}")
for r in records:
m = r["metadata"]
say(f" {r['service']:<17} {r['line']:<18} span_id={m.get('span_id', '')} " + " ".join(
f"{k}={m[k]}" for k in ("request_id", "route", "status", "job_id", "outcome") if k in m))
services = {r["service"] for r in records}
checks["API log record of the request has this trace_id and our X-Request-Id"] = any(
r["service"] == "messenger-api" and r["metadata"].get("request_id") == request_id for r in records)
checks["worker log record (job_done) has this trace_id"] = any(
r["service"] == "messenger-worker" and r["line"] == "job_done" for r in records)
say("\nChecks:")
for name, ok in checks.items():
say(f" [{'PASS' if ok else 'FAIL'}] {name}")
say(f"services in logs: {sorted(services)}")
if args.output:
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
Path(args.output).write_text("\n".join(out) + "\n", encoding="utf-8", newline="\n")
return 0 if all(checks.values()) else 1
def _ancestor(span: dict, ancestor: dict, ids: dict) -> bool:
seen = 0
while span["parent_id"] and seen < 100:
if span["parent_id"] == ancestor["span_id"]:
return True
span = ids.get(span["parent_id"])
if span is None:
return False
seen += 1
return False
if __name__ == "__main__":
sys.exit(main())
+69 -7
View File
@@ -1,19 +1,81 @@
# Модель угроз — заполнить # Модель угроз — решение lab7 (уровень 3)
## Активы и акторы ## Активы и акторы
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. **Активы.**
| Актив | Где живёт | Почему ценен |
| --- | --- | --- |
| Пароли пользователей | только Argon2id-хеш (PHC: алгоритм, параметры, соль) в `users.password_hash` | раскрытие = вход под чужим именем, в том числе на других сайтах |
| Сессии | Bearer-токен 256 бит у клиента; в Valkey только `session:<SHA-256 токена>` | токен = полномочия пользователя до expiry |
| Сообщения и вложения | PostgreSQL (метаданные), SeaweedFS (байты), приватные bucket | конфиденциальность переписки |
| Service identities | leaf-ключи в `./secrets/pki` (каждый сервис видит только свой) | ключ `lb` = право ходить в API в обход ingress |
| Секреты сервисов | пароли ролей БД, ключи S3, пароли RabbitMQ и Valkey: в `./secrets` и в OpenBao KV `messenger/` | прямой доступ к данным |
| Корни доверия | ключи `public-ca`/`internal-ca`, root token и доли unseal OpenBao | выпуск любых identity / чтение всех секретов |
| Телеметрия | Prometheus/Loki/Tempo | не должна содержать пароли, токены и тексты |
**Акторы и их доступ.**
* **Участник чата** — легальный пользователь с Bearer-токеном.
* **Посторонний пользователь** — зарегистрирован, но не участник чата.
* **Внешний клиент** — видит только `https://localhost:8443`, может подбирать пароли и подсовывать заголовки (`X-User-Id`, `X-Forwarded-For`).
* **Скомпрометированный сервис** — злоумышленник получил код или ключи одного контейнера (например worker) и действует из его сети с его credentials.
* **Оператор** — владелец хоста. Держит root token, доли unseal и ключи CA. Доверенный актор.
**Границы учебного стенда.**
* Один Docker-host; атакующий не root на хосте и не имеет доступа к Docker API (иначе он владеет всем, см. ограничения).
* Сети compose — граница сети. Все внутренние сети, кроме `edge` и `ui`, помечены `internal`.
* Данные синтетические.
## Границы доверия ## Границы доверия
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. ```
public-ca internal-ca (mTLS: allowlist SAN lb)
клиент ──HTTPS:8443──► lb (HAProxy) ────────────────────────────────► api ×2 ──TLS──► postgres (роль messenger_api)
│ ├─TLS──► valkey (ACL user api)
оператор ──HTTPS:3000──► grafana ──mTLS──► prometheus/loki/tempo │ ├─HTTPS─► s3 (ключ messenger-api)
оператор ──docker exec──► openbao (root token/доли из ~/.mtusi-lab7-operator) └─HTTPS─► openbao (AppRole api)
relay ──TLS──► postgres, ──AMQPS──► broker (user relay: только publish), ──HTTPS──► openbao (AppRole relay)
worker ──TLS──► postgres, ──AMQPS──► broker (user worker: только consume), ──HTTPS──► s3, openbao (AppRole worker)
api/relay/worker ──OTLP/HTTPS + client cert──► otel-collector ──mTLS──► prometheus / loki / tempo
```
Каждая связь (протокол, порт, CA, identity, права, тесты) описана в [contracts/trust-matrix.md](../contracts/trust-matrix.md).
* Публичные интерфейсы: только `127.0.0.1/[::1]:8443` (API через LB) и `:3000` (Grafana) — оба HTTPS.
* Секреты выдаются так. Оператор → `./secrets` (файлы) → OpenBao KV (`bao_operator.py`). Сервис приложения при старте → AppRole → свой путь KV.
* Сервисы приложения не монтируют ни одного пароля, только role_id/secret_id и свой сертификат.
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | | Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | TODO | | T1. Перехват/подмена трафика клиента: MITM на пути к ingress или фальшивый сервер с самоподписанным сертификатом | конфиденциальность Basic-пароля и Bearer-токена | только HTTPS 8443 (TLS 1.2+), сертификат `public-ca` с SAN `localhost`; клиент проверяет CA и hostname; открытого 8080 нет | `make test-security` (пустой trust store → ошибка проверки); `test_ingress_verifies_ca_and_hostname` (чужой hostname, внутренний CA → отказ); `test_no_plaintext_entry_point` | CA учебный; доверие к нему — ручная раздача `public-ca.crt`; отзыва (CRL/OCSP) нет |
| T2. Обход LB: процесс в сети `edge` или украденный ключ worker обращается к `api:8443` напрямую и подставляет `X-Forwarded-For`, чтобы обойти лимит входа | только LB говорит с API; клиентский IP честный | mTLS: `CERT_REQUIRED` + только `internal-ca` + allowlist SAN `lb` в `connection_made`; у API нет опубликованных портов; health на loopback; HAProxy перезаписывает `X-Forwarded-For` | `make mtls-check`: без cert / чужой CA с SAN `lb` / cert `worker` → отказ, `lb` → 200, по каждой реплике, TLS 1.3 и 1.2; 8081 снаружи закрыт | кража ключа `lb` = полный обход (ротация и отзыв leaf — уровень 4) |
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. | T3. Подбор пароля через `POST /auth/sessions` (одного аккаунта или одного пароля по многим аккаунтам) + DoS дорогим Argon2 | пароль нельзя угадать перебором; CPU реплики не выжигается | Argon2id m=19 MiB, t=2, p=1 (замер 30–50 мс/хеш при 1 CPU, ≤2 хеша параллельно на реплику); лимит неудач 5/60 с на username и 50/300 с на IP в Valkey (общий для реплик), проверка ДО Argon2, 429 + `Retry-After`, верный пароль при блокировке тоже 429 | `test_failed_logins_are_rate_limited_with_retry_after` (5×401 → 429, Retry-After ≤ 60, другой аккаунт не задет); unit `test_limit_per_username/ip` | можно на 60 с заблокировать вход известному username; ботнет с многих IP не ограничен глобально |
| T4. Утечка базы: дамп `users` | пароли не восстанавливаются | только Argon2id-хеш (PHC, соль 16 байт на пароль); одинаковые пароли дают разные хеши | `test_argon2id_hash_carries_salt_and_parameters` | слабый пароль из словаря всё равно подбирается офлайн, только медленнее |
| T5. Посторонний пользователь читает чужой чат или вложение, либо выдаёт себя за другого через `X-User-Id` | доступ только участникам; identity = сессия | Bearer-сессия → `user_id`; членство проверяется в SQL; чужое = 404; `X-User-Id` игнорируется; mTLS не заменяет сессию | `test_api.py::test_foreign_chat_is_indistinguishable_from_missing`, `test_x_user_id_basic_and_garbage_do_not_authenticate`, `test_attachments.py` (чужое → 404), `test_logout_revokes_only_this_token`, `test_sessions.py::test_short_ttl_expires` | — |
| T6. Скомпрометирован worker: пытается читать пользователей/сообщения в БД, писать в чужие таблицы, публиковать задачи, читать секреты API, писать в S3 как admin | наименьшие права worker | роль `messenger_worker` (GRANT только jobs/attempts/attachments/variants/outbox/job_events); RabbitMQ user `worker` только consume; S3 `messenger-worker` без Admin/List; OpenBao policy `worker` = свой путь | `test_postgres_tls_only_and_roles_least_privilege` (worker: users/messages/sessions/DELETE/функция → permission denied); `make bao-check` (worker: чужие пути, запись, sys/* → 403); `s3-init` (worker: ListBuckets пуст) | worker законно читает и пишет все вложения (это его работа) |
| T7. Подслушивание и подмена внутри Docker-сетей: процесс в сети `data`/`queue`/`storage` читает пароли и данные | конфиденциальность внутренних связей | TLS с проверкой сервера на каждой связи: PostgreSQL `verify-full` + `hostssl` only; Valkey `port 0`/`tls-port`; RabbitMQ `listeners.tcp = none`; S3 только HTTPS | `test_postgres_…` (`sslmode=disable` → отказ); `test_valkey_tls_and_acl` (без TLS нет PONG); `test_broker_tls_only…` (5672 закрыт); `test_s3_https…` (http не отвечает) | внутри контейнера остаются loopback-hop'ы (SeaweedFS master/filer, gRPC Loki/Tempo) |
| T8. Утечка секрета в Git, образ или телеметрию | секреты только у оператора и в OpenBao | `./secrets` и `*.key`/`*.pem` в `.gitignore` и `.dockerignore`; Dockerfile копирует только `src`, `migrations`, `openapi.json`; секреты через `/run/secrets` и OpenBao; логи не пишут тела, Authorization, URL с паролями; токен отзывается сразу | `test_no_secret_in_git_or_in_the_image` (значения секретов не найдены `git grep` и в файловой системе образа, `*.key` в образе нет); `test_observability.py::test_no_secrets_or_message_text_in_logs_and_traces` | значения в памяти процессов; root хоста видит `./secrets` |
| T9. Приложение получает «ключ от всего»: root token OpenBao, `BAO_TOKEN`, admin-ключ S3, суперпользователь БД | нет всемогущих credentials в app | AppRole на сервис, scoped policy, `token_no_default_policy`; root token и доли только у оператора; S3 admin только у `s3-init`; superuser БД только через локальный сокет | `make bao-check` (root token и доли не найдены в контейнерах, есть положительный контроль; нет env `*TOKEN*`); `test_compose_policy…` (точный список секретов каждого сервиса) | — |
| T10. Побег/эскалация из контейнера | изоляция хоста | нет `privileged`, host network/PID, docker.sock; `cap_drop: [ALL]` + `no-new-privileges` везде; app/worker uid 10001 с CapEff = 0; лимиты CPU/RAM на всех | `test_running_containers_are_hardened`, `test_compose_policy_limits_ports_secrets_images` | 4 stateful-образа стартуют от root ради `chown` (CHOWN/SETUID/…); read_only и seccomp-профили — уровень 4 |
## Lifecycle и инциденты ## Lifecycle и инциденты
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. * **Bootstrap.** Порядок такой:
1. Оператор запускает `scripts/init_secrets.py`: пароли и PKI в `./secrets`.
2. `docker compose up -d openbao` — OpenBao стартует запечатанным.
3. `scripts/bao_operator.py bootstrap`: init с тремя долями при пороге 2, unseal, KV, AppRole, политики, запись секретов, выпуск role_id/secret_id в `./secrets/bao`.
4. `docker compose up -d --wait`.
Bootstrap credentials сервисов (role_id/secret_id) получает только их собственный контейнер; секрет — это secret_id. Подробно: [docs/OPERATOR.md](../docs/OPERATOR.md).
* **Владельцы.** Ключи CA, root token и доли unseal — у оператора хоста. Доли лежат в `~/.mtusi-lab7-operator/<project>/` с правами 0600, вне репозитория и вне контейнеров. В команде каждая доля была бы у отдельного человека, root token — отозван после настройки.
* **Expiry.**
* Токены OpenBao сервисов отзываются через секунды после чтения; их TTL 1 ч — только верхняя граница.
* SecretID живёт 30 дней: `bao_operator.py new-secret-id <svc>`, затем пересоздать сервис.
* Leaf-сертификаты живут 365 дней, CA — 5 лет. Перевыпуск: удалить нужный leaf и запустить `init_pki.py`, затем пересоздать сервис.
* Автоматической ротации нет — это уровень 4.
* **Компрометация identity.** Утёк ключ одного сервиса — перевыпустить его leaf (CRL нет: старый leaf формально валиден до истечения, см. остаточный риск T2). Утёк secret_id — выпустить новый. Утёк сам секрет — сменить его в `./secrets` и в OpenBao (`bootstrap`). Это ручной сценарий; доказанная ротация — уровень 4.
* **Sealed или остановленный OpenBao.** Работающие api/relay/worker продолжают обслуживать запросы: секреты у них в памяти, OpenBao нужен только при старте. Новая реплика ждёт до `BAO_STARTUP_TIMEOUT_SECONDS` (60 с), пишет `openbao_unavailable`, затем завершается и перезапускается Docker. После `bao_operator.py unseal` она стартует. Это доказано в `test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones`.
* **Рестарт API.** Новый процесс заново входит по AppRole с тем же secret_id. Unseal не нужен, если сам OpenBao не перезапускался.
* **Scan findings.** Сканирование образов на CVE — требование уровня 4, на уровне 3 не выполнялось. Вместо этого: образы закреплены по digest, Python-пакеты — по sha256-хешам (`requirements.txt`).
+3
View File
@@ -0,0 +1,3 @@
"""Messenger for the MTUSI course «Высоконагруженные приложения» (lab 6: observability)."""
__version__ = "1.6.0"
+104
View File
@@ -0,0 +1,104 @@
"""Entry point: `python -m messenger`. The HTTP server is the main process (PID 1 in Docker).
Shutdown sequence on SIGTERM/SIGINT (lab 3: the replica stands behind HAProxy):
1. readiness flips to 503 (`app.state.draining = True`), requests are still served;
2. after DRAIN_SECONDS (compose: 3 s > HAProxy detection 2 x 1 s) the load balancer has
marked this replica DOWN and sends nothing new here;
3. uvicorn closes the listening socket; in-flight requests get up to
SHUTDOWN_TIMEOUT_SECONDS (compose: 8 s) to finish;
4. the lifespan closes the DB pool and the Valkey client; the process exits with code 0.
DRAIN + SHUTDOWN (11 s) < compose stop_grace_period (15 s), so Docker never needs SIGKILL.
A second signal during the drain skips the rest of it. Data stays in PostgreSQL and Valkey.
"""
from __future__ import annotations
import logging
import os
import sys
import threading
from types import FrameType
import uvicorn
from . import __version__, logging_setup, telemetry, tls
from .app import create_app
from .config import ConfigError, Settings, publish_instance_id
log = logging.getLogger("messenger")
class GracefulServer(uvicorn.Server):
"""uvicorn.Server that drains (readiness 503, still serving) before the normal graceful stop."""
def __init__(self, config: uvicorn.Config, drain_seconds: float):
super().__init__(config)
self.drain_seconds = drain_seconds
self.drain_timer: threading.Timer | None = None
def handle_exit(self, sig: int, frame: FrameType | None) -> None:
self.config.app.state.draining = True # config.app is our Starlette instance
if self.drain_timer is None and self.drain_seconds > 0 and not self.should_exit:
log.info("drain_started", extra={"fields": {"signal": sig, "drain_s": self.drain_seconds,
"timeout_s": self.config.timeout_graceful_shutdown}})
# uvicorn polls should_exit in its main loop, so setting it from a timer thread is safe.
self.drain_timer = threading.Timer(self.drain_seconds, self._stop, args=(sig, frame))
self.drain_timer.daemon = True
self.drain_timer.start()
return
if self.drain_timer is not None:
self.drain_timer.cancel() # second signal: stop draining now
self._stop(sig, frame)
def _stop(self, sig: int, frame: FrameType | None) -> None:
if not self.should_exit:
log.info("shutdown_requested", extra={"fields": {"signal": sig}})
super().handle_exit(sig, frame)
def main() -> int:
logging_setup.configure_early()
try:
settings = Settings.from_env()
except ConfigError as exc:
print(f"configuration error: {exc}", file=sys.stderr)
return 2
logging_setup.configure(settings.log_level)
publish_instance_id(settings.instance_id)
telemetry.setup("messenger-api", settings.instance_id, __version__)
app = create_app(settings)
mtls: dict = {}
if settings.tls_cert_file:
# Lab 7: mandatory mTLS (client certificate of the internal CA) + identity allowlist
# MTLS_ALLOWED_CLIENTS checked by the protocol class right after the handshake (tls.py).
context = tls.server_context(settings.tls_cert_file, settings.tls_key_file, settings.tls_client_ca_file)
protocol = tls.protocol_class()
mtls = {"ssl_context_factory": lambda _config, _default: context, "http": protocol,
"ssl_certfile": settings.tls_cert_file}
log.info("mtls_enabled", extra={"fields": {"allowed_clients": sorted(protocol.allowed)}})
config = uvicorn.Config(
app,
**mtls,
host=settings.host,
port=settings.port,
log_config=None,
access_log=False,
server_header=False,
proxy_headers=False,
lifespan="on",
timeout_graceful_shutdown=settings.shutdown_timeout,
)
server = GracefulServer(config, settings.drain_seconds)
log.info("starting", extra={"fields": {
"version": __version__, "revision": os.environ.get("APP_REVISION", "dev"), "env": settings.env, "host": settings.host, "port": settings.port,
"python": sys.version.split()[0], "storage": "postgresql", "instance_id": settings.instance_id,
}})
try:
server.run()
finally:
log.info("stopped")
telemetry.shutdown() # flush buffered spans/logs/metrics, bounded by the exporter timeouts
return 0
if __name__ == "__main__":
sys.exit(main())
+731
View File
@@ -0,0 +1,731 @@
"""HTTP layer: Starlette routes, request-id/logging middleware and error mapping."""
from __future__ import annotations
import asyncio
import contextlib
import hashlib
import json
import logging
import random
import re
import time
import uuid
from typing import Any
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import JSONResponse, Response, StreamingResponse
from starlette.routing import Route
from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Send
from opentelemetry import context as otel_context
from opentelemetry import trace
from . import attachments, authhdr, cursor, docs, passwords, ratelimit, repo, telemetry, tls, validation
from .config import Settings
from .db import Database
from .errors import BASIC_CHALLENGE, ApiError, Conflict, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable
from .sessions import SessionStore, build_store
from .storage import ObjectMissing, Storage
from .timefmt import rfc3339
log = logging.getLogger("messenger")
access_log = logging.getLogger("messenger.access")
REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
# --------------------------------------------------------------------------
# Responses
# --------------------------------------------------------------------------
def error_response(request_id: str, status: int, code: str, message: str, headers: dict[str, str] | None = None) -> JSONResponse:
body = {"error": {"code": code, "message": message, "request_id": request_id}}
return JSONResponse(body, status_code=status, headers={"X-Request-Id": request_id, **(headers or {})})
async def api_error_handler(request: Request, exc: Exception) -> JSONResponse:
assert isinstance(exc, ApiError)
return error_response(request.state.request_id, exc.status, exc.code, exc.message, exc.headers)
async def http_exception_handler(request: Request, exc: Exception) -> JSONResponse:
"""Unknown routes and wrong methods also answer in the contract error format."""
assert isinstance(exc, HTTPException)
if exc.status_code == 404:
return error_response(request.state.request_id, 404, "not_found", "Объект не найден")
if exc.status_code == 405:
return error_response(request.state.request_id, 405, "invalid_request", "Метод не поддерживается", exc.headers)
return error_response(request.state.request_id, exc.status_code, "invalid_request", "Неверный запрос")
# --------------------------------------------------------------------------
# Middleware (pure ASGI, so it also covers 404/405 and unexpected exceptions)
# --------------------------------------------------------------------------
class RequestContextMiddleware:
"""Adds X-Request-Id and X-Instance-Id to EVERY response (errors, health and crash 500/503
included), writes one access-log line, turns crashes into 500.
Lab 6: this outermost middleware is also the HTTP SERVER span and the HTTP metrics. The span
continues the caller's W3C `traceparent` (extracted from the headers BEFORE the span starts,
so a client-supplied trace is continued, not replaced by a new root). The route TEMPLATE
(`/api/v1/chats/{chat_id}/messages`) is taken from the Starlette route that served the request,
never the raw path: it names the span and labels the metrics. /health/* gets metrics but no
span (HAProxy and Docker poll it every second; those traces would only bury the real ones).
Response header X-Trace-Id = the trace of this request (to find it in Grafana/Tempo)."""
def __init__(self, app: ASGIApp, instance_id: str):
self.app = app
self.instance_id = instance_id.encode("ascii")
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
raw_headers = scope["headers"]
incoming = dict(raw_headers).get(b"x-request-id", b"").decode("latin-1")
request_id = incoming if REQUEST_ID_RE.fullmatch(incoming) else uuid.uuid4().hex
scope.setdefault("state", {})["request_id"] = request_id
method = scope["method"] if scope["method"] in KNOWN_METHODS else "_OTHER"
traced = not scope["path"].startswith("/health/")
span = (telemetry.TRACER.start_span(f"{method}", kind=telemetry.SpanKind.SERVER,
context=telemetry.extract_headers(raw_headers),
attributes={"http.request.method": method, "url.scheme": "http",
"messenger.request_id": request_id,
"service.instance.id": self.instance_id.decode("ascii")})
if traced else None)
token = otel_context.attach(trace.set_span_in_context(span)) if span is not None else None
trace_header = None
if span is not None and span.get_span_context().is_valid:
trace_header = format(span.get_span_context().trace_id, "032x").encode("ascii")
status = 500
started = False
begin = time.perf_counter()
telemetry.http_active.add(1, {"http.request.method": method})
async def send_with_id(message: AsgiMessage) -> None:
nonlocal status, started
if message["type"] == "http.response.start":
started = True
status = message["status"]
headers = [(k, v) for k, v in message.get("headers", [])
if k.lower() not in (b"x-request-id", b"x-instance-id", b"x-trace-id")]
headers.append((b"x-request-id", request_id.encode("latin-1")))
headers.append((b"x-instance-id", self.instance_id))
if trace_header is not None:
headers.append((b"x-trace-id", trace_header))
message = {**message, "headers": headers}
await send(message)
try:
await self.app(scope, receive, send_with_id)
except asyncio.CancelledError:
# uvicorn cancels requests still running when SHUTDOWN_TIMEOUT_SECONDS expires:
# answer 503 (retryable) instead of a generic 500, then let the cancellation proceed.
if not started:
status = 503
response = error_response(request_id, 503, "unavailable", "Сервер завершает работу")
await response(scope, receive, send_with_id)
raise
except Exception as exc:
log.exception("unhandled_error", extra={"fields": {"request_id": request_id}})
if span is not None:
span.record_exception(exc) # type + stack (code lines only), never request data
if not started:
status = 500
response = error_response(request_id, 500, "internal_error", "Внутренняя ошибка сервера")
await response(scope, receive, send_with_id)
finally:
elapsed = time.perf_counter() - begin
route = route_template(scope)
attributes = {"http.request.method": method, "http.route": route,
"http.response.status_code": status, "http.response.status_class": f"{status // 100}xx"}
telemetry.http_duration.record(elapsed, attributes)
telemetry.http_active.add(-1, {"http.request.method": method})
access_log.info("request", extra={"fields": {
"request_id": request_id,
"method": scope["method"],
"path": scope["path"], # ids only; query (cursor) and bodies are never logged
"route": route,
"status": status,
"instance_id": self.instance_id.decode("ascii"),
"duration_ms": round(elapsed * 1000, 3),
}})
if span is not None:
span.update_name(f"{method} {route}")
span.set_attribute("http.route", route)
span.set_attribute("http.response.status_code", status)
if status >= 500:
telemetry.mark_error(span, str(status)) # 4xx is the client's problem: not an error of the server span
span.end()
otel_context.detach(token)
KNOWN_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"})
def route_template(scope: Scope) -> str:
"""Template of the route that matched (set by the Starlette router), e.g.
/api/v1/chats/{chat_id}/messages. Unknown paths share ONE label value, so a scanner hitting
random URLs cannot create new metric series."""
route = scope.get("route")
path = getattr(route, "path", None)
return path if isinstance(path, str) else "UNMATCHED"
# --------------------------------------------------------------------------
# Request helpers
# --------------------------------------------------------------------------
def db_of(request: Request) -> Database:
return request.app.state.db
def sessions_of(request: Request) -> SessionStore:
return request.app.state.sessions
def storage_of(request: Request) -> Storage:
return request.app.state.storage
def staging_of(request: Request) -> Storage:
return request.app.state.staging
async def authenticate(request: Request) -> str:
"""User id of a valid Bearer session, otherwise 401. X-User-Id is ignored since lab 2.
Store failures are 503 (Unavailable), never 401 and never anonymous access.
"""
token = authhdr.parse_bearer(request.headers.get("authorization"))
user_id = await sessions_of(request).user_id_for(token)
if user_id is None:
raise Unauthorized("Сессия недействительна, истекла или отозвана")
return user_id
def path_uuid(request: Request, name: str) -> str:
return validation.parse_uuid(request.path_params[name], name)
async def read_json(request: Request) -> dict[str, Any]:
content_type = request.headers.get("content-type", "")
media_type, _, params = content_type.partition(";")
if media_type.strip().lower() != "application/json":
raise InvalidRequest("Content-Type должен быть application/json")
charset = params.strip().lower()
if charset and charset.replace(" ", "") not in {"charset=utf-8", "charset=\"utf-8\""}:
raise InvalidRequest("Поддерживается только кодировка UTF-8")
limit: int = request.app.state.settings.max_body_bytes
declared = request.headers.get("content-length")
if declared is not None and declared.isdigit() and int(declared) > limit:
raise PayloadTooLarge()
chunks: list[bytes] = []
size = 0
async for chunk in request.stream():
size += len(chunk)
if size > limit:
raise PayloadTooLarge()
chunks.append(chunk)
return validation.parse_json_object(b"".join(chunks))
def page_params(request: Request) -> tuple[int, str | None]:
query = request.query_params.multi_items()
limit = validation.parse_limit(validation.single_query_param(query, "limit"))
raw_cursor = validation.single_query_param(query, "cursor")
if raw_cursor is not None and raw_cursor == "":
raise InvalidRequest("cursor не может быть пустым")
return limit, raw_cursor
async def reject_body(request: Request) -> None:
"""POST /auth/sessions takes credentials only from the Basic header; any body is 400."""
if request.headers.get("transfer-encoding") or request.headers.get("content-length", "0") != "0":
raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела")
async for chunk in request.stream():
if chunk:
raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела")
def idempotency_key(request: Request) -> str:
values = request.headers.getlist("idempotency-key")
return validation.idempotency_key(values[0] if len(values) == 1 else None)
def request_fingerprint(text: str, attachment_ids: list[str]) -> bytes:
"""SHA-256 of the canonical body: key order and an absent attachment_ids vs [] do not matter."""
canonical = json.dumps({"attachment_ids": attachment_ids, "text": text},
ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).digest()
def ok(body: Any, status: int = 200) -> JSONResponse:
return JSONResponse(body, status_code=status)
# --------------------------------------------------------------------------
# Handlers
# --------------------------------------------------------------------------
async def live(request: Request) -> JSONResponse:
return ok({"status": "ok"})
async def ready(request: Request) -> JSONResponse:
"""200 only if the WHOLE mandatory synchronous path can be served: PostgreSQL, Valkey
(SESSION_STORE=valkey) and, since lab 4, the S3 bucket (upload/download of attachments)
answer. 503 while draining after SIGTERM. HAProxy routes to such replicas first."""
problem = await readiness_problem(request.app)
if problem is not None:
raise Unavailable(problem)
return ok({"status": "ok"})
async def readiness_problem(app: Starlette, core: bool = False) -> str | None:
"""None if ready, otherwise the (public, secret-free) reason. Shared by GET /health/ready(/core)
and the loopback health listener of the Docker healthcheck (tls.health_listener, lab 7).
core=True: without S3 (the LB's degraded mode, see ready_core)."""
if app.state.draining:
return "Сервер завершает работу"
if core:
db_ok, store_ok = await asyncio.gather(app.state.db.ping(), app.state.sessions.ping())
return None if db_ok and store_ok else "PostgreSQL или хранилище сессий недоступно"
db_ok, store_ok, s3_ok = await asyncio.gather(app.state.db.ping(), app.state.sessions.ping(),
app.state.storage.ping())
if not db_ok:
return "PostgreSQL недоступен"
if not store_ok:
return "Хранилище сессий недоступно"
if not s3_ok:
return "Хранилище файлов (S3) недоступно"
return None
async def ready_core(request: Request) -> JSONResponse:
"""Not in the contract: readiness WITHOUT S3, for the load balancer's degraded mode only.
If S3 is down for every replica, /health/ready is 503 everywhere; HAProxy then routes to
replicas that are at least core-ready, so chats and messages keep working while every
attachment request answers 503 itself (see infra/haproxy/haproxy.cfg)."""
problem = await readiness_problem(request.app, core=True)
if problem is not None:
raise Unavailable(problem)
return ok({"status": "ok"})
async def register_user(request: Request) -> JSONResponse:
data = await read_json(request)
validation.check_fields(data, {"username", "display_name", "password"})
username = validation.username_field(data)
display_name = validation.text_field(data, "display_name", 100)
password = validation.password_field(data)
password_hash = await passwords.hash_password(password)
user = await repo.create_user(db_of(request), username, display_name, password_hash)
log.info("user_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}})
return ok(user.to_json(), 201)
def client_ip(request: Request) -> str:
"""Client address for the login rate limit: X-Forwarded-For as SET (overwritten) by HAProxy.
Trusted because only the LB identity can connect to the API (mTLS allowlist, tls.py)."""
forwarded = request.headers.get("x-forwarded-for", "").strip()
if forwarded and len(forwarded) <= 64 and "," not in forwarded:
return forwarded
return request.client.host if request.client else "-"
async def create_session(request: Request) -> JSONResponse:
"""Login: only `Authorization: Basic`; wrong user and wrong password give the same 401.
Lab 7: failed attempts are limited per username and per client IP (ratelimit.py) -> 429 with
Retry-After, checked BEFORE the Argon2 work."""
username, password = authhdr.parse_basic(request.headers.get("authorization"))
await reject_body(request)
limiter: ratelimit.LoginLimiter = request.app.state.login_limiter
ip = client_ip(request)
try:
await limiter.check(username, ip)
except ratelimit.RateLimited as exc:
log.info("login_rate_limited", extra={"fields": {"request_id": request.state.request_id,
"retry_after_s": exc.retry_after}})
raise
found = await repo.get_credentials(db_of(request), username)
user, stored_hash = found if found else (None, None)
if not await passwords.verify_password(stored_hash, password) or user is None:
await limiter.failed(username, ip)
log.info("login_failed", extra={"fields": {"request_id": request.state.request_id}})
raise Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE)
await limiter.succeeded(username)
ttl = request.app.state.settings.session_ttl_seconds
token, expires_at = await sessions_of(request).create(user.id, ttl)
log.info("session_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}})
return ok({"token": token, "token_type": "Bearer", "expires_at": rfc3339(expires_at), "user": user.to_json()}, 201)
async def revoke_session(request: Request) -> Response:
token = authhdr.parse_bearer(request.headers.get("authorization"))
if not await sessions_of(request).revoke(token):
raise Unauthorized("Сессия недействительна, истекла или отозвана")
log.info("session_revoked", extra={"fields": {"request_id": request.state.request_id}})
return Response(status_code=204)
async def me(request: Request) -> JSONResponse:
user_id = await authenticate(request)
user = await repo.get_user(db_of(request), user_id)
if user is None:
raise Unauthorized("Сессия недействительна, истекла или отозвана")
return ok(user.to_json())
async def create_chat(request: Request) -> JSONResponse:
user_id = await authenticate(request)
data = await read_json(request)
validation.check_fields(data, {"title", "member_ids"})
title = validation.text_field(data, "title", 100)
member_ids = validation.member_ids_field(data)
chat = await repo.create_chat(db_of(request), user_id, title, member_ids)
log.info("chat_created", extra={"fields": {"request_id": request.state.request_id, "chat_id": chat.id, "members": len(member_ids)}})
return ok(chat.to_json(), 201)
async def list_chats(request: Request) -> JSONResponse:
user_id = await authenticate(request)
limit, raw_cursor = page_params(request)
after = cursor.decode(raw_cursor, cursor.CHATS, user_id) if raw_cursor else None
items, has_more = await repo.list_chats(db_of(request), user_id, after, limit)
next_cursor = cursor.encode(cursor.CHATS, user_id, items[-1].key) if has_more else None
return ok({"items": [c.to_json() for c in items], "next_cursor": next_cursor})
async def get_chat(request: Request) -> JSONResponse:
user_id = await authenticate(request)
chat_id = path_uuid(request, "chat_id")
return ok((await repo.get_chat(db_of(request), user_id, chat_id)).to_json())
def parse_message(data: dict[str, Any]) -> tuple[str, list[str]]:
"""`text` is required and a string (also with attachments); `attachment_ids`, if present, an
array of 0-10 unique UUIDs. "" or whitespace-only text is allowed only with attachments."""
validation.check_fields(data, {"text"}, frozenset({"attachment_ids"}))
attachment_ids = validation.attachment_ids_field(data)
text = validation.text_field(data, "text", 4000, min_len=0 if attachment_ids else 1,
allow_blank=bool(attachment_ids))
return text, attachment_ids
async def create_message(request: Request) -> JSONResponse:
"""Order of answers for both write paths: 401 -> 400 bad chat id -> 404 outsider -> 400 key/body
-> 409 other body with the same key -> 201 (new or replayed). sender_id comes from the session."""
user_id = await authenticate(request)
chat_id = path_uuid(request, "chat_id")
db = db_of(request)
settings = request.app.state.settings
await message_faults(request)
if settings.message_write_path == "multi":
await repo.ensure_member(db, user_id, chat_id) # outsiders get 404 before key/body are looked at
key = idempotency_key(request)
text, attachment_ids = parse_message(await read_json(request))
result = await repo.post_message(db, user_id, chat_id, key, request_fingerprint(text, attachment_ids), text,
settings.idempotency_ttl_seconds, attachment_ids)
else:
try:
key = idempotency_key(request)
text, attachment_ids = parse_message(await read_json(request))
except ApiError:
# Rare error path only: an outsider must still get 404, not a hint about the body.
await repo.ensure_member(db, user_id, chat_id)
raise
# Membership check, key claim, chat clock and message: one SQL call, one transaction.
result = await repo.post_message_single_call(db, user_id, chat_id, key,
request_fingerprint(text, attachment_ids), text,
settings.idempotency_ttl_seconds, attachment_ids)
if result.replayed:
log.info("idempotent_replay", extra={"fields": {"request_id": request.state.request_id,
"message_id": result.message.id}})
return ok(result.message.to_json(), 201)
async def list_messages(request: Request) -> JSONResponse:
user_id = await authenticate(request)
chat_id = path_uuid(request, "chat_id")
db = db_of(request)
await repo.ensure_member(db, user_id, chat_id) # 404 for outsiders before cursor details leak
limit, raw_cursor = page_params(request)
after = cursor.decode(raw_cursor, cursor.MESSAGES, chat_id) if raw_cursor else None
items, has_more = await repo.list_messages(db, chat_id, after, limit)
next_cursor = cursor.encode(cursor.MESSAGES, chat_id, items[-1].key) if has_more else None
return ok({"items": [m.to_json() for m in items], "next_cursor": next_cursor})
# ------------------------------------------------------------------ attachments (lab 4, lab 5)
async def message_faults(request: Request) -> None:
"""Lab 6 experiments (API_FAULT_POINTS slow_handler / random_5xx / random_slow); no-op normally."""
settings: Settings = request.app.state.settings
points = settings.fault_points
if not points:
return
if "random_5xx" in points and random.random() * 1000 < settings.fault_value("random_5xx", 10):
log.warning("fault_injected", extra={"fields": {"request_id": request.state.request_id, "point": "random_5xx"}})
raise Unavailable("Внедрённый отказ: random_5xx")
if "random_slow" in points and random.random() * 1000 < settings.fault_value("random_slow", 10):
await asyncio.sleep(0.5)
if "slow_handler" in points:
await asyncio.sleep(settings.fault_value("slow_handler", 300) / 1000)
def fault(request: Request, point: str) -> None:
"""Failure injection for the experiments (FAULT_POINTS of the api service, compose variable
API_FAULT_POINTS; empty in normal runs)."""
if point in request.app.state.settings.fault_points:
log.warning("fault_injected", extra={"fields": {"request_id": request.state.request_id, "point": point}})
raise Unavailable("Внедрённый отказ: " + point)
async def upload_attachment(request: Request) -> JSONResponse:
"""POST /chats/{chat_id}/attachments?filename=...: raw PNG/JPEG -> 202 queued (attachments.py)."""
settings: Settings = request.app.state.settings
reader = attachments.BodyReader(request)
slots: asyncio.Semaphore = request.app.state.upload_slots
acquired = False
try:
try:
user_id = await authenticate(request)
chat_id = path_uuid(request, "chat_id")
db = db_of(request)
await repo.ensure_member(db, user_id, chat_id) # outsiders: 404 before anything about the body
filename = validation.filename_param(validation.query_items(request.scope["query_string"]))
declared = attachments.declared_type(request)
length = attachments.declared_length(request, settings.max_upload_bytes)
try:
await asyncio.wait_for(slots.acquire(), settings.upload_queue_timeout_seconds)
except asyncio.TimeoutError:
raise attachments.Busy("Слишком много одновременных загрузок, повторите позже") from None
acquired = True
upload = await attachments.read_image(reader, settings, declared, request.app.state.verify_slots, length)
except ApiError:
# Early rejection: drop (not store) a bounded rest of the body so the client reads our error.
await reader.discard(settings.max_upload_bytes + (1 << 20), timeout=5.0)
raise
# The slot is held until the buffer is no longer needed (after the S3 PUT), so at most
# UPLOAD_CONCURRENCY bodies of this replica exist in memory at any moment.
return await store_upload(request, db, chat_id, user_id, filename, upload)
finally:
if acquired:
slots.release()
async def store_upload(request: Request, db: Database, chat_id: str, user_id: str, filename: str,
upload: attachments.Upload) -> JSONResponse:
"""intent (pending) -> staging PUT -> queued + job + outbox -> 202 (docs/PIPELINE.md).
No resize here: the worker does it; a stopped worker only delays `ready`."""
settings: Settings = request.app.state.settings
attachment_id = uuid.uuid4()
staging_key = attachments.new_staging_key()
await attachments.create_intent(db, attachment_id, chat_id, user_id, filename, upload.info, len(upload.data),
upload.sha256, staging_key)
await staging_of(request).put(staging_key, upload.data, upload.info.content_type,
{"attachment-id": str(attachment_id), "sha256": upload.sha256.hex()})
fault(request, "after_s3_put")
attachment = await attachments.enqueue(db, attachment_id, settings)
if attachment is None:
raise Unavailable("Загрузка не завершена, повторите запрос")
fault(request, "after_enqueue_commit")
log.info("attachment_queued", extra={"fields": {"request_id": request.state.request_id,
"attachment_id": attachment.id, "chat_id": chat_id,
"size": attachment.size_bytes, "type": attachment.content_type,
"pipeline_version": settings.pipeline_version}})
return ok(attachment.to_json(), 202)
async def get_attachment(request: Request) -> JSONResponse:
user_id = await authenticate(request)
attachment_id = path_uuid(request, "attachment_id")
return ok((await attachments.get_visible(db_of(request), user_id, attachment_id)).to_json())
def content_disposition(filename: str) -> str:
"""RFC 6266/5987: ASCII fallback + UTF-8 name; the stored name itself is never interpreted."""
from urllib.parse import quote
fallback = "".join(c if 32 <= ord(c) < 127 and c not in '"\\%;' else "_" for c in filename)
return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(filename, safe='')}"
async def download_attachment(request: Request) -> Response:
"""Original or variant bytes through the authorized API: no redirect, no public S3 URL.
queued/processing/failed -> 409 (not ready); a variant a ready attachment lacks -> 404.
Streamed from S3 in 64 KiB chunks (memory per download does not depend on the file size)."""
user_id = await authenticate(request)
attachment_id = path_uuid(request, "attachment_id")
query = validation.query_items(request.scope["query_string"])
try:
variant = validation.variant_param(query)
except ApiError:
await attachments.get_visible(db_of(request), user_id, attachment_id) # 404 for outsiders first
raise
attachment = await attachments.get_visible(db_of(request), user_id, attachment_id)
if attachment.status != "ready":
raise Conflict("Обработка вложения не удалась" if attachment.status == "failed" else "Вложение ещё не готово")
if attachment.lost:
raise NotFound("Оригинал вложения утрачен")
if variant == "original":
key, size_expected, media_type, etag = (attachment.object_key, attachment.size_bytes,
attachment.content_type, attachment.sha256)
name = attachment.filename
else:
found = attachment.variant(variant)
if found is None:
raise NotFound("Такого варианта у вложения нет")
key, size_expected, media_type, etag = found.object_key, found.size_bytes, found.content_type, found.sha256
stem = attachment.filename.rsplit(".", 1)[0] or "image"
name = stem + "-" + variant + (".webp" if media_type == "image/webp" else ".jpg")
try:
size, chunks = await storage_of(request).open_stream(key)
except ObjectMissing:
log.error("attachment_object_missing", extra={"fields": {"request_id": request.state.request_id,
"attachment_id": attachment.id, "variant": variant}})
raise Unavailable("Файл вложения временно недоступен") from None
if size != size_expected:
log.error("attachment_size_mismatch", extra={"fields": {"request_id": request.state.request_id,
"attachment_id": attachment.id, "variant": variant}})
await chunks.aclose()
raise Unavailable("Файл вложения временно недоступен")
headers = {
"Content-Length": str(size),
"Content-Disposition": content_disposition(name),
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, no-store",
"ETag": '"' + etag + '"',
}
return StreamingResponse(chunks, media_type=media_type, headers=headers)
def create_app(settings: Settings | None = None) -> Starlette:
settings = settings or Settings.from_env()
db = Database(settings)
sessions = build_store(settings, db)
storage = Storage(settings) # final bucket: Read
staging = Storage(settings, bucket=settings.s3_staging_bucket) # staging bucket: Write (+ janitor DELETE)
async def purge_loop() -> None:
"""Housekeeping: expired Idempotency-Key rows (older than IDEMPOTENCY_TTL_SECONDS)."""
while True:
await asyncio.sleep(600)
try:
deleted = await repo.purge_idempotency_keys(db, settings.idempotency_ttl_seconds)
if deleted:
log.info("idempotency_keys_purged", extra={"fields": {"deleted": deleted}})
except ApiError:
pass # database unavailable right now; next round
async def janitor_loop(every: float) -> None:
"""Cleanup of intents of failed uploads older than PENDING_GRACE_SECONDS (attachments.py).
Every replica runs it; the advisory lock lets one round run at a time."""
while True:
await asyncio.sleep(every * (0.5 + random.random()))
try:
removed = await attachments.clean_stale_pending(db, staging, settings.pending_grace_seconds)
if removed:
log.info("stale_uploads_removed", extra={"fields": {"count": removed}})
except ApiError:
pass # PostgreSQL or S3 unavailable right now; the rows stay pending for the next round
stats_log = logging.getLogger("messenger.stats")
async def stats_loop(every: float) -> None:
"""Experiments only: DB pool saturation (waiting requests, wait time) and process CPU."""
cpu = time.process_time()
db.pool.pop_stats()
while True:
await asyncio.sleep(every)
stats = db.pool.pop_stats()
now_cpu = time.process_time()
stats_log.info("pool_stats", extra={"fields": {
"interval_s": every, "cpu_s": round(now_cpu - cpu, 4),
**{k: stats.get(k, 0) for k in ("pool_size", "pool_available", "requests_waiting", "requests_num",
"requests_queued", "requests_wait_ms", "usage_ms", "requests_errors")}}})
cpu = now_cpu
@contextlib.asynccontextmanager
async def lifespan(app: Starlette):
passwords.configure(settings.hash_concurrency, settings.argon2_memory_kib, settings.argon2_iterations,
settings.argon2_parallelism)
telemetry.observe_pool(db.pool, db.name)
await db.open()
await storage.open()
await staging.open()
if hasattr(sessions, "warm"):
await sessions.warm() # lab 7: TLS connections to Valkey opened before readiness
log.info("dependencies_configured", extra={"fields": {
"session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds,
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds,
"instance_id": settings.instance_id, "drain_s": settings.drain_seconds,
"message_write_path": settings.message_write_path, "s3_bucket": settings.s3_bucket,
"s3_staging_bucket": settings.s3_staging_bucket, "pipeline_version": settings.pipeline_version,
"upload_concurrency": settings.upload_concurrency, "verify_concurrency": settings.image_verify_concurrency,
"pending_grace_s": settings.pending_grace_seconds,
"argon2": passwords.parameters(),
"login_limit": {"user": f"{settings.login_user_limit}/{settings.login_user_window_seconds}s",
"ip": f"{settings.login_ip_limit}/{settings.login_ip_window_seconds}s"},
"fault_points": sorted(settings.fault_points)}})
tasks = [asyncio.create_task(purge_loop())]
if settings.janitor_interval_seconds > 0:
tasks.append(asyncio.create_task(janitor_loop(settings.janitor_interval_seconds)))
if settings.stats_log_seconds > 0:
tasks.append(asyncio.create_task(stats_loop(settings.stats_log_seconds)))
health_server = None
if settings.health_port:
async def probe(path: str) -> int:
if path == "/health/live":
return 200
problem = await readiness_problem(app, core=path == "/health/ready/core")
return 200 if problem is None else 503
health_server = await tls.health_listener(settings.health_port, probe)
try:
yield
finally:
if health_server is not None:
health_server.close()
for task in tasks:
task.cancel()
await sessions.close()
await staging.close()
await storage.close()
await db.close()
routes = [
Route("/health/live", live, methods=["GET"]),
Route("/health/ready", ready, methods=["GET"]),
Route("/health/ready/core", ready_core, methods=["GET"]),
Route("/api/v1/users", register_user, methods=["POST"]),
Route("/api/v1/users/me", me, methods=["GET"]),
Route("/api/v1/auth/sessions", create_session, methods=["POST"]),
Route("/api/v1/auth/sessions/current", revoke_session, methods=["DELETE"]),
Route("/api/v1/chats", create_chat, methods=["POST"]),
Route("/api/v1/chats", list_chats, methods=["GET"]),
Route("/api/v1/chats/{chat_id}", get_chat, methods=["GET"]),
Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]),
Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]),
Route("/api/v1/chats/{chat_id}/attachments", upload_attachment, methods=["POST"]),
Route("/api/v1/attachments/{attachment_id}", get_attachment, methods=["GET"]),
Route("/api/v1/attachments/{attachment_id}/content", download_attachment, methods=["GET"]),
]
if settings.docs_enabled: # Swagger UI for manual experiments, not part of the contract
routes += [
Route("/docs", docs.swagger_page, methods=["GET"]),
Route("/openapi.json", docs.openapi_json, methods=["GET"]),
]
app = Starlette(
routes=routes,
exception_handlers={ApiError: api_error_handler, HTTPException: http_exception_handler},
lifespan=lifespan,
)
app.add_middleware(RequestContextMiddleware, instance_id=settings.instance_id)
app.state.settings = settings
app.state.db = db
app.state.sessions = sessions
app.state.login_limiter = ratelimit.LoginLimiter(settings, getattr(sessions, "client", None))
app.state.storage = storage
app.state.staging = staging
app.state.upload_slots = asyncio.Semaphore(settings.upload_concurrency)
app.state.verify_slots = asyncio.Semaphore(settings.image_verify_concurrency)
app.state.draining = False
return app
+339
View File
@@ -0,0 +1,339 @@
"""Attachments: metadata in PostgreSQL, bytes in private S3 buckets (lab 4), processed
asynchronously by the worker (lab 5, docs/PIPELINE.md).
Upload (POST /chats/{id}/attachments, raw PNG/JPEG body), in this order:
auth -> membership (404) -> filename / Content-Type / Content-Length (400/415/413)
-> upload slot (at most UPLOAD_CONCURRENCY bodies per replica, else 503 + Retry-After)
-> body in chunks: size limit, read deadline, format + pixel count from the first bytes
-> full integrity check (images.verify) -> SHA-256 / size known (415 is decided HERE)
-> INSERT row status='pending' with a fresh random staging key, COMMIT (intent)
-> PUT the original into the STAGING bucket (Content-MD5)
-> ONE transaction: status 'pending' -> 'queued' + jobs row + outbox row, COMMIT
-> 202 queued.
What is durable at 202: the complete, verified original in the staging bucket (S3 confirmed the
PUT and its MD5), the metadata row, the job and the outbox row that makes the relay publish it.
A crash of the API after the answer loses nothing; a broker that is down only delays the publish.
Failures between the steps (docs/PIPELINE.md, failure windows):
* before the intent COMMIT: nothing was written;
* after the intent, before/while PUT, or between PUT and the job COMMIT (FAULT_POINTS=after_s3_put):
a 'pending' row (+ maybe the staging object), invisible to everybody (404). The client got 503
and may retry (a new attachment). The janitor deletes the staging object - idempotent - and then
the row once it is older than PENDING_GRACE_SECONDS, deciding under the row lock;
* after the job COMMIT, answer lost (FAULT_POINTS=after_enqueue_commit): a correct queued
attachment the client does not know; the worker processes it as usual.
"""
from __future__ import annotations
import asyncio
import datetime as dt
import hashlib
import logging
import secrets
import uuid
from dataclasses import dataclass
import psycopg
from psycopg import errors as pg_errors
from starlette.requests import Request
from . import images, jobs
from .config import Settings
from .db import Database
from .errors import ApiError, InvalidRequest, NotFound, PayloadTooLarge, Unavailable, UnsupportedMediaType
from .storage import STAGING_PREFIX, Storage
from .timefmt import rfc3339
log = logging.getLogger("messenger.attachments")
JANITOR_LOCK_ID = 2026_04 # advisory lock: one janitor round at a time across all replicas
@dataclass(frozen=True, slots=True)
class Variant:
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
object_key: str
def to_json(self) -> dict:
return {"name": self.name, "content_type": self.content_type, "size_bytes": self.size_bytes,
"width": self.width, "height": self.height, "sha256": self.sha256}
@dataclass(frozen=True, slots=True)
class Attachment:
id: str
chat_id: str
owner_id: str
filename: str
content_type: str
size_bytes: int
sha256: str
object_key: str | None # published original in the final bucket (None until the worker publishes it)
status: str
created_at: dt.datetime
updated_at: dt.datetime
lost: bool = False
error_code: str | None = None
published_version: int | None = None
variants: tuple[Variant, ...] = ()
def to_json(self) -> dict:
"""Public representation: no object keys, no buckets, no job internals."""
return {"id": self.id, "chat_id": self.chat_id, "owner_id": self.owner_id, "filename": self.filename,
"content_type": self.content_type, "size_bytes": self.size_bytes, "sha256": self.sha256,
"status": self.status, "variants": [v.to_json() for v in self.variants] if self.status == "ready" else [],
"error_code": self.error_code if self.status == "failed" else None,
"created_at": rfc3339(self.created_at), "updated_at": rfc3339(self.updated_at)}
def variant(self, name: str) -> Variant | None:
return next((v for v in self.variants if v.name == name), None)
COLUMNS = ("a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.object_key, "
"a.status, a.created_at, a.updated_at, a.lost_at IS NOT NULL, a.error_code, a.published_version")
def _attachment(row, variants: tuple[Variant, ...] = ()) -> Attachment:
return Attachment(str(row[0]), str(row[1]), str(row[2]), row[3], row[4], row[5], bytes(row[6]).hex(), row[7],
row[8], row[9], row[10], row[11], row[12], row[13], variants)
def new_staging_key() -> str:
"""Server-generated, 128 random bits, unrelated to the attachment id and the filename."""
return STAGING_PREFIX + secrets.token_hex(16)
# ------------------------------------------------------------------ SQL
async def create_intent(db: Database, attachment_id: uuid.UUID, chat_id: str, owner_id: str, filename: str,
info: images.ImageInfo, size: int, sha256: bytes, staging_key: str) -> None:
async def work(conn: psycopg.AsyncConnection) -> None:
await conn.execute(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
"width, height, staging_key, staging_state, status) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'present', 'pending')",
(attachment_id, chat_id, owner_id, filename, info.content_type, size, sha256, info.width, info.height,
staging_key))
try:
await db.run(work, transaction=False)
except pg_errors.ForeignKeyViolation:
raise NotFound("Чат не найден") from None
async def enqueue(db: Database, attachment_id: uuid.UUID, settings: Settings) -> Attachment | None:
"""pending -> queued + job + outbox row in ONE transaction (the durable handoff before 202).
None if the row is no longer pending (the janitor removed a stale intent)."""
async def work(conn: psycopg.AsyncConnection) -> Attachment | None:
cur = await conn.execute(
"UPDATE attachments a SET status = 'queued', updated_at = clock_timestamp() "
f"WHERE a.id = %s AND a.status = 'pending' RETURNING {COLUMNS}", (attachment_id,))
row = await cur.fetchone()
if row is None:
return None
await jobs.create_job(conn, attachment_id, settings.pipeline_version, "upload", settings.job_max_attempts,
"api:" + settings.instance_id)
return _attachment(row)
return await db.run(work)
async def get_visible(db: Database, user_id: str, attachment_id: str) -> Attachment:
"""An attachment of a chat the user is a member of, in any state but the invisible intent
'pending'; anything else is 404 (unknown, foreign chat, unfinished upload) - existence of
foreign objects is never revealed. A ready attachment comes with its published variants."""
async def work(conn: psycopg.AsyncConnection) -> Attachment:
cur = await conn.execute(
f"SELECT {COLUMNS} FROM attachments a "
"JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = %s "
"WHERE a.id = %s AND a.status <> 'pending'", (user_id, attachment_id))
row = await cur.fetchone()
if row is None:
raise NotFound("Вложение не найдено")
variants: tuple[Variant, ...] = ()
if row[8] == "ready":
cur = await conn.execute(
"SELECT name, content_type, size_bytes, width, height, sha256, object_key FROM attachment_variants "
"WHERE attachment_id = %s AND pipeline_version = %s "
"ORDER BY array_position(ARRAY['thumbnail', 'crop', 'optimized'], name)", (row[0], row[13]))
variants = tuple(Variant(r[0], r[1], r[2], r[3], r[4], bytes(r[5]).hex(), r[6]) for r in await cur.fetchall())
return _attachment(row, variants)
# REPEATABLE READ is not needed: the variant rows of a published version never change.
return await db.run(work)
async def clean_stale_pending(db: Database, staging: Storage, grace_seconds: int, batch: int = 20) -> int:
"""Janitor round: remove intents of uploads that never got their job (no 202 was sent).
Under FOR UPDATE: an upload that is (impossibly) still running would block on the row in
enqueue() and then find it gone (-> 503). Order: staging object first (idempotent), row second;
a crash in between leaves the pending row and the next round repeats. Only status='pending'
rows older than the grace period are touched: queued/processing/ready/failed never.
"""
async def work(conn: psycopg.AsyncConnection) -> int:
cur = await conn.execute("SELECT pg_try_advisory_xact_lock(%s)", (JANITOR_LOCK_ID,))
if not (await cur.fetchone())[0]:
return 0
cur = await conn.execute(
"SELECT id, staging_key FROM attachments WHERE status = 'pending' "
"AND created_at < clock_timestamp() - make_interval(secs => %s) "
"ORDER BY created_at LIMIT %s FOR UPDATE SKIP LOCKED", (grace_seconds, batch))
rows = await cur.fetchall()
if not rows:
return 0
await asyncio.gather(*(staging.delete(key) for _, key in rows))
await conn.execute("DELETE FROM attachments WHERE id = ANY(%s) AND status = 'pending'",
([r[0] for r in rows],))
return len(rows)
return await db.run(work, deadline=staging.timeout + 5)
# ------------------------------------------------------------------ request body
class Busy(Unavailable):
"""All upload slots of this replica are taken: retry shortly (no body was read)."""
@property
def headers(self) -> dict[str, str]:
return {"Retry-After": "1"}
@dataclass
class Upload:
data: bytearray
info: images.ImageInfo
sha256: bytes
class BodyReader:
"""Reads the raw ASGI body ourselves (not request.stream()), so we always know how much of it
is consumed and can discard the rest after an early rejection."""
def __init__(self, request: Request):
self.receive = request.receive
self.done = False
async def chunk(self, timeout: float) -> bytes | None:
if self.done:
return None
message = await asyncio.wait_for(self.receive(), timeout)
if message["type"] == "http.disconnect":
self.done = True
raise InvalidRequest("Клиент прервал загрузку")
if not message.get("more_body", False):
self.done = True
return message.get("body", b"")
async def discard(self, limit: int, timeout: float) -> None:
"""After an early 4xx: read and DROP up to `limit` more bytes, so an ordinary client that
writes the whole body before reading the answer still gets our JSON error instead of a
connection reset. Nothing is kept in memory; beyond the limit the connection is dropped."""
loop = asyncio.get_running_loop()
deadline = loop.time() + timeout
seen = 0
try:
while not self.done and seen <= limit:
remaining = deadline - loop.time()
if remaining <= 0:
return
seen += len(await self.chunk(remaining) or b"")
except (ApiError, asyncio.TimeoutError):
return
def declared_type(request: Request) -> str:
"""Content-Type of the upload must be image/png or image/jpeg (parameters ignored)."""
media_type = request.headers.get("content-type", "").partition(";")[0].strip().lower()
if media_type not in (images.PNG, images.JPEG):
raise UnsupportedMediaType("Content-Type должен быть image/png или image/jpeg")
return media_type
def declared_length(request: Request, limit: int) -> int | None:
raw = request.headers.get("content-length")
if raw is None:
return None # chunked transfer: the limit is enforced while reading
if not raw.isdigit():
raise InvalidRequest("Неверный Content-Length")
length = int(raw)
if length > limit:
raise PayloadTooLarge(f"Файл больше {limit} байт")
if length == 0:
raise InvalidRequest("Тело запроса пустое: нужны байты изображения")
return length
async def read_image(reader: BodyReader, settings: Settings, declared: str, verify_slots: asyncio.Semaphore,
length: int | None) -> Upload:
"""Body -> verified image. Memory: ONE buffer of at most MAX_UPLOAD_BYTES per upload - exactly
Content-Length bytes allocated once when the length is declared (no growth, no final copy);
it is passed as is to the checks and to the S3 PUT. The format and the pixel count are known
after the first bytes, so a picture that is too big or not a PNG/JPEG is rejected without
reading/decoding the rest."""
loop = asyncio.get_running_loop()
deadline = loop.time() + settings.upload_read_timeout_seconds
limit = settings.max_upload_bytes
buffer = bytearray(length) if length else bytearray()
view = memoryview(buffer) if length else None
filled = 0
digest = hashlib.sha256()
info: images.ImageInfo | None = None
while True:
remaining = deadline - loop.time()
if remaining <= 0:
raise InvalidRequest("Тело запроса не получено вовремя")
try:
chunk = await reader.chunk(remaining)
except asyncio.TimeoutError:
raise InvalidRequest("Тело запроса не получено вовремя") from None
if chunk is None:
break
if filled + len(chunk) > (length or limit):
raise PayloadTooLarge(f"Файл больше {limit} байт")
if view is not None:
view[filled:filled + len(chunk)] = chunk
else:
buffer += chunk
filled += len(chunk)
digest.update(chunk)
if info is None and filled:
info = _sniff(view[:filled] if view is not None else buffer, settings, declared)
if view is not None:
view.release()
if not filled:
raise InvalidRequest("Тело запроса пустое: нужны байты изображения")
if length and filled != length:
raise InvalidRequest("Тело запроса короче Content-Length")
if info is None:
raise UnsupportedMediaType("Файл не является корректным изображением PNG или JPEG")
try:
async with verify_slots:
await images.verify(buffer, info, timeout=settings.image_verify_timeout_seconds,
jpeg_max_memory_mb=settings.jpeg_max_memory_mb)
except images.ImageError as exc:
raise _image_error(exc) from None
except asyncio.TimeoutError:
raise UnsupportedMediaType("Изображение не удалось проверить за отведённое время") from None
except (images.VerifierUnavailable, MemoryError):
log.warning("image_verifier_unavailable", extra={"fields": {"type": info.content_type, "size": filled}})
raise Busy("Не хватило ресурсов для проверки изображения, повторите позже") from None
return Upload(buffer, info, digest.digest())
def _sniff(buffer: bytearray, settings: Settings, declared: str) -> images.ImageInfo | None:
try:
info = images.sniff(buffer, settings.max_image_pixels)
except images.ImageError as exc:
raise _image_error(exc) from None
if info is not None and info.content_type != declared:
# "MIME spoofing": the header says PNG, the bytes are JPEG (or vice versa).
raise UnsupportedMediaType("Содержимое не совпадает с Content-Type")
return info
def _image_error(exc: images.ImageError) -> ApiError:
return PayloadTooLarge(exc.message) if exc.status == 413 else UnsupportedMediaType(exc.message)
+190
View File
@@ -0,0 +1,190 @@
"""Track 2: read-only checker of the pipeline invariants: `python -m messenger.audit`
(compose service `auditor`, profile tools; `make audit`).
Read-only by construction: every database transaction is `READ ONLY` (PostgreSQL refuses any
write), and the S3 key pair of the auditor has Read + List only. Output: one JSON report; exit 1
if any invariant is violated.
Invariants (docs/PIPELINE.md):
I1 no lost work - a queued/processing attachment has an active job; an active job has an
outbox row (published or due) - nothing waits for a message that nobody sends.
I2 one effect - per (attachment, pipeline_version) either no variant rows or exactly the
three variants, all written by ONE successful attempt of a job of that version.
I3 published data - every published object (original, variants) exists with the stored size
(--verify-checksums: and the stored SHA-256).
I4 monotonic - published_version = the highest version with a succeeded job; a ready
attachment is never queued/processing again (published_version stays set).
I5 source kept - an active job whose original is not published still has its staging copy
(state present AND the object exists in the staging bucket).
I6 no stray data - every object in the buckets is referenced: published, staging of a live row,
or planned by an attempt whose objects were not cleaned yet. An object of an
already cleaned attempt is reported as `leaked_object` (written by a stalled
attempt after its cleanup: garbage, never a loss).
I7 attempts - a succeeded job has exactly one succeeded attempt; at most one running attempt
per job, and it is the lease holder.
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import sys
from .config import ConfigError, Settings
from .db import Database
from .errors import Unavailable
from .pipeline import VARIANT_NAMES
from .storage import ObjectMissing, SENTINEL_KEY, Storage
async def rows(db: Database, sql: str, params=()) -> list[tuple]:
async def work(conn):
await conn.execute("SET TRANSACTION READ ONLY")
cur = await conn.execute(sql, params)
return await cur.fetchall()
return await db.run(work, deadline=db.deadline)
async def list_all(storage: Storage, prefix: str) -> dict[str, int]:
found, after = {}, None
while True:
page, more = await storage.list_page(prefix, after, 1000)
for item in page:
found[item.key] = item.size
if not more or not page:
return found
after = page[-1].key
async def audit(settings: Settings, verify: bool) -> dict:
db = Database(settings, name="messenger-audit")
final = Storage(settings)
staging = Storage(settings, bucket=settings.s3_staging_bucket)
await db.open()
await final.open()
await staging.open()
violations: list[dict] = []
notes: list[dict] = []
def bad(kind: str, **detail) -> None:
violations.append({"invariant": kind, **{k: str(v) for k, v in detail.items()}})
try:
# I1: queued/processing attachment without an active job; active job without outbox row.
for (aid,) in await rows(db, "SELECT a.id FROM attachments a WHERE a.status IN ('queued', 'processing') "
"AND NOT EXISTS (SELECT 1 FROM jobs j WHERE j.attachment_id = a.id "
"AND j.state IN ('queued', 'processing'))"):
bad("I1_no_active_job", attachment_id=aid)
for (jid,) in await rows(db, "SELECT j.id FROM jobs j WHERE j.state = 'queued' AND NOT EXISTS "
"(SELECT 1 FROM outbox o WHERE o.job_id = j.id)"):
bad("I1_queued_without_outbox", job_id=jid)
# I2: exactly three variants per published version, one successful attempt of that version.
for aid, version, names, tokens in await rows(
db, "SELECT attachment_id, pipeline_version, array_agg(name ORDER BY name), "
"array_agg(DISTINCT attempt_token) FROM attachment_variants GROUP BY 1, 2"):
if sorted(names) != sorted(VARIANT_NAMES):
bad("I2_variant_set", attachment_id=aid, version=version, names=names)
if len(tokens) != 1:
bad("I2_mixed_attempts", attachment_id=aid, version=version, attempts=len(tokens))
for aid, version, outcome, jversion in await rows(
db, "SELECT v.attachment_id, v.pipeline_version, ja.outcome, j.pipeline_version "
"FROM attachment_variants v JOIN job_attempts ja ON ja.token = v.attempt_token "
"JOIN jobs j ON j.id = ja.job_id WHERE ja.outcome <> 'succeeded' OR j.pipeline_version "
"<> v.pipeline_version OR j.attachment_id <> v.attachment_id"):
bad("I2_variant_from_unsuccessful_attempt", attachment_id=aid, version=version, outcome=outcome)
# I4: published_version = highest succeeded version; ready <=> published.
for aid, status, published, best in await rows(
db, "SELECT a.id, a.status, a.published_version, (SELECT max(j.pipeline_version) FROM jobs j "
"WHERE j.attachment_id = a.id AND j.state = 'succeeded') FROM attachments a "
"WHERE a.published_version IS DISTINCT FROM (SELECT max(j.pipeline_version) FROM jobs j "
"WHERE j.attachment_id = a.id AND j.state = 'succeeded') "
"OR (a.published_version IS NOT NULL AND a.status <> 'ready')"):
bad("I4_published_version", attachment_id=aid, status=status, published=published, best_succeeded=best)
# I7: attempts.
for (jid,) in await rows(db, "SELECT j.id FROM jobs j WHERE j.state = 'succeeded' AND (SELECT count(*) "
"FROM job_attempts a WHERE a.job_id = j.id AND a.outcome = 'succeeded') <> 1"):
bad("I7_succeeded_attempts", job_id=jid)
for jid, token in await rows(db, "SELECT a.job_id, a.token FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
"WHERE a.outcome = 'running' AND j.lease_token IS DISTINCT FROM a.token"):
bad("I7_running_not_holder", job_id=jid, token=token)
# I3 + I5 + I6: storage.
published = {k: (s, h) for k, s, h in await rows(
db, "SELECT object_key, size_bytes, sha256 FROM attachment_variants UNION ALL "
"SELECT object_key, size_bytes, sha256 FROM attachments WHERE object_key IS NOT NULL")}
staging_live = {k: (s, st, status) for k, s, st, status in await rows(
db, "SELECT staging_key, size_bytes, staging_state, status FROM attachments WHERE staging_key IS NOT NULL")}
planned_open, planned_cleaned = set(), set()
for keys, cleaned in await rows(db, "SELECT planned_keys, objects_cleaned_at IS NOT NULL FROM job_attempts"):
(planned_cleaned if cleaned else planned_open).update(keys)
final_objects = await list_all(final, "")
staging_objects = await list_all(staging, "")
for key, (size, sha) in published.items():
if key not in final_objects:
bad("I3_published_missing", key=key)
elif final_objects[key] != size:
bad("I3_published_size", key=key, stored=size, actual=final_objects[key])
elif verify:
data = await final.read_all(key, limit=settings.max_upload_bytes)
if hashlib.sha256(data).digest() != bytes(sha):
bad("I3_published_checksum", key=key)
for key, (size, state, status) in staging_live.items():
# 'pending' may lack its object (the PUT failed: the janitor removes the row); accepted
# work (queued/processing) must have it.
active = status in ("queued", "processing")
if state == "present" and key not in staging_objects and active:
bad("I5_staging_missing", key=key, status=status)
for (aid,) in await rows(db, "SELECT a.id FROM attachments a WHERE a.status IN ('queued', 'processing') "
"AND a.object_key IS NULL AND a.staging_state <> 'present'"):
bad("I5_active_without_source", attachment_id=aid)
for key in final_objects:
if key == SENTINEL_KEY or key in published or key in planned_open:
continue
if key in planned_cleaned:
notes.append({"kind": "leaked_object", "key": key})
else:
bad("I6_unknown_final_object", key=key)
for key in staging_objects:
if key == SENTINEL_KEY:
continue
row = staging_live.get(key)
if row is None:
bad("I6_unknown_staging_object", key=key)
elif row[1] == "deleted":
notes.append({"kind": "staging_marked_deleted_still_present", "key": key})
counts = dict(await rows(db, "SELECT status, count(*) FROM attachments GROUP BY status"))
jobs = dict(await rows(db, "SELECT state, count(*) FROM jobs GROUP BY state"))
return {"ok": not violations, "violations": violations, "notes": notes,
"attachments": counts, "jobs": jobs,
"objects": {"final": len(final_objects), "staging": len(staging_objects),
"published": len(published), "checksums_verified": verify}}
finally:
await staging.close()
await final.close()
await db.close()
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="audit", description="Read-only check of the pipeline invariants")
p.add_argument("--verify-checksums", action="store_true", help="read every published object and compare SHA-256")
args = p.parse_args(argv)
try:
settings = Settings.from_env()
except ConfigError as exc:
print(f"configuration error: {exc}", file=sys.stderr)
return 2
try:
report = asyncio.run(audit(settings, args.verify_checksums))
except (Unavailable, ObjectMissing) as exc:
print(json.dumps({"ok": False, "error": "store_unavailable", "detail": type(exc).__name__}))
return 1
print(json.dumps(report, ensure_ascii=False, indent=1, default=str))
return 0 if report["ok"] else 1
if __name__ == "__main__":
sys.exit(main())
+48
View File
@@ -0,0 +1,48 @@
"""Parsing of the Authorization header. Any malformed value is 401, never 500.
Basic (RFC 7617) is accepted only by POST /auth/sessions; everything else needs
Bearer. Basic is an encoding, not encryption: plain HTTP is acceptable only for the
local synthetic lab stand (lab 7 adds TLS).
"""
from __future__ import annotations
import base64
import binascii
import re
from .errors import BASIC_CHALLENGE, BEARER_CHALLENGE, Unauthorized
from .validation import USERNAME_RE
B64_RE = re.compile(r"[A-Za-z0-9+/]+={0,2}")
TOKEN_RE = re.compile(r"[A-Za-z0-9_-]{32,128}") # token_urlsafe(32) gives 43 characters
def _split(header: str | None) -> tuple[str, str]:
if not header:
return "", ""
scheme, _, value = header.strip().partition(" ")
return scheme.lower(), value.strip()
def parse_basic(header: str | None) -> tuple[str, str]:
"""(username, password) from `Basic base64(username:password)`; the password may contain ':'."""
invalid = Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE)
scheme, value = _split(header)
if scheme != "basic" or B64_RE.fullmatch(value) is None or len(value) > 1024:
raise invalid
try:
decoded = base64.b64decode(value, validate=True).decode("utf-8")
except (binascii.Error, ValueError, UnicodeDecodeError):
raise invalid from None
username, sep, password = decoded.partition(":") # split at the FIRST colon
if not sep or USERNAME_RE.fullmatch(username) is None or not password:
raise invalid
return username, password
def parse_bearer(header: str | None) -> str:
scheme, value = _split(header)
if scheme != "bearer" or TOKEN_RE.fullmatch(value) is None:
# Missing header, Basic on a business endpoint, garbage token: one answer.
raise Unauthorized("Требуется действительная Bearer-сессия", challenge=BEARER_CHALLENGE)
return value
+116
View File
@@ -0,0 +1,116 @@
"""Lab 7: secrets of a service from OpenBao (AppRole login -> read own KV path -> revoke token).
Used by config._secret(): when BAO_ADDR is set, DATABASE_URL / CACHE_URL / S3_* / BROKER_URL come from
`BAO_SECRET_PATH` (e.g. messenger/data/api) instead of files. Startup sequence (once per process):
1. read role_id + secret_id from BAO_ROLE_ID_FILE / BAO_SECRET_ID_FILE (Docker secrets of THIS
service only; the "first secret" delivered by the operator, scripts/bao_operator.py);
2. POST auth/approle/login over HTTPS (server verified: BAO_CACERT = internal CA, hostname openbao)
-> a service token with ONE policy (read its own path), TTL 1 h;
3. GET the KV path -> the values stay in process memory only (never logged, never written);
4. POST auth/token/revoke-self: the token is dead seconds after it was created.
Failure modes (README "что происходит при ..."):
* OpenBao sealed/stopped at start: retried for BAO_STARTUP_TIMEOUT_SECONDS, then the process exits
(configuration error) and Docker restarts it; replicas that are already running are not
affected - they do not need OpenBao after startup.
* Token expiry: irrelevant after startup (revoked anyway); every new process logs in again.
* Wrong/expired secret_id or a policy denial: fail at once with the HTTP status, no retry.
No root token, no unseal key and no long-lived token ever exist in an application container.
"""
from __future__ import annotations
import json
import logging
import os
import ssl
import time
import urllib.error
import urllib.request
from pathlib import Path
log = logging.getLogger("messenger.bao")
_cache: dict[str, str] | None = None
class BaoError(RuntimeError):
pass
def enabled() -> bool:
return bool(os.environ.get("BAO_ADDR", "").strip())
def _file(name: str) -> str:
path = os.environ.get(name, "").strip()
if not path:
raise BaoError(f"{name} must be set when BAO_ADDR is set")
try:
return Path(path).read_text(encoding="utf-8").strip()
except OSError as exc:
raise BaoError(f"{name}={path} cannot be read: {exc.strerror}") from None
class Client:
def __init__(self, addr: str, ca_file: str, timeout: float = 5.0):
self.addr = addr.rstrip("/")
self.timeout = timeout
self.context = ssl.create_default_context(cafile=ca_file or None) # verify chain + hostname
self.context.minimum_version = ssl.TLSVersion.TLSv1_2
def call(self, method: str, path: str, token: str | None = None, body: dict | None = None) -> dict:
data = json.dumps(body).encode() if body is not None else (b"" if method == "POST" else None)
request = urllib.request.Request(f"{self.addr}/v1/{path}", data=data, method=method)
request.add_header("Content-Type", "application/json")
if token:
request.add_header("X-Vault-Token", token)
with urllib.request.urlopen(request, timeout=self.timeout, context=self.context) as response:
raw = response.read()
return json.loads(raw) if raw else {}
def _status(exc: Exception) -> int | None:
return exc.code if isinstance(exc, urllib.error.HTTPError) else None
def fetch() -> dict[str, str]:
"""Login, read the service's KV path, revoke the token. Values are cached for the process."""
global _cache
if _cache is not None:
return _cache
client = Client(os.environ["BAO_ADDR"], os.environ.get("BAO_CACERT", "").strip())
path = os.environ.get("BAO_SECRET_PATH", "").strip()
if not path:
raise BaoError("BAO_SECRET_PATH must be set when BAO_ADDR is set")
role_id, secret_id = _file("BAO_ROLE_ID_FILE"), _file("BAO_SECRET_ID_FILE")
deadline = time.monotonic() + float(os.environ.get("BAO_STARTUP_TIMEOUT_SECONDS", "60"))
while True:
try:
auth = client.call("POST", "auth/approle/login", body={"role_id": role_id, "secret_id": secret_id})["auth"]
token = auth["client_token"]
try:
data = client.call("GET", path, token=token)["data"]["data"]
finally:
try:
client.call("POST", "auth/token/revoke-self", token=token)
except (urllib.error.URLError, OSError):
pass # TTL (1 h) bounds the token anyway
break
except (urllib.error.URLError, OSError, KeyError, ValueError) as exc:
status = _status(exc)
# 503 = sealed / standby, no status = unreachable: wait for the operator. 4xx = our
# credentials or the policy are wrong: retrying would not help.
if status is not None and status != 503:
raise BaoError(f"OpenBao refused {path!r} for this service: HTTP {status}") from None
if time.monotonic() > deadline:
raise BaoError(f"OpenBao unavailable (sealed or unreachable): {type(exc).__name__}") from None
log.warning("openbao_unavailable", extra={"fields": {"status": status, "error": type(exc).__name__}})
time.sleep(2)
if not isinstance(data, dict):
raise BaoError(f"OpenBao path {path!r} has no KV data")
log.info("secrets_loaded", extra={"fields": {
"path": path, "keys": sorted(data), "policies": auth.get("token_policies"),
"token_ttl_s": auth.get("lease_duration"), "token_revoked": True}})
_cache = {str(k): str(v) for k, v in data.items()}
return _cache
+103
View File
@@ -0,0 +1,103 @@
"""RabbitMQ (AMQP 0-9-1) for the attachment jobs: topology names and the message format.
Topology (declared by the broker itself from its definitions file at boot, infra/rabbitmq and
scripts/init_secrets.py; the relay and the worker have NO configure permission and declare nothing):
exchange messenger.jobs direct, durable
queue messenger.attachment-jobs quorum (Raft log on disk), bound with routing key
attachment.process.v1; x-delivery-limit and dead-lettering to
exchange messenger.jobs.dlx fanout -> queue messenger.attachment-jobs.dlq (quorum)
Publisher side (relay): persistent message, `mandatory` (an unroutable message is returned, not
silently dropped), channel in confirm mode - `publish()` returns only after the broker has
written the message to the quorum log (publisher confirm). Consumer side (worker): manual ack
after the durable effect, prefetch = WORKER_CONCURRENCY.
The message carries IDs and service fields only (contracts/jobs.schema.json): no bytes, no URL,
no S3 key, no filename, no credentials. The worker takes every trusted detail from PostgreSQL.
"""
from __future__ import annotations
import datetime as dt
import json
import re
import ssl
import uuid
EXCHANGE = "messenger.jobs"
QUEUE = "messenger.attachment-jobs"
DLX = "messenger.jobs.dlx"
DLQ = "messenger.attachment-jobs.dlq"
ROUTING_KEY = "attachment.process.v1"
def ssl_context(settings) -> ssl.SSLContext | None:
"""Lab 7: amqps:// -> TLS context that verifies the broker (internal CA + hostname `broker`).
A plain amqp:// URL gets None and is refused by the broker anyway (its TCP listener is off)."""
if not settings.broker_url.startswith("amqps://"):
return None
from .tls import client_context
return client_context(settings.tls_ca_file)
JOB_TYPE = "attachment.process.v1"
MAX_MESSAGE_BYTES = 4096
REQUIRED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
OPTIONAL = {"traceparent", "tracestate"}
TRACEPARENT_RE = re.compile(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}")
DATETIME_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z")
class BadMessage(ValueError):
"""Not a valid job message (schema v1): dead-lettered, never processed."""
def rfc3339(value: dt.datetime) -> str:
return value.astimezone(dt.timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def encode(job_id: str, attachment_id: str, pipeline_version: int, attempt: int, created_at: dt.datetime,
trace_context: dict[str, str] | None = None) -> bytes:
"""Lab 6: `trace_context` = {"traceparent", "tracestate"} of the relay's PRODUCER span (the same
values also go into the AMQP headers; the worker reads the body fields, the schema's carrier)."""
body = {"schema_version": 1, "job_id": job_id, "type": JOB_TYPE, "attachment_id": attachment_id,
"pipeline_version": pipeline_version, "attempt": attempt, "created_at": rfc3339(created_at)}
for key in ("traceparent", "tracestate"):
value = (trace_context or {}).get(key)
if value:
body[key] = value
return json.dumps(body, separators=(",", ":")).encode()
def decode(raw: bytes) -> dict:
"""Strict check against contracts/jobs.schema.json (additionalProperties: false)."""
if len(raw) > MAX_MESSAGE_BYTES:
raise BadMessage("too large")
try:
body = json.loads(raw)
except (ValueError, UnicodeError):
raise BadMessage("not JSON") from None
if not isinstance(body, dict):
raise BadMessage("not an object")
keys = set(body)
if not REQUIRED <= keys or keys - REQUIRED - OPTIONAL:
raise BadMessage("wrong fields")
if body["schema_version"] != 1 or isinstance(body["schema_version"], bool) or body["type"] != JOB_TYPE:
raise BadMessage("unsupported schema/type")
for name in ("job_id", "attachment_id"):
if not isinstance(body[name], str):
raise BadMessage(name)
try:
uuid.UUID(body[name])
except ValueError:
raise BadMessage(name) from None
for name in ("pipeline_version", "attempt"):
value = body[name]
if not isinstance(value, int) or isinstance(value, bool) or value < 1:
raise BadMessage(name)
if not isinstance(body["created_at"], str) or not DATETIME_RE.fullmatch(body["created_at"]):
raise BadMessage("created_at")
if "traceparent" in body and not (isinstance(body["traceparent"], str) and TRACEPARENT_RE.fullmatch(body["traceparent"])):
raise BadMessage("traceparent")
if "tracestate" in body and not (isinstance(body["tracestate"], str) and len(body["tracestate"]) <= 512):
raise BadMessage("tracestate")
return body
+424
View File
@@ -0,0 +1,424 @@
"""Runtime configuration read from environment variables (12-factor style).
Non-secret settings have safe defaults. Connection strings with passwords are
read from files (`DATABASE_URL_FILE`, `CACHE_URL_FILE` → Docker secrets in
/run/secrets), so they never appear in `docker inspect`, compose files or logs.
Invalid values stop the process at startup with a clear message.
"""
from __future__ import annotations
import os
import re
import secrets
from dataclasses import dataclass, field
from pathlib import Path
class ConfigError(ValueError):
pass
INSTANCE_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")
_INSTANCE_ID: str | None = None
def _instance_id() -> str:
"""X-Instance-Id of this process (also service.instance.id, lease owner, broker connection name).
Lab 7 (contract, balancing): a RANDOM alias drawn at process start, e.g. `i-3f9a1c2b7d10`
(48 random bits) - it reveals neither the hostname/container ID nor an IP, is unique per process
and stable for its life. INSTANCE_ID overrides it (tests). The MAIN process of a service writes it
to INSTANCE_ID_FILE (publish_instance_id), so the operator can map alias -> container.
"""
global _INSTANCE_ID
if _INSTANCE_ID is None:
value = os.environ.get("INSTANCE_ID", "").strip() or "i-" + secrets.token_hex(6)
if INSTANCE_ID_RE.fullmatch(value) is None:
raise ConfigError("INSTANCE_ID must match [A-Za-z0-9._-]{1,64}")
_INSTANCE_ID = value
return _INSTANCE_ID
def publish_instance_id(instance_id: str) -> None:
"""Called by the service's main process only (api/relay/worker entry points): writes the alias to
INSTANCE_ID_FILE (compose: /tmp/instance_id inside the container) for
`docker exec <container> cat /tmp/instance_id` (scripts/stop-one.sh, lbctl.py). A helper process
started in the same container (docker compose exec ... python) must not overwrite it."""
target = os.environ.get("INSTANCE_ID_FILE", "").strip()
if target:
Path(target).write_text(instance_id + "\n", encoding="ascii")
def _int(name: str, default: int, low: int, high: int) -> int:
raw = os.environ.get(name)
if raw is None or raw.strip() == "":
return default
try:
value = int(raw.strip())
except ValueError:
raise ConfigError(f"{name} must be an integer, got {raw!r}") from None
if not low <= value <= high:
raise ConfigError(f"{name} must be in [{low}, {high}], got {value}")
return value
def _float(name: str, default: float, low: float, high: float) -> float:
raw = os.environ.get(name)
if raw is None or raw.strip() == "":
return default
try:
value = float(raw.strip())
except ValueError:
raise ConfigError(f"{name} must be a number, got {raw!r}") from None
if not low <= value <= high:
raise ConfigError(f"{name} must be in [{low}, {high}], got {value}")
return value
def _bool(name: str, default: bool) -> bool:
raw = os.environ.get(name, "").strip().lower()
if raw == "":
return default
if raw not in {"true", "false", "1", "0"}:
raise ConfigError(f"{name} must be true/false, got {raw!r}")
return raw in {"true", "1"}
def _choice(name: str, default: str, allowed: set[str]) -> str:
value = os.environ.get(name, "").strip().lower() or default
if value not in allowed:
raise ConfigError(f"{name} must be one of {sorted(allowed)}, got {value!r}")
return value
def _secret(name: str, required: bool) -> str:
"""Value of a secret setting, in this order:
1. OpenBao (lab 7, BAO_ADDR set): key name.lower() of the service's KV path (bao.py);
2. <NAME>_FILE (Docker secret file: bootstrap jobs and operator tools);
3. <NAME> (local runs/tests)."""
from . import bao
if bao.enabled():
try:
values = bao.fetch()
except bao.BaoError as exc:
raise ConfigError(str(exc)) from None
if name.lower() in values:
return values[name.lower()]
path = os.environ.get(f"{name}_FILE", "").strip()
if path:
try:
value = Path(path).read_text(encoding="utf-8").strip()
except OSError as exc:
# The message names the file, never its content.
raise ConfigError(f"{name}_FILE={path} cannot be read: {exc.strerror}") from None
else:
value = os.environ.get(name, "").strip()
if required and not value:
raise ConfigError(f"{name}_FILE (or {name}) must be set")
return value
@dataclass(frozen=True)
class Settings:
host: str
port: int
env: str
log_level: str
shutdown_timeout: float
max_body_bytes: int
docs_enabled: bool = True
database_url: str = ""
session_store: str = "postgres"
cache_url: str = ""
session_ttl_seconds: int = 3600
db_pool_min: int = 1
db_pool_max: int = 10
db_timeout_seconds: float = 3.0
cache_timeout_seconds: float = 0.5
cache_pool_size: int = 8
hash_concurrency: int = 2
instance_id: str = "local"
drain_seconds: float = 0.0
idempotency_ttl_seconds: int = 86400
stats_log_seconds: float = 0.0
message_write_path: str = "function"
# Lab 4: private S3 bucket and attachment limits (see storage.py, attachments.py).
s3_endpoint: str = "http://s3:8333"
s3_region: str = "us-east-1"
s3_bucket: str = "messenger-attachments"
s3_access_key_id: str = ""
s3_secret_access_key: str = ""
s3_timeout_seconds: float = 3.0
s3_connect_timeout_seconds: float = 1.0
s3_max_connections: int = 20
max_upload_bytes: int = 10 * 1024 * 1024
max_image_pixels: int = 40_000_000
upload_concurrency: int = 4
upload_queue_timeout_seconds: float = 5.0
upload_read_timeout_seconds: float = 30.0
image_verify_timeout_seconds: float = 10.0
image_verify_concurrency: int = 1
jpeg_max_memory_mb: int = 256
pending_grace_seconds: int = 900
janitor_interval_seconds: float = 60.0
# Lab 5: staging bucket (API writes, worker reads) and the asynchronous pipeline (jobs_settings()).
s3_staging_bucket: str = "messenger-staging"
broker_url: str = ""
pipeline_version: int = 1
job_max_attempts: int = 5
job_timeout_seconds: float = 60.0
job_lease_seconds: float = 30.0
job_retry_base_seconds: float = 2.0
job_retry_max_seconds: float = 60.0
worker_concurrency: int = 2
worker_shutdown_seconds: float = 20.0
image_max_memory_mb: int = 768
staging_retention_seconds: int = 86400
orphan_grace_seconds: int = 600
cleanup_interval_seconds: float = 30.0
relay_poll_seconds: float = 0.5
relay_batch: int = 50
queued_republish_seconds: float = 300.0
fault_points: frozenset[str] = frozenset()
fault_values: dict[str, int] = field(default_factory=dict)
# Lab 7: TLS of the API listener (mTLS, src/messenger/tls.py) and the loopback health port.
tls_cert_file: str = ""
tls_key_file: str = ""
# CA that every OUTGOING TLS connection verifies the server with (internal CA): S3, Valkey,
# RabbitMQ (PostgreSQL: sslrootcert in DATABASE_URL, OTLP: OTEL_EXPORTER_OTLP_CERTIFICATE).
tls_ca_file: str = ""
tls_client_ca_file: str = ""
health_port: int = 0
# Lab 7: Argon2id parameters (passwords.py) and the login rate limit (ratelimit.py).
argon2_memory_kib: int = 19456
argon2_iterations: int = 2
argon2_parallelism: int = 1
login_user_limit: int = 5
login_user_window_seconds: int = 60
login_ip_limit: int = 50
login_ip_window_seconds: int = 300
def fault_value(self, point: str, default: int = 0) -> int:
return self.fault_values.get(point, default)
@property
def db_statement_timeout_ms(self) -> int:
# The server stops a statement a bit before the client-side deadline fires.
return max(100, int(self.db_timeout_seconds * 1000) - 500)
@classmethod
def from_env(cls, *, s3_credentials: bool = True) -> "Settings":
"""s3_credentials=False: processes without S3 access (relay, jobctl)."""
log_level = os.environ.get("LOG_LEVEL", "info").strip().lower() or "info"
if log_level not in {"debug", "info", "warning", "error"}:
raise ConfigError(f"LOG_LEVEL must be debug/info/warning/error, got {log_level!r}")
session_store = os.environ.get("SESSION_STORE", "postgres").strip().lower() or "postgres"
if session_store == "redis":
session_store = "valkey" # same protocol; the course allows Redis OR Valkey
if session_store not in {"postgres", "valkey"}:
raise ConfigError(f"SESSION_STORE must be postgres or valkey, got {session_store!r}")
db_pool_min = _int("DB_POOL_MIN", 1, 0, 50)
db_pool_max = _int("DB_POOL_MAX", 10, 1, 100)
if db_pool_min > db_pool_max:
raise ConfigError("DB_POOL_MIN must not exceed DB_POOL_MAX")
return cls(
host=os.environ.get("APP_HOST", "0.0.0.0").strip() or "0.0.0.0",
port=_int("APP_PORT", 8080, 1, 65535),
env=os.environ.get("APP_ENV", "lab").strip() or "lab",
log_level=log_level,
# DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS must stay below compose stop_grace_period.
shutdown_timeout=_float("SHUTDOWN_TIMEOUT_SECONDS", 8.0, 0.0, 30.0),
max_body_bytes=_int("MAX_BODY_BYTES", 64 * 1024, 1024, 1024 * 1024),
docs_enabled=_bool("DOCS_ENABLED", True),
database_url=_secret("DATABASE_URL", required=True),
session_store=session_store,
cache_url=_secret("CACHE_URL", required=session_store == "valkey"),
# Contract name. Minimum 1 s so the expiry test can use 2 s.
session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600),
db_pool_min=db_pool_min,
db_pool_max=db_pool_max,
db_timeout_seconds=_float("DB_TIMEOUT_SECONDS", 3.0, 0.5, 30.0),
cache_timeout_seconds=_float("CACHE_TIMEOUT_SECONDS", 0.5, 0.05, 10.0),
cache_pool_size=_int("CACHE_POOL_SIZE", 8, 1, 200),
hash_concurrency=_int("PASSWORD_HASH_CONCURRENCY", 2, 1, 16),
instance_id=_instance_id(),
# After SIGTERM: readiness is 503 but requests are still served for this long,
# so the load balancer stops routing here before the listener closes.
drain_seconds=_float("DRAIN_SECONDS", 0.0, 0.0, 10.0),
# Contract: a replay within 24 h returns the original result.
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 86400, 30 * 24 * 3600),
# Experiments (bench/track1): log DB pool counters and process CPU every N s; 0 = off.
stats_log_seconds=_float("STATS_LOG_SECONDS", 0.0, 0.0, 60.0),
# Track 1: `function` = one SQL call per send (migration 0003), `multi` = the previous
# multi-statement transaction; both have identical semantics (A/B on one image).
message_write_path=_choice("MESSAGE_WRITE_PATH", "function", {"function", "multi"}),
**s3_settings(credentials_required=s3_credentials),
**jobs_settings(broker_required=False),
**tls_settings(),
# OWASP minimum for Argon2id is m=19 MiB, t=2, p=1: never configurable below it.
argon2_memory_kib=_int("ARGON2_MEMORY_KIB", 19456, 19456, 1024 * 1024),
argon2_iterations=_int("ARGON2_ITERATIONS", 2, 2, 20),
argon2_parallelism=_int("ARGON2_PARALLELISM", 1, 1, 8),
# Failed logins: per username (brute force of one account) and per client IP (spraying
# many accounts), fixed windows in Valkey, shared by all replicas.
login_user_limit=_int("LOGIN_RATE_LIMIT_USER", 5, 1, 1000),
login_user_window_seconds=_int("LOGIN_RATE_LIMIT_USER_WINDOW_SECONDS", 60, 1, 86400),
login_ip_limit=_int("LOGIN_RATE_LIMIT_IP", 50, 1, 100000),
login_ip_window_seconds=_int("LOGIN_RATE_LIMIT_IP_WINDOW_SECONDS", 300, 1, 86400),
)
# Contract limits (contracts/README.md): configurable DOWN for experiments, never above them.
CONTRACT_MAX_UPLOAD_BYTES = 10 * 1024 * 1024
CONTRACT_MAX_IMAGE_PIXELS = 40_000_000
# Failure points for the experiments only (FAULT_POINTS of ONE service, compose variables
# API_/RELAY_/WORKER_FAULT_POINTS); empty in normal runs. `name` or `name=<integer>`.
FAULT_POINTS = {
# API, upload: between the staging PUT and the job COMMIT / after the job COMMIT, before 202.
"after_s3_put", "after_enqueue_commit",
# Relay: crash after the broker confirmed a publish but before outbox.published_at is
# committed; publish every message twice; publish a batch in reverse order.
"crash_after_publish", "duplicate_publish", "reverse_order",
# Worker: crash after the claim (before any side effect), after the S3 writes (before the
# result COMMIT), after the result COMMIT (before the ack); transient failure of the first N
# attempts; permanent failure; slow processing (N s, lease kept alive) of every job or only of
# pipeline version `slow_pipeline`; hang: stop the heartbeat and sleep N s inside processing.
"crash_after_claim", "crash_after_s3_write", "crash_after_commit", "transient_error", "permanent_error",
"slow", "slow_pipeline", "hang",
# Worker cleanup: pause N s after reading the candidates, before locking/deleting them.
"pause_cleanup",
# Lab 6 (API, POST /chats/{chat_id}/messages only): slow handler code (N ms of work outside the
# database: the trace shows a long server span WITHOUT a long child span - incident 2 contrast);
# rare server errors (N per mille answered 503) and rare slow requests (N per mille + 500 ms)
# for track 1 (what sampling keeps of rare events).
"slow_handler", "random_5xx", "random_slow",
}
def _faults() -> tuple[frozenset[str], dict[str, int]]:
names, values = set(), {}
for item in os.environ.get("FAULT_POINTS", "").split(","):
name, _, raw = item.strip().partition("=")
if not name:
continue
if name not in FAULT_POINTS:
raise ConfigError(f"FAULT_POINTS may contain only {sorted(FAULT_POINTS)}")
if raw:
if not raw.isdigit():
raise ConfigError(f"FAULT_POINTS value of {name} must be an integer")
values[name] = int(raw)
names.add(name)
return frozenset(names), values
def _bucket(name: str, default: str) -> str:
bucket = os.environ.get(name, default).strip() or default
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
raise ConfigError(f"{name} is not a valid bucket name: {bucket!r}")
return bucket
def s3_settings(*, credentials_required: bool = True) -> dict:
"""S3 part of Settings; also used by the bootstrap CLI with its own keys."""
faults, fault_values = _faults()
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:8333").strip() or "http://s3:8333"
if not re.fullmatch(r"https?://[A-Za-z0-9.\-]+(:[0-9]{1,5})?/?", endpoint):
raise ConfigError(f"S3_ENDPOINT must be http(s)://host[:port], got {endpoint!r}")
bucket = _bucket("S3_BUCKET", "messenger-attachments")
staging = _bucket("S3_STAGING_BUCKET", "messenger-staging")
if staging == bucket:
raise ConfigError("S3_STAGING_BUCKET must differ from S3_BUCKET")
return dict(
s3_endpoint=endpoint,
s3_region=os.environ.get("S3_REGION", "us-east-1").strip() or "us-east-1",
s3_bucket=bucket,
s3_staging_bucket=staging,
s3_access_key_id=_secret("S3_ACCESS_KEY_ID", required=credentials_required),
s3_secret_access_key=_secret("S3_SECRET_ACCESS_KEY", required=credentials_required),
s3_timeout_seconds=_float("S3_TIMEOUT_SECONDS", 3.0, 0.2, 30.0),
s3_connect_timeout_seconds=_float("S3_CONNECT_TIMEOUT_SECONDS", 1.0, 0.1, 10.0),
s3_max_connections=_int("S3_MAX_CONNECTIONS", 20, 1, 200),
max_upload_bytes=_int("MAX_UPLOAD_BYTES", CONTRACT_MAX_UPLOAD_BYTES, 1024, CONTRACT_MAX_UPLOAD_BYTES),
max_image_pixels=_int("MAX_IMAGE_PIXELS", CONTRACT_MAX_IMAGE_PIXELS, 1, CONTRACT_MAX_IMAGE_PIXELS),
# At most this many request bodies of one replica are buffered/checked at once (RAM bound:
# UPLOAD_CONCURRENCY x MAX_UPLOAD_BYTES); further uploads wait, then get 503.
upload_concurrency=_int("UPLOAD_CONCURRENCY", 4, 1, 64),
upload_queue_timeout_seconds=_float("UPLOAD_QUEUE_TIMEOUT_SECONDS", 5.0, 0.0, 60.0),
upload_read_timeout_seconds=_float("UPLOAD_READ_TIMEOUT_SECONDS", 30.0, 1.0, 300.0),
image_verify_timeout_seconds=_float("IMAGE_VERIFY_TIMEOUT_SECONDS", 10.0, 1.0, 120.0),
# Full checks running at once per replica: a strict JPEG decode of a 40 Mpx progressive
# file needs up to ~120-240 MB of coefficient buffers (capped by JPEG_MAX_MEMORY_MB).
image_verify_concurrency=_int("IMAGE_VERIFY_CONCURRENCY", 1, 1, 16),
jpeg_max_memory_mb=_int("JPEG_MAX_MEMORY_MB", 256, 16, 2048),
# An intent row still `pending` after this long belongs to a failed upload: the janitor
# deletes its object and the row. Far above the longest possible upload (~45 s).
pending_grace_seconds=_int("PENDING_GRACE_SECONDS", 900, 1, 7 * 24 * 3600),
janitor_interval_seconds=_float("JANITOR_INTERVAL_SECONDS", 60.0, 0.0, 3600.0),
fault_points=faults,
fault_values=fault_values,
tls_ca_file=_path("TLS_CA_FILE"),
)
def _path(name: str) -> str:
"""Optional file path setting; if set, the file must exist (fail at start, not at first use)."""
value = os.environ.get(name, "").strip()
if value and not Path(value).is_file():
raise ConfigError(f"{name}={value} does not exist")
return value
def tls_settings() -> dict:
"""Lab 7, API listener: TLS_CERT_FILE/TLS_KEY_FILE = the replica's certificate (SAN `api`),
TLS_CLIENT_CA_FILE = the internal CA that client certificates must chain to. All three or none."""
cert, key, ca = _path("TLS_CERT_FILE"), _path("TLS_KEY_FILE"), _path("TLS_CLIENT_CA_FILE")
if any((cert, key, ca)) and not all((cert, key, ca)):
raise ConfigError("TLS_CERT_FILE, TLS_KEY_FILE and TLS_CLIENT_CA_FILE must be set together")
return dict(tls_cert_file=cert, tls_key_file=key, tls_client_ca_file=ca,
health_port=_int("APP_HEALTH_PORT", 0, 0, 65535))
def jobs_settings(*, broker_required: bool) -> dict:
"""Lab 5 pipeline: retries, lease, worker limits, cleanup, relay (docs/PIPELINE.md)."""
from .pipeline import PIPELINES # local import: pipeline.py imports nothing from here
timeout = _float("JOB_TIMEOUT_SECONDS", 60.0, 1.0, 600.0)
lease = _float("JOB_LEASE_SECONDS", 30.0, 2.0, 600.0)
base = _float("JOB_RETRY_BASE_SECONDS", 2.0, 0.0, 600.0)
cap = _float("JOB_RETRY_MAX_SECONDS", 60.0, 0.0, 3600.0)
if base > cap:
raise ConfigError("JOB_RETRY_BASE_SECONDS must not exceed JOB_RETRY_MAX_SECONDS")
orphan_grace = _int("ORPHAN_GRACE_SECONDS", 600, 1, 7 * 24 * 3600)
version = _int("PIPELINE_VERSION", 1, 1, 1000)
if version not in PIPELINES:
raise ConfigError(f"PIPELINE_VERSION must be one of {sorted(PIPELINES)}")
return dict(
broker_url=_secret("BROKER_URL", required=broker_required),
# Pipeline version of the jobs created by new uploads (track 2: versioned pipeline).
pipeline_version=version,
# Managed attempts (claims) per job before failed/retry_exhausted.
job_max_attempts=_int("JOB_MAX_ATTEMPTS", 5, 1, 100),
# Hard limit of ONE attempt: the image child process is killed, the lease is no longer renewed.
job_timeout_seconds=timeout,
# Lease of a claimed job, renewed by the heartbeat every lease/3 while the attempt runs.
job_lease_seconds=lease,
# Backoff of transient failures: full jitter, uniform(0, min(max, base * 2^(attempt-1))).
job_retry_base_seconds=base,
job_retry_max_seconds=cap,
# Jobs processed at once by ONE worker process = RabbitMQ prefetch (basic.qos).
worker_concurrency=_int("WORKER_CONCURRENCY", 2, 1, 32),
worker_shutdown_seconds=_float("WORKER_SHUTDOWN_SECONDS", 20.0, 0.0, 120.0),
# Address-space limit (RLIMIT_AS) of the child process that decodes/encodes ONE image.
image_max_memory_mb=_int("IMAGE_MAX_MEMORY_MB", 768, 128, 8192),
# Staging copy of a FAILED attachment is kept this long for a replay, then deleted.
staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400, 0, 30 * 24 * 3600),
# Objects of attempts that did not publish are deleted once the attempt ended this long ago.
orphan_grace_seconds=orphan_grace,
cleanup_interval_seconds=_float("CLEANUP_INTERVAL_SECONDS", 30.0, 0.0, 3600.0),
relay_poll_seconds=_float("RELAY_POLL_SECONDS", 0.5, 0.05, 60.0),
relay_batch=_int("RELAY_BATCH", 50, 1, 1000),
# A queued job whose message has not led to a claim for this long is published again
# (message lost in the broker, dead-lettered, purged): no accepted job waits forever.
queued_republish_seconds=_float("QUEUED_REPUBLISH_SECONDS", 300.0, 5.0, 86400.0),
)
+56
View File
@@ -0,0 +1,56 @@
"""Opaque keyset cursors.
A cursor encodes the sort key `(created_at, id)` of the last item on the page
plus the resource it belongs to, e.g. `v1|m|<chat_id>|<ts_us>|<message_id>`,
packed in URL-safe base64. The client treats it as an opaque string; the server
rejects cursors of another chat/user (400) and any non-canonical encoding.
"""
from __future__ import annotations
import base64
import re
from .errors import InvalidRequest
from .validation import UUID_RE
B64_RE = re.compile(r"[A-Za-z0-9_-]{1,512}")
TS_RE = re.compile(r"[0-9]{1,19}")
# Latest instant both Python datetime and PostgreSQL accept: 9999-12-31T23:59:59.999999Z.
MAX_TS_US = 253402300799999999
MESSAGES = "m"
CHATS = "c"
SortKey = tuple[int, str]
def encode(scope: str, owner_id: str, key: SortKey) -> str:
ts, item_id = key
raw = f"v1|{scope}|{owner_id}|{ts}|{item_id}".encode("ascii")
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def decode(cursor: str, scope: str, owner_id: str) -> SortKey:
"""Return the sort key stored in the cursor or raise InvalidRequest."""
bad = InvalidRequest("Неверный cursor")
if B64_RE.fullmatch(cursor) is None:
raise bad
try:
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)).decode("ascii")
except (ValueError, UnicodeDecodeError):
raise bad from None
parts = raw.split("|")
if len(parts) != 5 or parts[0] != "v1":
raise bad
_, got_scope, got_owner, ts, item_id = parts
if TS_RE.fullmatch(ts) is None or UUID_RE.fullmatch(item_id) is None or item_id != item_id.lower():
raise bad
key = (int(ts), item_id)
if key[0] > MAX_TS_US:
raise bad # out-of-range time must be 400, not an overflow (500) in datetime/SQL
if encode(got_scope, got_owner, key) != cursor:
raise bad # only the canonical form produced by the server is accepted
if got_scope != scope or got_owner != owner_id:
raise InvalidRequest("cursor относится к другому ресурсу")
return key
+171
View File
@@ -0,0 +1,171 @@
"""PostgreSQL access: a bounded connection pool and a hard deadline for every unit of work.
Three independent limits keep a request from hanging when the database misbehaves:
* pool `timeout` — waiting for a free connection (pool exhausted);
* server `statement_timeout` / `lock_timeout` — PostgreSQL itself cancels a slow
statement or a statement stuck behind a lock;
* client deadline — covers what the server cannot report, e.g. a
paused/frozen PostgreSQL container or a dead network.
The client deadline needs care. Every unit of work runs as its own task; at the deadline
the REQUEST stops waiting and gets 503 at once, but the task is NOT cancelled: cancelling a
psycopg query makes psycopg send a cancel request, and libpq starts that connection
(PQcancelStart) synchronously in the event-loop thread, resolving the host name first.
When the API has lost its network to PostgreSQL (lab 3 review scenario: `docker network
disconnect`), that blocked the WHOLE replica, /health/live included, for ~1 minute.
The abandoned task instead ends by itself, bounded by:
* TCP keepalives + `tcp_user_timeout` (= the deadline): a dead peer or a vanished network
breaks the socket within seconds, the connection is discarded by the pool;
* `statement_timeout` / `lock_timeout` on a live but slow server;
* a frozen (paused) server keeps the connection until it resumes; meanwhile new work waits
at most the pool timeout and gets 503.
Any failure becomes 503 `unavailable` — never 401, never a hang.
"""
from __future__ import annotations
import asyncio
import logging
import sys
import time
from collections.abc import Awaitable, Callable
from typing import TypeVar
import psycopg
from psycopg_pool import AsyncConnectionPool, PoolTimeout
from . import telemetry
from .config import Settings
from .errors import Unavailable
log = logging.getLogger("messenger.db")
T = TypeVar("T")
Work = Callable[[psycopg.AsyncConnection], Awaitable[T]]
# Errors that mean "the database is unavailable right now", not "the request is wrong".
# QueryCanceled (statement_timeout), LockNotAvailable (lock_timeout) and AdminShutdown
# (server restart) are subclasses of OperationalError.
UNAVAILABLE_ERRORS = (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout, TimeoutError)
def _forget(task: asyncio.Task) -> None:
"""Done-callback for abandoned tasks: retrieve the result so nothing is logged as 'never retrieved'."""
if not task.cancelled():
task.exception()
class Database:
def __init__(self, settings: Settings, name: str = "messenger-api"):
self.name = name
self.deadline = settings.db_timeout_seconds
options = (
f"-c statement_timeout={settings.db_statement_timeout_ms} "
f"-c lock_timeout={max(100, settings.db_statement_timeout_ms // 2)} "
"-c idle_in_transaction_session_timeout=10000"
)
self.pool = AsyncConnectionPool(
conninfo=settings.database_url,
min_size=settings.db_pool_min,
max_size=settings.db_pool_max,
timeout=settings.db_timeout_seconds, # max wait for a free connection
open=False,
name=name,
check=AsyncConnectionPool.check_connection, # drop connections broken by a DB restart
kwargs={
"options": options,
"connect_timeout": max(1, int(settings.db_timeout_seconds)),
"application_name": name, # visible in pg_stat_activity: api / relay / worker
# Autocommit connections: a single statement (post_message function, ping) is its
# own transaction with ONE round trip; multi-statement work uses an explicit
# conn.transaction() (BEGIN ... COMMIT), see run().
"autocommit": True,
# Detect a dead peer / lost network without any cancel request (see module doc).
"keepalives": 1,
"keepalives_idle": 5,
"keepalives_interval": 1,
"keepalives_count": 3,
"tcp_user_timeout": int(settings.db_timeout_seconds * 1000),
},
)
async def open(self) -> None:
# wait=False: the API starts (liveness 200) even if PostgreSQL is not up yet;
# readiness stays 503 until the database answers.
await self.pool.open(wait=False)
async def close(self) -> None:
await self.pool.close(timeout=2)
async def run(self, work: Work[T], deadline: float | None = None, *, transaction: bool = True,
op: str | None = None) -> T:
"""Run `work(conn)` in one transaction (COMMIT on success, ROLLBACK on any exception).
transaction=False: `work` issues exactly ONE statement, which autocommit makes atomic.
Domain errors raised by `work` (NotFound, Conflict, ...) propagate unchanged;
database unavailability and the deadline become Unavailable (503).
Lab 6: one CLIENT span `db <op>` per unit of work (only inside a traced request/job: no
root spans from background loops) with the pool wait as attribute
`db.client.connection.wait_time_ms`, plus the metrics db.client.operation.duration and
db.client.connection.wait_time. `op` defaults to the calling function's name (a fixed
set of code names, low cardinality); SQL text and parameters are never recorded.
"""
op = op or sys._getframe(1).f_code.co_name
parent_recording = telemetry.trace.get_current_span().is_recording()
async def unit() -> T:
begin = time.perf_counter()
span = (telemetry.TRACER.start_span(f"db {op}", kind=telemetry.SpanKind.CLIENT, attributes={
"db.system.name": "postgresql", "db.operation.name": op, "db.client.connection.pool.name": self.name})
if parent_recording else None)
outcome = "error"
try:
async with self.pool.connection() as conn:
waited = time.perf_counter() - begin
telemetry.db_wait.record(waited, {"db.client.connection.pool.name": self.name})
if span is not None:
span.set_attribute("db.client.connection.wait_time_ms", round(waited * 1000, 3))
if not transaction:
result = await work(conn)
else:
async with conn.transaction():
result = await work(conn)
outcome = "ok"
return result
except UNAVAILABLE_ERRORS as exc:
if span is not None:
telemetry.mark_error(span, type(exc).__name__)
raise
except Exception:
outcome = "domain" # NotFound/Conflict...: an answer, not a database failure
raise
finally:
telemetry.db_duration.record(time.perf_counter() - begin, {
"db.system.name": "postgresql", "db.operation.name": op, "outcome": outcome,
"db.client.connection.pool.name": self.name})
if span is not None:
span.end()
task = asyncio.ensure_future(unit()) # copies the context: the span's parent is the caller's span
try:
return await asyncio.wait_for(asyncio.shield(task), deadline or self.deadline)
except UNAVAILABLE_ERRORS as exc:
log.warning("database_unavailable", extra={"fields": {"error": type(exc).__name__, "op": op}})
raise Unavailable("База данных временно недоступна") from None
finally:
if not task.done():
# Deadline or cancelled request: stop waiting now. The task is left to finish
# on its own (no task.cancel(): that would trigger psycopg's blocking cancel).
task.add_done_callback(_forget)
async def ping(self, timeout: float = 1.0) -> bool:
async def select_one(conn: psycopg.AsyncConnection) -> None:
await conn.execute("SELECT 1")
try:
await self.run(select_one, deadline=timeout, transaction=False, op="ping")
return True
except Unavailable:
return False

Some files were not shown because too many files have changed in this diff Show More