ЛР 7 — БПИ2301 — Дугина — на 4 #83

Open
aleksandra_dugina wants to merge 1 commits from aleksandra_dugina/mtusi2026lab7:solution/BPI2301-Dugina into main
91 changed files with 10163 additions and 50 deletions
Showing only changes of commit 11390b65fd - Show all commits
+52
View File
@@ -2,8 +2,24 @@
.env
.env.*
!.env.example
.envrc
.netrc
.pgpass
.pg_service.conf
.aws/
.docker/
.ssh/
.kube/
.codex/
credentials.json
credentials.local.*
service-account*.json
secrets/
certs/local/
certs/private/
openbao-v2.json
openbao-v2.pending
openbao-v2.init-attempted
*.key
*.p12
*.pfx
@@ -13,10 +29,33 @@ certs/private/
volumes/
data/
backups/
# Local working files and raw scan output
/SECURITY_HANDOFF.md
tmp/
.tmp/
.local/
scan-output/
security-rescan/
trivy-cache/
*.tmp
*.temp
*.swp
*.swo
*~
*.bak
# Runtime/build artifacts
.venv/
.venv-*/
venv/
__pycache__/
*.py[cod]
.pytest_cache/
.mypy_cache/
.ruff_cache/
.tox/
.nox/
node_modules/
dist/
build/
@@ -24,7 +63,20 @@ target/
bin/
obj/
coverage/
.coverage
.coverage.*
htmlcov/
logs/
*.log
*.log.*
*.pid
*.sock
*.sqlite
*.sqlite3
*.sqlite-wal
*.sqlite-shm
*.sqlite3-wal
*.sqlite3-shm
.DS_Store
.idea/
.vscode/
+14
View File
@@ -0,0 +1,14 @@
FROM python:3.11.16-slim-bookworm@sha256:a36c24f9cbdf4fd0f52d67f0823eeac19c2028c637cecc392d97f980d4fec56b
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN python -m pip install --no-cache-dir -r requirements.txt && python -m pip check \
&& useradd --uid 10001 --no-create-home --shell /usr/sbin/nologin appuser
COPY src/ ./src/
COPY scripts/uds_probe.py /app/uds_probe.py
COPY db/ ./db/
COPY contracts/openapi.json ./contracts/openapi.json
USER 10001:10001
STOPSIGNAL SIGTERM
CMD ["python", "-m", "uvicorn", "src.main:app", "--uds", "/run/api/api.sock", "--no-access-log", "--no-proxy-headers", "--timeout-graceful-shutdown", "5"]
+97 -23
View File
@@ -1,37 +1,111 @@
# Отчёт — лабораторная 7
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Автор — Дугина Александра, БПИ2301.
- Цель — оценка 4.
- Ветка — `solution/BPI2301-Dugina`.
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
## Воспроизведение
## Архитектура и решения
Нужны Docker Compose с поддержкой `!override`, Python 3.11+, OpenSSL и
`requirements-dev.txt` для OpenAPI. Приложение собрано на Python 3.11 Bookworm,
управляющие команды повторного прогона выполнены на Python 3.13.
Версии образов указаны в [Compose](compose.yaml), [Dockerfile](Dockerfile)
и [Dockerfile наблюдаемости](infra/otel/Dockerfile).
Основной стенд запускается через `sh scripts/bootstrap.sh`. Операторский
OpenBao bootstrap и восстановление после рестарта описаны в
[runbook](infra/runbooks.md). Остановка без удаления данных — `./scripts/compose.sh stop`.
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
Следующие команды воспроизводят испытания из корня проекта.
## Доказательства критериев
```sh
export COMPOSE_PROJECT_NAME="lab7-grade4-$(date +%s)"
export COMPOSE_FILE=compose.yaml:student-tests/grade4.compose.yaml
export LAB7_STATE="$(mktemp -d)/state"
export LAB7_IMAGE_PREFIX="$COMPOSE_PROJECT_NAME"
export LAB7_OPENBAO_URL=https://localhost:28200
sh scripts/bootstrap.sh
export CA_FILE="$LAB7_STATE/trust/ca.crt"
make test test-security BASE_URL=https://localhost:28443
./scripts/compose.sh run --rm -T probe matrix
python3 student-tests/observability.py signals --base-url https://localhost:28443 --grafana https://localhost:23007
for scenario in db leaf login rehash log-hygiene login-recovery sealed; do
python3 student-tests/grade4_probe.py "$scenario" || break
done
make test-persistence BASE_URL=https://localhost:28443 ACTION_SCRIPT=scripts/restart.sh
make test-failover BASE_URL=https://localhost:28443 ACTION_SCRIPT=scripts/stop-one.sh
./scripts/compose.sh start api-a api-b
PIPELINE_FAULTS=1 python3 student-tests/pipeline.py --disposable --base-url https://localhost:28443
PIPELINE_FAULTS=0 ./scripts/compose.sh up -d --wait --no-deps publisher worker recovery
RECOVERY_TEST_APP_IMAGE="$LAB7_IMAGE_PREFIX-app:local" sh student-tests/recovery-test.sh
./scripts/compose.sh stop
```
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
Схема доверия, порты, identities и срок действия описаны в
[contracts/trust-matrix.md](contracts/trust-matrix.md). PostgreSQL хранит
сессии, лимит входа, состояния jobs и ссылку на опубликованный объект.
MinIO хранит байты. HAProxy передаёт HTTP в Uvicorn через Unix socket после
mTLS. OpenBao выдаёт приложению ограниченный KV по cert auth, операторский
токен и Shamir shares остаются вне приложения. Сценарии противодействия
описаны в [security/THREAT_MODEL.md](security/THREAT_MODEL.md).
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
## Доказательства
## Эксперименты и отказы
| Требование README | Где проверено |
| --- | --- |
| Уровень 3. HTTPS, предыдущий API и данные, Argon2id | HTTPS smoke, persistence, отказ обеих реплик по очереди, тесты pipeline и бюджет Argon2id ниже. |
| Уровень 3. TLS и LB→API mTLS, ограниченные роли и OpenBao | TLS-матрица, scoped KV и запрет прямого TCP-доступа к Uvicorn. Постоянное состояние OpenBao хранится в Raft, доступ приложений через cert auth. |
| Уровень 3. Ограничения контейнеров, запросов и входа, ACL и время жизни сессии | Hardening, smoke, логин и проверка expiry. Лимит загрузки 10 MiB. |
| Уровень 4. Раздельные mTLS identities для AMQP и OTLP | TLS-матрица отклоняет отсутствующий сертификат, чужой CA и постороннюю identity того же CA. AMQP проверяет права publisher/consumer отдельно. |
| Уровень 4. Rehash, хеш сессии, защита от login DoS | Argon2id с индивидуальной солью, SHA-256 случайного bearer в PostgreSQL, общий admission budget и ограничение параллельных KDF. Проверены rehash, 429/Retry-After и отсутствие credentials в ошибках и telemetry. |
| Уровень 4. Ротация рабочего секрета и leaf, expiry и seal | DB и leaf rotation, OpenBao seal/unseal и ограниченный по времени snapshot. Bootstrap и renewal описаны в runbook и матрице. |
| Уровень 4. Hardening и применимость результатов сканирования | Эффективная конфигурация 25 сервисов, результаты pip-audit и Trivy ниже. |
| Уровень 4. Модель угроз, upload-worker и полный TLS-аудит | Девять угроз с контрольными сценариями в модели. Worker ограничен 1 CPU и 768 MiB на реплику. Процесс рендера ограничен 512 MiB адресного пространства, мягким и жёстким лимитами CPU 15 и 16 с и тайм-аутом 20 с по настенным часам. TLS-матрица, проверка ACL и логов/трасс дополняют тесты рендера. |
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
| Проверка | Наблюдение |
| --- | --- |
| `make test`, `make test-security` | Сквозной HTTPS API и данные вложения; ACL, logout, отклонение недоверенного CA. |
| `probe matrix` | TLS hostname, запрет plaintext на проверенных портах, mTLS/identity для API, RabbitMQ и Collector. PostgreSQL SCRAM/TLS и отказ без TLS, S3 ACL, OpenBao scoped KV, renew-self и deny чужой policy, telemetry backends и Grafana datasource proxy. |
| `grade4_probe.py db` | Обе реплики перешли на новый KV/DB role. Старый пароль отклонён. Во время ротации 42 аутентифицированных GET, все 200. |
| `grade4_probe.py leaf` | Проверены CA, SAN и новый leaf, старый отклонён обеими API-репликами. Во время ротации 174 GET, все 200. |
| `grade4_probe.py login` | Лимит 40 на 10 секунд общий для обеих реплик, 40 допущенных и 40 получили 429 с Retry-After. Из 80 синтетических запросов с неверным паролем 8 дали 401 после KDF, 72 получили 429 за 1,154 с при 12 клиентах. |
| `grade4_probe.py rehash` | Успешный вход обновил сохранённый профиль Argon2id. |
| `grade4_probe.py log-hygiene` | Синтетические пароль, bearer и Basic payload отсутствуют в контейнерных логах и коррелированных записях Loki/Tempo; просроченный bearer получил 401. |
| `grade4_probe.py login-recovery` | При остановке PostgreSQL обе API-реплики вернули 503 на login, после запуска допуск восстановился. |
| `grade4_probe.py sealed` | После seal OpenBao доступ закрывается по истечении snapshot. После unseal готовность восстанавливается. |
| `make test-persistence` | Перезапуск OpenBao, PostgreSQL, S3, RabbitMQ и процессов приложения сохранил подтверждённые данные, старую сессию и исходник. |
| `make test-failover` | Повторный тест остановки API-B сохранил данные и сессию. 111 успешных записей, 7 переходных ошибок, первая восстановленная запись через 2,192 с. До обновления отдельно проверены API-A (115 записей, 6 ошибок, 2,381 с) и API-B (117 записей, 5 ошибок, 1,764 с). |
| `sh student-tests/recovery-test.sh` | 13 тестов (8 unit и 5 integration) прошли с обновлённым образом приложения и PostgreSQL. Два процесса не дублируют recovery, cleanup сохраняет используемый staging и опубликованный объект. |
| `PIPELINE_FAULTS=1 python3 student-tests/pipeline.py --disposable --base-url https://localhost:28443` | 15 сценариев прошли, включая отказы до/после S3, fencing, повторную доставку, смену версии и рестарт с очередью. Тестовые права на `pipeline_faults` отозваны после прогона. |
| `python3 -m unittest discover -s student-tests -p test_grade4_unit.py` | 4 проверки CAS, остановки ротации и privilege gate. |
| `student-tests/render.py` в app image | Проверены границы JPEG/PNG, отказ TIFF, MIME, pixel cap, геометрия и EXIF на этапе подготовки обновления. |
| `student-tests/observability.py signals` | После обновления прошла проверка метрик Prometheus, логов Loki и трасс Tempo через Grafana. [Результат проверки](evidence/signals.json). |
| `tests/load.py --duration 10 --concurrency 4` | Замер до обновления зависимостей. 1417 успешных POST сообщений, 0 ошибок, 141,357 RPS. p50/p95/p99 — 26,057/46,482/69,392 мс. Closed-loop без повторов, перцентили успешных запросов. |
| `make check validate` | Проверены структура проекта, локальные ссылки и схема OpenAPI 3.1. |
| `scripts/check-hardening.py` и runtime UID | 25 Compose-сервисов проверены. API и Worker работают с UID 10001, PID 1 PostgreSQL и RabbitMQ — с UID 999 после entrypoint. |
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
## Ограничения и следующие шаги
Логи повторного прогона сохранены локально в
`/private/tmp/lab7-security-regression`. После pipeline отключена инъекция
сбоев и подтверждён отзыв тестовых прав publisher и worker. В изолированном
проекте остановлены 24 из 24 контейнеров, список из 10 томов совпал до и
после остановки.
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
Argon2id измерялся командой
`./scripts/compose.sh exec -T api-a python - < student-tests/argon2_budget.py`
до обновления зависимостей в Linux ARM64 Docker Desktop. Лимит API — 1 CPU и 768 MiB. Argon2id использует
64 MiB на операцию, 3 прохода, 4 lanes, до двух KDF одновременно на процесс.
В 24 замерах после одного прогрева p50 составил 372,0 мс, p95 — 492,8 мс,
пиковый RSS процесса — 194 860 KiB. Это измерение бюджета KDF и один burst, поэтому оно
не устанавливает максимальную пропускную способность всего стенда.
```sh
export SCAN_OUTPUT="$(mktemp -d)"
sh scripts/security-scan.sh
python3 scripts/summarize-security.py "$SCAN_OUTPUT"
```
Испытания покрывают перезапуски сервисов и потерю одной API-реплики на одном
Docker-хосте. Потеря Docker-хоста, БД или балансировщика как постоянный отказ
выходят за рамки испытаний.
+883
View File
@@ -0,0 +1,883 @@
name: mtusi2026lab7
services:
postgres:
image: postgres:16.16-bookworm@sha256:cd0e9518bda5f2ea667ff84d22795d089720c883f288e215d97ce57437e8ef37
networks:
- db
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/postgres:/run/identity:ro
- postgres_data:/var/lib/postgresql/data
- ./infra/postgres:/lab:ro
restart: unless-stopped
security_opt:
- no-new-privileges:true
mem_limit: 512m
cpus: 0.75
pids_limit: 256
environment:
POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/identity/admin
entrypoint:
- /bin/sh
- /lab/start.sh
tmpfs:
- /run/postgres-tls
- /tmp
healthcheck:
test:
- CMD-SHELL
- pg_isready -h 127.0.0.1 -d messenger -U migrator
interval: 3s
timeout: 4s
retries: 25
start_period: 10s
s3:
image: bitnamilegacy/minio:2025.7.23-debian-12-r5@sha256:6dabb4a2088c9a79908de3bc05f4586c23ad2182c8908e7e3acbf61c1467fb20
networks:
- objects
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/s3:/run/identity:ro
- s3_data:/data
restart: unless-stopped
security_opt:
- no-new-privileges:true
mem_limit: 512m
cpus: 0.75
pids_limit: 256
entrypoint:
- /opt/bitnami/minio/bin/minio
command:
- server
- /data
- --certs-dir
- /run/identity
- --console-address
- :9001
environment:
MINIO_ROOT_USER: labroot
MINIO_ROOT_PASSWORD_FILE: /run/identity/admin
healthcheck:
test:
- CMD
- curl
- -fsS
- --cacert
- /run/trust/ca.crt
- --resolve
- s3:9000:127.0.0.1
- https://s3:9000/minio/health/live
interval: 3s
timeout: 4s
retries: 25
start_period: 10s
user: 1001:0
depends_on:
volume-init:
condition: service_completed_successfully
s3-bootstrap:
user: 1001:0
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 128m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: bitnamilegacy/minio:2025.7.23-debian-12-r5@sha256:6dabb4a2088c9a79908de3bc05f4586c23ad2182c8908e7e3acbf61c1467fb20
networks:
- objects
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/s3:/run/identity:ro
- ./infra/minio:/lab:ro
entrypoint:
- /bin/sh
- /lab/bootstrap.sh
depends_on:
s3:
condition: service_healthy
profiles:
- bootstrap
broker:
image: rabbitmq:4.1.8-management@sha256:8699e1329a59f86824f92d0fbb74d2ff8bc86e1a190d3e165cceb0f22e21bbb0
networks:
- queue
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/broker:/run/identity:ro
- broker_data:/var/lib/rabbitmq
- ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
- ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
- ./infra/rabbitmq:/lab:ro
restart: unless-stopped
security_opt:
- no-new-privileges:true
mem_limit: 512m
cpus: 0.75
pids_limit: 256
hostname: broker
healthcheck:
test:
- CMD
- rabbitmq-diagnostics
- -q
- check_running
interval: 3s
timeout: 4s
retries: 25
start_period: 20s
openbao:
image: ghcr.io/openbao/openbao:2.7.3
networks:
- secrets
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/openbao:/run/identity:ro
- openbao_data_v2:/openbao/data
- ./infra/openbao:/lab:ro
restart: unless-stopped
security_opt:
- no-new-privileges:true
mem_limit: 512m
cpus: 0.75
pids_limit: 256
entrypoint:
- bao
command:
- server
- -config=/lab/server.hcl
ports:
- 127.0.0.1:18200:8200
environment:
BAO_ADDR: https://localhost:8200
BAO_CACERT: /run/trust/ca.crt
healthcheck:
test:
- CMD
- bao
- status
interval: 3s
timeout: 4s
retries: 25
start_period: 10s
cap_drop:
- ALL
user: "100:1000"
depends_on:
volume-init:
condition: service_completed_successfully
migrate:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 256m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-app:local
build: .
networks:
- db
environment:
DATABASE_URL_FILE: /run/identity/dsn
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/migrator:/run/identity:ro
command:
- python
- -m
- src.migrate
depends_on:
postgres:
condition: service_healthy
ops:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 256m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-app:local
networks:
- db
- queue
profiles:
- ops
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/ops:/run/identity:ro
environment:
DATABASE_URL_FILE: /run/identity/dsn
TLS_CA_FILE: /run/trust/ca.crt
entrypoint:
- python
- -m
- src.operator
api-a:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 768m
cpus: 1.0
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-app:local
networks:
- db
- objects
- secrets
- otlp
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/api-a:/run/identity:ro
- api-a_socket:/run/api
environment:
TLS_CA_FILE: /run/trust/ca.crt
BAO_ADDR: https://openbao:8200
BAO_ROLE: api-a
CREDENTIAL_MAX_AGE: ${CREDENTIAL_MAX_AGE:-30}
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/trust/ca.crt
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/otel.crt
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/otel.key
PIPELINE_FAULTS: ${PIPELINE_FAULTS:-0}
BAO_SCOPE: api
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
LOGIN_WINDOW_LIMIT: ${LOGIN_WINDOW_LIMIT:-40}
LOGIN_WINDOW_SECONDS: ${LOGIN_WINDOW_SECONDS:-10}
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-65536}
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-3}
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-4}
restart: unless-stopped
depends_on:
migrate:
condition: service_completed_successfully
s3:
condition: service_healthy
openbao:
condition: service_healthy
healthcheck:
test:
- CMD
- python
- /app/uds_probe.py
interval: 3s
timeout: 4s
retries: 25
start_period: 10s
api-a-tls:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 128m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: haproxy:3.0.32-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3
command: ["haproxy", "-W", "-db", "-f", "/usr/local/etc/haproxy/haproxy.cfg"]
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/api-a-tls:/run/identity:ro
- ./infra/tls/api.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
- api-a_socket:/run/api
restart: unless-stopped
networks:
- edge
api-b:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 768m
cpus: 1.0
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-app:local
networks:
- db
- objects
- secrets
- otlp
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/api-b:/run/identity:ro
- api-b_socket:/run/api
environment:
TLS_CA_FILE: /run/trust/ca.crt
BAO_ADDR: https://openbao:8200
BAO_ROLE: api-b
CREDENTIAL_MAX_AGE: ${CREDENTIAL_MAX_AGE:-30}
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/trust/ca.crt
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/otel.crt
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/otel.key
PIPELINE_FAULTS: ${PIPELINE_FAULTS:-0}
BAO_SCOPE: api
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
LOGIN_WINDOW_LIMIT: ${LOGIN_WINDOW_LIMIT:-40}
LOGIN_WINDOW_SECONDS: ${LOGIN_WINDOW_SECONDS:-10}
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-65536}
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-3}
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-4}
restart: unless-stopped
depends_on:
migrate:
condition: service_completed_successfully
s3:
condition: service_healthy
openbao:
condition: service_healthy
healthcheck:
test:
- CMD
- python
- /app/uds_probe.py
interval: 3s
timeout: 4s
retries: 25
start_period: 10s
api-b-tls:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 128m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: haproxy:3.0.32-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3
command: ["haproxy", "-W", "-db", "-f", "/usr/local/etc/haproxy/haproxy.cfg"]
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/api-b-tls:/run/identity:ro
- ./infra/tls/api.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
- api-b_socket:/run/api
restart: unless-stopped
networks:
- edge
publisher:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 384m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-app:local
networks:
- db
- queue
- secrets
- otlp
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/publisher:/run/identity:ro
environment:
TLS_CA_FILE: /run/trust/ca.crt
BAO_ADDR: https://openbao:8200
BAO_ROLE: publisher
CREDENTIAL_MAX_AGE: ${CREDENTIAL_MAX_AGE:-30}
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/trust/ca.crt
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/otel.crt
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/otel.key
PIPELINE_FAULTS: ${PIPELINE_FAULTS:-0}
restart: unless-stopped
command:
- python
- -m
- src.publisher
healthcheck:
test:
- CMD
- python
- -m
- src.pipeline_health
interval: 3s
timeout: 4s
retries: 5
start_period: 25s
depends_on:
migrate:
condition: service_completed_successfully
openbao:
condition: service_healthy
worker:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 768m
cpus: 1.0
pids_limit: 128
tmpfs:
- /tmp:size=64m,mode=1777
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-app:local
networks:
- db
- objects
- queue
- secrets
- otlp
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/worker:/run/identity:ro
environment:
TLS_CA_FILE: /run/trust/ca.crt
BAO_ADDR: https://openbao:8200
BAO_ROLE: worker
CREDENTIAL_MAX_AGE: ${CREDENTIAL_MAX_AGE:-30}
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/trust/ca.crt
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/otel.crt
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/otel.key
PIPELINE_FAULTS: ${PIPELINE_FAULTS:-0}
restart: unless-stopped
command:
- python
- -m
- src.worker
healthcheck:
test:
- CMD
- python
- -m
- src.pipeline_health
interval: 3s
timeout: 4s
retries: 5
start_period: 25s
depends_on:
migrate:
condition: service_completed_successfully
openbao:
condition: service_healthy
deploy:
replicas: 2
init: true
stop_grace_period: 30s
recovery:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 384m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-app:local
networks:
- db
- objects
- secrets
- otlp
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/recovery:/run/identity:ro
environment:
TLS_CA_FILE: /run/trust/ca.crt
BAO_ADDR: https://openbao:8200
BAO_ROLE: recovery
CREDENTIAL_MAX_AGE: ${CREDENTIAL_MAX_AGE:-30}
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/trust/ca.crt
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/otel.crt
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/otel.key
PIPELINE_FAULTS: ${PIPELINE_FAULTS:-0}
restart: unless-stopped
command:
- python
- -m
- src.recovery
healthcheck:
test:
- CMD
- python
- -m
- src.pipeline_health
interval: 3s
timeout: 4s
retries: 25
start_period: 25s
depends_on:
migrate:
condition: service_completed_successfully
openbao:
condition: service_healthy
lb:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 128m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: haproxy:3.0.32-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3
command: ["haproxy", "-W", "-db", "-f", "/usr/local/etc/haproxy/haproxy.cfg"]
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/lb:/run/identity:ro
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
restart: unless-stopped
networks:
- edge
- telemetry
ports:
- 127.0.0.1:8443:8443
otel-collector:
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-otel:local
networks:
- otlp
- telemetry
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/otel:/run/identity:ro
- ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro
restart: unless-stopped
security_opt:
- no-new-privileges:true
mem_limit: 256m
cpus: 0.75
pids_limit: 256
build:
context: ./infra/otel
target: collector
read_only: true
tmpfs:
- /tmp:size=16m,mode=1777
cap_drop:
- ALL
command:
- --config=/etc/otel/collector.yaml
otel-tls:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 128m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: haproxy:3.0.32-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/otel:/run/identity:ro
- ./infra/tls/otel.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
restart: unless-stopped
network_mode: service:otel-collector
prometheus:
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-prometheus:local
networks:
- telemetry
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/prometheus:/run/identity:ro
- ./infra/prometheus:/etc/prometheus:ro
- prometheus_data:/prometheus
restart: unless-stopped
security_opt:
- no-new-privileges:true
mem_limit: 512m
cpus: 0.75
pids_limit: 256
build:
context: ./infra/otel
target: prometheus
read_only: true
tmpfs:
- /tmp:size=16m,mode=1777
cap_drop:
- ALL
command:
- --config.file=/etc/prometheus/prometheus.yaml
- --web.listen-address=127.0.0.1:19090
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=3d
- --storage.tsdb.retention.size=512MB
- --enable-feature=exemplar-storage
prometheus-tls:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 128m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: haproxy:3.0.32-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/prometheus:/run/identity:ro
- ./infra/tls/prometheus.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
restart: unless-stopped
network_mode: service:prometheus
loki:
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-loki:local
networks:
- telemetry
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/loki:/run/identity:ro
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
- loki_data:/loki
restart: unless-stopped
security_opt:
- no-new-privileges:true
mem_limit: 512m
cpus: 0.75
pids_limit: 256
build:
context: ./infra/otel
target: loki
read_only: true
tmpfs:
- /tmp:size=16m,mode=1777
cap_drop:
- ALL
command:
- -config.file=/etc/loki/loki.yaml
loki-tls:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 128m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: haproxy:3.0.32-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/loki:/run/identity:ro
- ./infra/tls/loki.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
restart: unless-stopped
network_mode: service:loki
tempo:
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-tempo:local
networks:
- telemetry
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/tempo:/run/identity:ro
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
- tempo_data:/var/tempo
restart: unless-stopped
security_opt:
- no-new-privileges:true
mem_limit: 512m
cpus: 0.75
pids_limit: 256
build:
context: ./infra/otel
target: tempo
read_only: true
tmpfs:
- /tmp:size=16m,mode=1777
cap_drop:
- ALL
command:
- -config.file=/etc/tempo/tempo.yaml
tempo-tls:
user: 10001:10001
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 128m
cpus: 0.5
pids_limit: 128
tmpfs:
- /tmp:size=16m,mode=1777
image: haproxy:3.0.32-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/tempo:/run/identity:ro
- ./infra/tls/tempo.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
restart: unless-stopped
network_mode: service:tempo
grafana:
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-grafana:local
networks:
- telemetry
volumes:
- ${LAB7_STATE:?run scripts/compose.sh}/trust:/run/trust:ro
- ${LAB7_STATE:?run scripts/compose.sh}/grafana:/run/identity:ro
- grafana_data:/var/lib/grafana
- ./scripts/grafana-start.sh:/lab/grafana-start.sh:ro
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
restart: unless-stopped
security_opt:
- no-new-privileges:true
mem_limit: 512m
cpus: 0.75
pids_limit: 256
build:
context: ./infra/otel
target: grafana
read_only: true
tmpfs:
- /tmp:size=16m,mode=1777
cap_drop:
- ALL
entrypoint:
- /bin/sh
- /lab/grafana-start.sh
ports:
- 127.0.0.1:3007:3000
environment:
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/identity/admin
GF_SERVER_PROTOCOL: https
GF_SERVER_CERT_FILE: /run/identity/server.crt
GF_SERVER_CERT_KEY: /run/identity/server.key
GF_SERVER_ROOT_URL: https://localhost:3007
GF_USERS_ALLOW_SIGN_UP: 'false'
GF_ANALYTICS_REPORTING_ENABLED: 'false'
GF_ANALYTICS_CHECK_FOR_UPDATES: 'false'
volume-init:
image: busybox:1.37.0-musl
network_mode: none
user: 0:0
entrypoint:
- /bin/sh
- -ec
- |
chown 100:1000 /bao
chown 1001:0 /s3
read_only: true
cap_drop:
- ALL
cap_add:
- CHOWN
security_opt:
- no-new-privileges:true
volumes:
- openbao_data_v2:/bao
- s3_data:/s3
mem_limit: 32m
cpus: 0.2
pids_limit: 16
probe:
image: ${LAB7_IMAGE_PREFIX:-mtusi2026lab7}-app:local
profiles:
- operator
networks:
- edge
- queue
- otlp
- db
- objects
- secrets
- telemetry
user: 10001:10001
read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
pids_limit: 32
mem_limit: 96m
cpus: 0.5
entrypoint:
- python
- /lab/probe.py
volumes:
- ./student-tests/tls_probe.py:/lab/probe.py:ro
- ${LAB7_STATE}/trust:/run/trust:ro
- ${LAB7_STATE}/lb:/probe/lb:ro
- ${LAB7_STATE}/probe:/probe/probe:ro
- ${LAB7_STATE}/publisher:/probe/publisher:ro
- ${LAB7_STATE}/worker:/probe/worker:ro
- ${LAB7_STATE}/ops:/probe/ops:ro
- ${LAB7_STATE}/rotation:/probe/rotation:ro
- ${LAB7_STATE}/api-a:/probe/api-a:ro
- ${LAB7_STATE}/api-b:/probe/api-b:ro
- ${LAB7_STATE}/recovery:/probe/recovery:ro
- ${LAB7_STATE}/otel:/probe/otel:ro
- ${LAB7_STATE}/grafana:/probe/grafana:ro
- ${LAB7_STATE}/prometheus:/probe/prometheus:ro
volumes:
postgres_data: {}
s3_data: {}
broker_data: {}
openbao_data_v2: {}
api-a_socket:
driver: local
driver_opts:
type: tmpfs
device: tmpfs
o: uid=10001,gid=10001,mode=0750,size=1048576
api-b_socket:
driver: local
driver_opts:
type: tmpfs
device: tmpfs
o: uid=10001,gid=10001,mode=0750,size=1048576
prometheus_data: {}
loki_data: {}
tempo_data: {}
grafana_data: {}
networks:
edge: {}
db: {}
objects: {}
queue: {}
secrets: {}
otlp: {}
telemetry: {}
+17 -13
View File
@@ -1,21 +1,21 @@
# Матрица доверия — заполнить в решении lab7
# Матрица доверия — лабораторная 7
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
| --- | --- | --- | --- |
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | HTTPS `localhost:8443`, lab CA и SAN `localhost`. Bearer TTL 3600 с по умолчанию, scope сессии пользователя. `make test test-security`, `grade4_probe.py login`. |
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | `api-a-tls/api-b-tls:8444`, lab CA и SAN реплики. Client identity `lb-to-api` проверяется allowlist CN и CRL, leaf 30 дней. Дальше Unix socket. `probe matrix`, `grade4_probe.py leaf`. |
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | `postgres:5432`, lab CA и SAN `postgres`, SCRAM и `verify-full`. API использует blue/green, Worker — worker. PostgreSQL-пароль действует до ротации, snapshot имеет локальный TTL. `probe matrix`, `grade4_probe.py db`. |
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | `s3:9000`, lab CA и SAN `s3`. API пишет staging и читает results, Worker читает исходники и пишет results. IAM-ключи действуют до смены. `make test`, `probe matrix`, `recovery-test.sh`. |
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | `broker:5671`, lab CA и SAN `broker`, EXTERNAL по CN. API фиксирует outbox, publisher публикует, worker потребляет, ops может повторно публиковать. Leaf 30 дней. `probe matrix` проверяет допуск и запрет операций. |
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | `otel-collector:4318`, lab CA и SAN `otel-collector`, allowlist CN для ingest, leaf 30 дней. Закрытый loopback до Collector. `probe matrix`. |
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | `loki:3100/otlp/v1/logs`, `tempo:4318/v1/traces`. Lab CA, SAN каждого backend, CN `collector-export`, leaf 30 дней, ограничение метода и пути. `probe matrix`. |
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | `prometheus:9090`, `loki:3100`, `tempo:3200`, SAN по именам, CN `grafana-query`, leaf 30 дней. Только query routes. `probe matrix`. |
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | `openbao:8200`, lab CA и SAN `openbao`. Cert role ограничивает DNS SAN *.bao.lab индивидуальным именем, KV read и renew-self. Token 20 с, максимум 60 с, snapshot по умолчанию 30 с. `probe matrix`, `grade4_probe.py sealed`. |
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | OpenBao `127.0.0.1:18200`, Grafana `127.0.0.1:3007`; TLS SAN localhost и локальные operator credentials. MinIO admin на закрытой сети через bootstrap. Root OpenBao и admin MinIO вне приложений. |
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | N/A. Лимиты, сессии и данные хранятся в общем PostgreSQL. |
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | N/A. PostgreSQL, RabbitMQ и Raft развёрнуты по одному узлу; отказ хоста не покрывается. |
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
@@ -35,3 +35,7 @@
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 — хорошее расширение, но не обязательное название технологии.
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
Проверка операторского профиля на отдельном Compose-проекте: `./scripts/compose.sh run --rm -T probe matrix`. В тестовом проекте внешние порты 28443, 28200 и 23007. OpenBao и PostgreSQL роли проверяются без вывода токенов и паролей. Положительная передача синтетического OTLP-лога проверяет ingest.
Prometheus получает метрики от LB по TLS на 8404 и от Collector на 9464/8888 с CN `prometheus-scrape`. Uvicorn слушает Unix socket; локальные OTLP, Loki, Tempo и Prometheus listeners доступны внутри network namespace соответствующего backend. DNS Docker разделяет сети edge, db, objects, queue, secrets, otlp и telemetry. Healthchecks контейнеров используют локальный transport или TLS health endpoint.
+51
View File
@@ -0,0 +1,51 @@
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
username VARCHAR(32) NOT NULL UNIQUE
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name VARCHAR(100) NOT NULL
CHECK (length(btrim(display_name)) > 0),
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS chats (
id UUID PRIMARY KEY,
title VARCHAR(100) NOT NULL
CHECK (length(btrim(title)) > 0),
created_by UUID NOT NULL REFERENCES users(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id),
joined_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id),
text TEXT NOT NULL
CHECK (length(text) <= 4000 AND length(btrim(text)) > 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS sessions (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL,
revoked_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_messages_chat_created_id
ON messages (chat_id, created_at, id);
CREATE INDEX IF NOT EXISTS idx_chat_members_user_id
ON chat_members (user_id);
CREATE INDEX IF NOT EXISTS idx_sessions_expires_at
ON sessions (expires_at);
+9
View File
@@ -0,0 +1,9 @@
CREATE TABLE message_requests (
chat_id UUID NOT NULL REFERENCES chats(id),
sender_id UUID NOT NULL REFERENCES users(id),
key VARCHAR(128) NOT NULL,
text TEXT NOT NULL,
message_id UUID REFERENCES messages(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (chat_id, sender_id, key)
);
+16
View File
@@ -0,0 +1,16 @@
CREATE TABLE attachments (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id),
owner_id UUID NOT NULL REFERENCES users(id),
filename TEXT NOT NULL,
object_key TEXT NOT NULL UNIQUE,
size_bytes BIGINT NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
content_type TEXT NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
sha256 CHAR(64) NOT NULL,
status TEXT NOT NULL DEFAULT 'ready' CHECK (status = 'ready'),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD COLUMN attachment_ids UUID[] NOT NULL DEFAULT '{}';
ALTER TABLE messages ADD CHECK (length(text) <= 4000 AND (length(btrim(text)) > 0 OR cardinality(attachment_ids) > 0));
+77
View File
@@ -0,0 +1,77 @@
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ALTER COLUMN status SET DEFAULT 'queued';
ALTER TABLE attachments ADD CHECK (status IN ('queued','processing','ready','failed'));
ALTER TABLE attachments
ADD COLUMN desired_version INTEGER NOT NULL DEFAULT 1,
ADD COLUMN active_version INTEGER,
ADD COLUMN staging_key TEXT UNIQUE,
ADD COLUMN error_code TEXT;
CREATE TABLE image_jobs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
attachment_id UUID NOT NULL REFERENCES attachments(id),
pipeline_version INTEGER NOT NULL CHECK (pipeline_version > 0),
state TEXT NOT NULL DEFAULT 'queued' CHECK (state IN ('queued','processing','ready','failed','superseded')),
attempt INTEGER NOT NULL DEFAULT 1 CHECK (attempt > 0),
failures INTEGER NOT NULL DEFAULT 0,
fence BIGINT NOT NULL DEFAULT 0,
lease_until TIMESTAMPTZ,
error_code TEXT,
manifest JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (attachment_id, pipeline_version),
CHECK ((state = 'processing') = (lease_until IS NOT NULL)),
CHECK ((state = 'ready') = (manifest IS NOT NULL))
);
CREATE INDEX image_jobs_expired ON image_jobs(lease_until) WHERE state = 'processing';
CREATE TABLE job_outbox (
job_id UUID PRIMARY KEY REFERENCES image_jobs(id),
publish_after TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX job_outbox_due ON job_outbox(publish_after);
CREATE TABLE job_events (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id UUID NOT NULL REFERENCES image_jobs(id),
attempt INTEGER NOT NULL,
event TEXT NOT NULL,
detail TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX job_events_lookup ON job_events(job_id, id);
-- Durable operator-visible DLQ. Replays retain the historical failure rows.
CREATE TABLE job_dead_letters (
job_id UUID NOT NULL REFERENCES image_jobs(id),
attempt INTEGER NOT NULL,
error_code TEXT NOT NULL,
failed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
replayed_at TIMESTAMPTZ,
PRIMARY KEY (job_id, attempt)
);
-- Used only by an explicitly enabled synthetic fault-injection stand.
CREATE TABLE pipeline_faults (
attachment_id UUID NOT NULL REFERENCES attachments(id),
pipeline_version INTEGER NOT NULL,
point TEXT NOT NULL,
action TEXT NOT NULL CHECK (action IN ('crash','pause','temporary','permanent')),
hit_at TIMESTAMPTZ,
released BOOLEAN NOT NULL DEFAULT false,
PRIMARY KEY (attachment_id,pipeline_version,point)
);
-- Upgrade persisted lab4 originals, which remain the source until v1 commits.
UPDATE attachments SET status='queued', updated_at=now();
WITH inserted AS (
INSERT INTO image_jobs(attachment_id,pipeline_version)
SELECT id,1 FROM attachments RETURNING id
)
INSERT INTO job_outbox(job_id) SELECT id FROM inserted;
ALTER TABLE attachments
ADD CHECK (desired_version > 0 AND (active_version IS NULL OR active_version <= desired_version)),
ADD CHECK ((status = 'ready') = (active_version IS NOT NULL)),
ADD CHECK ((status = 'failed') = (error_code IS NOT NULL)),
ADD FOREIGN KEY (id, active_version) REFERENCES image_jobs(attachment_id, pipeline_version);
+9
View File
@@ -0,0 +1,9 @@
ALTER TABLE image_jobs
ADD COLUMN trace_context JSONB,
ADD COLUMN accepted_at TIMESTAMPTZ,
ADD COLUMN first_ready_at TIMESTAMPTZ;
CREATE INDEX image_jobs_unfinished ON image_jobs(created_at)
WHERE state IN ('queued', 'processing');
CREATE INDEX image_jobs_acceptance ON image_jobs(accepted_at)
WHERE accepted_at IS NOT NULL;
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE login_limits (
scope text NOT NULL,
bucket bigint NOT NULL,
attempts integer NOT NULL,
PRIMARY KEY (scope, bucket)
);
CREATE INDEX login_limits_bucket ON login_limits (bucket);
+29
View File
@@ -0,0 +1,29 @@
GRANT SELECT, INSERT ON users, sessions, chats, chat_members, messages TO api_runtime;
GRANT UPDATE(password_hash) ON users TO api_runtime;
GRANT UPDATE(revoked_at) ON sessions TO api_runtime;
GRANT SELECT, INSERT, UPDATE, DELETE ON message_requests, login_limits TO api_runtime;
GRANT SELECT, INSERT ON attachments, image_jobs TO api_runtime;
GRANT UPDATE(updated_at) ON attachments TO api_runtime;
GRANT SELECT, INSERT ON job_outbox TO api_runtime;
GRANT UPDATE(publish_after) ON job_outbox TO api_runtime;
GRANT SELECT ON image_jobs TO publisher;
GRANT SELECT, DELETE ON job_outbox TO publisher;
GRANT UPDATE(publish_after) ON job_outbox TO publisher;
GRANT INSERT ON job_events TO publisher;
GRANT SELECT ON attachments, image_jobs TO worker, recovery, ops;
GRANT UPDATE(status,error_code,updated_at) ON attachments TO worker, recovery, ops;
GRANT UPDATE(active_version,object_key) ON attachments TO worker;
GRANT UPDATE(staging_key) ON attachments TO recovery;
GRANT UPDATE(desired_version) ON attachments TO ops;
GRANT UPDATE(state,fence,lease_until,failures,attempt,error_code) ON image_jobs TO worker,recovery,ops;
GRANT UPDATE(manifest,first_ready_at) ON image_jobs TO worker;
GRANT INSERT ON image_jobs TO ops;
GRANT SELECT, INSERT ON job_outbox TO worker,recovery,ops;
GRANT UPDATE(publish_after) ON job_outbox TO worker,recovery,ops;
GRANT INSERT ON job_events TO worker,recovery,ops;
GRANT INSERT ON job_dead_letters TO worker,recovery;
GRANT SELECT ON job_dead_letters TO ops;
GRANT UPDATE(replayed_at) ON job_dead_letters TO ops;
GRANT USAGE ON SEQUENCE job_events_id_seq TO publisher,worker,recovery,ops;
File diff suppressed because it is too large Load Diff
+682
View File
@@ -0,0 +1,682 @@
{
"title": "Messenger · Lab 6",
"uid": "messenger-lab6",
"schemaVersion": 39,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"id": 1,
"title": "HTTP · запросов/с",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(lab_http_requests_total[1m]))",
"legendFormat": "API",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
}
},
{
"id": 2,
"title": "HTTP · доля 5xx",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "lab:sli_api_bad:2m / lab:sli_api_total:2m",
"legendFormat": "Публичный вход",
"exemplar": true
},
{
"refId": "B",
"expr": "(sum(rate(lab_http_requests_total{status_class=\"5xx\"}[1m])) or 0 * sum(rate(lab_http_requests_total[1m]))) / sum(rate(lab_http_requests_total[1m]))",
"legendFormat": "API",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 3,
"title": "HTTP · задержка по всем репликам",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5,sum by (le)(rate(lab_http_duration_seconds_bucket[1m])))",
"legendFormat": "p50",
"exemplar": true
},
{
"refId": "B",
"expr": "histogram_quantile(0.95,sum by (le)(rate(lab_http_duration_seconds_bucket[1m])))",
"legendFormat": "p95",
"exemplar": true
},
{
"refId": "C",
"expr": "histogram_quantile(0.99,sum by (le)(rate(lab_http_duration_seconds_bucket[1m])))",
"legendFormat": "p99",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 4,
"title": "Реплики и доступность",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name)((lab_process_alive and on(service_instance_id) (time()-lab_process_heartbeat_seconds<20)))",
"legendFormat": "{{service_name}}",
"exemplar": true
},
{
"refId": "B",
"expr": "sum(haproxy_server_status{proxy=\"replicas\",state=\"UP\"})",
"legendFormat": "Готовые API по HAProxy",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 5,
"title": "Очередь · queued",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "max(lab_queue_depth)",
"legendFormat": "queued",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 6,
"title": "Старейшая незавершённая работа",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "max(lab_oldest_job_age_seconds)",
"legendFormat": "queued или processing",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 7,
"title": "Попытки worker · исходы/с",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome)(rate(lab_job_results_total[1m]))",
"legendFormat": "{{outcome}}",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 8,
"title": "Worker · время попытки",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5,sum by (le)(rate(lab_job_duration_seconds_bucket[1m])))",
"legendFormat": "p50",
"exemplar": true
},
{
"refId": "B",
"expr": "histogram_quantile(0.95,sum by (le)(rate(lab_job_duration_seconds_bucket[1m])))",
"legendFormat": "p95",
"exemplar": true
},
{
"refId": "C",
"expr": "histogram_quantile(0.99,sum by (le)(rate(lab_job_duration_seconds_bucket[1m])))",
"legendFormat": "p99",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 9,
"title": "Время до готовности · успешные",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5,sum by (le)(rate(lab_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "p50",
"exemplar": true
},
{
"refId": "B",
"expr": "histogram_quantile(0.95,sum by (le)(rate(lab_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "p95",
"exemplar": true
},
{
"refId": "C",
"expr": "histogram_quantile(0.99,sum by (le)(rate(lab_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "p99",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 10,
"title": "Worker · занятость и ёмкость",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum((lab_worker_busy and on(service_instance_id) (time()-lab_process_heartbeat_seconds<20))) or vector(0)",
"legendFormat": "занято",
"exemplar": true
},
{
"refId": "B",
"expr": "sum((lab_worker_capacity and on(service_instance_id) (time()-lab_process_heartbeat_seconds<20))) or vector(0)",
"legendFormat": "ёмкость",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 11,
"title": "PostgreSQL · пул",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name)(lab_db_pool_used)",
"legendFormat": "занято {{service_name}}",
"exemplar": true
},
{
"refId": "B",
"expr": "sum by (service_name)(lab_db_pool_waiting)",
"legendFormat": "ждут {{service_name}}",
"exemplar": true
},
{
"refId": "C",
"expr": "sum by (service_name)(lab_db_pool_capacity)",
"legendFormat": "лимит {{service_name}}",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 12,
"title": "Пулы API · ожидание",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "max by (service_instance_id)(lab_db_pool_waiting{service_name=\"messenger-api\"})",
"legendFormat": "{{service_instance_id}}",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 13,
"title": "CPU · число ядер на процесс",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "rate(lab_process_cpu_seconds_total[1m])",
"legendFormat": "{{service_name}} / {{service_instance_id}}",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 14,
"title": "RAM · RSS процесса",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "lab_process_rss_bytes",
"legendFormat": "{{service_name}} / {{service_instance_id}}",
"exemplar": true
},
{
"refId": "B",
"expr": "otelcol_process_memory_rss_bytes",
"legendFormat": "Collector",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
}
},
{
"id": 15,
"title": "API и ready · SLI за 1 час",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "1-lab:sli_api_bad:1h/lab:sli_api_total:1h",
"legendFormat": "API",
"exemplar": true
},
{
"refId": "B",
"expr": "1-lab:sli_ready_bad:1h/lab:sli_ready_total:1h",
"legendFormat": "Ready",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 16,
"title": "Расход бюджета · доля бюджета за 1 час",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "lab:burn_api:1h",
"legendFormat": "API (цель 99%)",
"exemplar": true
},
{
"refId": "B",
"expr": "lab:burn_ready:1h",
"legendFormat": "Ready (цель 95%)",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 17,
"title": "Collector · очередь экспорта",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 64,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_queue_size",
"legendFormat": "{{exporter}}",
"exemplar": true
},
{
"refId": "B",
"expr": "otelcol_exporter_queue_capacity",
"legendFormat": "лимит {{exporter}}",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 18,
"title": "Collector · потери на экспорте",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 64,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum by (exporter)(increase(otelcol_exporter_send_failed_spans_total[1m]))",
"legendFormat": "spans {{exporter}}",
"exemplar": true
},
{
"refId": "B",
"expr": "sum by (exporter)(increase(otelcol_exporter_send_failed_log_records_total[1m]))",
"legendFormat": "logs {{exporter}}",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 19,
"title": "Активные оповещения",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 72,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "ALERTS",
"legendFormat": "{{alertname}} {{alertstate}}",
"exemplar": true
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 20,
"title": "Связанные логи API / Worker",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 12,
"y": 72,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"messenger-api|messenger-worker\"}",
"legendFormat": ""
}
]
}
]
}
@@ -0,0 +1,7 @@
apiVersion: 1
providers:
- name: messenger
folder: Lab 6
type: file
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,57 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
secureJsonData:
tlsCACert: $LAB_CA
tlsClientCert: $LAB_CERT
tlsClientKey: $LAB_KEY
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
timeInterval: 5s
exemplarTraceIdDestinations:
- name: trace_id
datasourceUid: tempo
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
secureJsonData:
tlsCACert: $LAB_CA
tlsClientCert: $LAB_CERT
tlsClientKey: $LAB_KEY
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
derivedFields:
- name: Trace
matcherRegex: '"trace_id":"([0-9a-f]{32})"'
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
secureJsonData:
tlsCACert: $LAB_CA
tlsClientCert: $LAB_CERT
tlsClientKey: $LAB_KEY
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: '-10s'
spanEndTimeShift: '10s'
tags:
- key: service.name
value: service_name
customQuery: true
query: '{$${__tags}} | json | trace_id="$${__span.traceId}"'
+32
View File
@@ -0,0 +1,32 @@
global
maxconn 1024
defaults
mode http
timeout connect 1s
timeout client 60s
timeout server 60s
timeout check 1s
retries 0
resolvers docker
nameserver dns 127.0.0.11:53
hold valid 2s
frontend public
bind :8443 ssl crt /run/identity/server.pem ssl-min-ver TLSv1.2
default_backend replicas
backend replicas
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost
http-check expect status 200
default-server inter 1s fall 2 rise 1 resolvers docker init-addr libc,none
server a api-a-tls:8444 check ssl verify required ca-file /run/trust/ca.crt crt /run/identity/client.pem sni str(api-a-tls) check-sni api-a-tls verifyhost api-a-tls
server b api-b-tls:8444 check ssl verify required ca-file /run/trust/ca.crt crt /run/identity/client.pem sni str(api-b-tls) check-sni api-b-tls verifyhost api-b-tls
frontend monitoring
bind :8404 ssl crt /run/identity/server.pem ca-file /run/trust/ca.crt verify required
http-request deny unless { ssl_c_s_dn(cn) -m str prometheus-scrape } { path /metrics }
http-request use-service prometheus-exporter
+37
View File
@@ -0,0 +1,37 @@
auth_enabled: false
server:
http_listen_address: 127.0.0.1
http_listen_port: 13100
grpc_listen_address: 127.0.0.1
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 72h
otlp_config:
resource_attributes:
ignore_defaults: true
attributes_config:
- action: index_label
attributes: [service.name]
compactor:
retention_enabled: true
delete_request_store: filesystem
+39
View File
@@ -0,0 +1,39 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::messenger-attachments/staging/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::messenger-attachments/results/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::messenger-attachments"
],
"Condition": {
"StringEquals": {
"s3:prefix": [
"originals/"
]
}
}
}
]
}
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
set -eu
export MC_CONFIG_DIR=/tmp/mc
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
cp /run/trust/ca.crt "$MC_CONFIG_DIR/certs/CAs/lab.crt"
if ! mc alias set local https://s3:9000 labroot "$(cat /run/identity/admin)" >/dev/null 2>&1; then
echo 'MinIO administrative connection failed' >&2
exit 1
fi
# New buckets are private by default. Keep the existing bucket policy on replay.
mc mb --ignore-existing local/messenger-attachments >/dev/null
users=$(mc --no-color admin user list local)
policies=$(mc --no-color admin policy list local)
for role in api worker recovery; do
name="lab-$role"
if ! printf '%s\n' "$policies" | grep -Fxq "$name"; then
mc admin policy create local "$name" "/lab/$role.json" >/dev/null
fi
user=$(printf '%s\n' "$users" | awk -v name="$name" '$2 == name')
if [ -z "$user" ]; then
if ! mc admin user add local "$name" "$(cat "/run/identity/$role")" >/dev/null 2>&1; then
printf 'Could not create MinIO user %s\n' "$name" >&2
exit 1
fi
elif [ -n "$(printf '%s\n' "$user" | awk '{print $3}')" ]; then
continue
fi
mc admin policy attach local "$name" --user "$name" >/dev/null
done
+30
View File
@@ -0,0 +1,30 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::messenger-attachments/staging/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::messenger-attachments"
],
"Condition": {
"StringEquals": {
"s3:prefix": [
"staging/"
]
}
}
}
]
}
+25
View File
@@ -0,0 +1,25 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::messenger-attachments/staging/*",
"arn:aws:s3:::messenger-attachments/originals/*",
"arn:aws:s3:::messenger-attachments/results/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::messenger-attachments/results/*"
]
}
]
}
+13
View File
@@ -0,0 +1,13 @@
api_addr = "https://openbao:8200"
cluster_addr = "https://openbao:8201"
storage "raft" {
path = "/openbao/data"
node_id = "lab7"
}
listener "tcp" {
address = "0.0.0.0:8200"
cluster_address = "127.0.0.1:8201"
tls_cert_file = "/run/identity/server.crt"
tls_key_file = "/run/identity/server.key"
tls_min_version = "tls12"
}
+9
View File
@@ -0,0 +1,9 @@
FROM busybox:1.37.0-musl AS probe
FROM otel/opentelemetry-collector-contrib:0.144.0@sha256:213886eb6407af91b87fa47551c3632be1a6419ff3a5114ef1e6fc364628496f AS collector
COPY --from=probe /bin/busybox /lab/busybox
FROM grafana/loki:3.6.12@sha256:2483b71b28b15dee230f85512cae2b20c4b5f6e98a6eabe686cbccfa5ea3ba4a AS loki
COPY --from=probe /bin/busybox /lab/busybox
FROM grafana/tempo:2.10.5@sha256:ee21727732c7a7199cb71c3eee9153bbf23f9b0b87619f0555a0cf21a67f1a33 AS tempo
COPY --from=probe /bin/busybox /lab/busybox
FROM prom/prometheus:v3.5.5@sha256:332c2f43e7e389d74d3893b55bb02fbbd684208e681eeb604641d5d769c0fe2a AS prometheus
FROM grafana/grafana:11.6.14@sha256:ebe075cd4c4520f9d3af2403a1ddc830651ca7d009cbdfdcf21032db574dc3a7 AS grafana
+67
View File
@@ -0,0 +1,67 @@
extensions:
health_check:
endpoint: 127.0.0.1:13133
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 160
spike_limit_mib: 40
batch:
timeout: 1s
send_batch_size: 256
send_batch_max_size: 256
exporters:
prometheus:
endpoint: 127.0.0.1:19464
metric_expiration: 25s
enable_open_metrics: true
resource_to_telemetry_conversion:
enabled: true
otlphttp/loki:
endpoint: https://loki:3100/otlp
tls: &backend_tls
ca_file: /run/trust/ca.crt
cert_file: /run/identity/client.crt
key_file: /run/identity/client.key
timeout: 2s
sending_queue: &bounded_queue
num_consumers: 1
queue_size: 16
retry_on_failure: &bounded_retry
initial_interval: 1s
max_interval: 4s
max_elapsed_time: 10s
otlphttp/tempo:
endpoint: https://tempo:4318
tls: *backend_tls
timeout: 2s
sending_queue: *bounded_queue
retry_on_failure: *bounded_retry
service:
extensions: [health_check]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 127.0.0.1
port: 18888
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
+54
View File
@@ -0,0 +1,54 @@
#!/bin/sh
set -eu
sql() {
psql -Xq -v ON_ERROR_STOP=1 -U postgres -d messenger "$@"
}
for role in migrator api_blue publisher worker recovery ops; do
if [ "$(sql -At -c "SELECT 1 FROM pg_roles WHERE rolname = '$role'")" = 1 ]; then
continue
fi
credential=$(cat "/run/identity/$role")
case "$credential" in
*[!a-f0-9]*|'') printf 'Invalid credential file for %s\n' "$role" >&2; exit 1 ;;
esac
if ! {
printf '%s\n' 'BEGIN;' "SET LOCAL password_encryption = 'scram-sha-256';" \
"SET LOCAL log_statement = 'none';" "SET LOCAL log_min_error_statement = 'panic';" \
'SELECT pg_advisory_xact_lock(70701);'
printf "SELECT format('CREATE ROLE %%I LOGIN PASSWORD %%L', '%s', '%s') WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '%s')\n" "$role" "$credential" "$role"
printf '%s\n' '\gexec' 'COMMIT;'
} | sql >/dev/null 2>&1; then
printf 'Could not create PostgreSQL role %s\n' "$role" >&2
exit 1
fi
done
sql >/dev/null <<'SQL'
BEGIN;
SELECT pg_advisory_xact_lock(70701);
DO $roles$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'api_runtime') THEN
CREATE ROLE api_runtime NOLOGIN;
END IF;
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'api_green') THEN
CREATE ROLE api_green LOGIN;
END IF;
IF EXISTS (
SELECT FROM pg_roles
WHERE (rolname IN ('api_blue', 'api_green') AND NOT rolcanlogin)
OR (rolname = 'api_runtime' AND rolcanlogin)
) THEN
RAISE EXCEPTION 'Existing API roles have incompatible LOGIN settings; manual reconciliation required';
END IF;
END
$roles$;
GRANT api_runtime TO api_blue, api_green;
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
GRANT CONNECT ON DATABASE messenger TO migrator, api_runtime, publisher, worker, recovery, ops;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
GRANT CREATE, USAGE ON SCHEMA public TO migrator;
COMMIT;
SQL
+6
View File
@@ -0,0 +1,6 @@
local all postgres peer
local all all reject
hostssl messenger all 0.0.0.0/0 scram-sha-256
hostssl messenger all ::/0 scram-sha-256
host all all 0.0.0.0/0 reject
host all all ::/0 reject
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
set -eu
install -m 0600 -o postgres -g postgres /run/identity/server.key /run/postgres-tls/server.key
install -m 0644 -o postgres -g postgres /run/identity/server.crt /run/postgres-tls/server.crt
# Execute the bind-mounted script through sh. Docker Desktop may mount it noexec.
printf '%s\n' '#!/bin/sh' 'exec /bin/sh /lab/init-roles.sh' \
> /docker-entrypoint-initdb.d/10-roles.sh
chmod 0755 /docker-entrypoint-initdb.d/10-roles.sh
exec docker-entrypoint.sh postgres -c ssl=on \
-c ssl_cert_file=/run/postgres-tls/server.crt \
-c ssl_key_file=/run/postgres-tls/server.key \
-c ssl_min_protocol_version=TLSv1.2 \
-c hba_file=/lab/pg_hba.conf -c password_encryption=scram-sha-256
+28
View File
@@ -0,0 +1,28 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files: [/etc/prometheus/rules.yaml]
scrape_configs:
- job_name: application-otlp
scheme: https
tls_config: &scrape_tls
ca_file: /run/trust/ca.crt
cert_file: /run/identity/client.crt
key_file: /run/identity/client.key
scrape_protocols: [OpenMetricsText1.0.0, PrometheusText0.0.4]
static_configs:
- targets: [otel-collector:9464]
- job_name: collector
scheme: https
tls_config: *scrape_tls
static_configs:
- targets: [otel-collector:8888]
- job_name: ingress
scheme: https
tls_config: *scrape_tls
metrics_path: /metrics
static_configs:
- targets: [lb:8404]
- job_name: prometheus
static_configs:
- targets: [127.0.0.1:19090]
+117
View File
@@ -0,0 +1,117 @@
groups:
- name: messenger-sli
rules:
- record: lab:sli_api_total:30s
expr: sum(increase(haproxy_frontend_http_responses_total{proxy="public"}[30s]))
- record: lab:sli_api_bad:30s
expr: sum(increase(haproxy_frontend_http_responses_total{proxy="public",code="5xx"}[30s])) or 0 * sum(increase(haproxy_frontend_http_responses_total{proxy="public"}[30s]))
- record: lab:sli_ready_total:30s
expr: sum(lab_ready_cohort{window="30s",outcome="total"}) and on() (time() - max(lab_queue_sample_timestamp_seconds) < 15)
- record: lab:sli_ready_bad:30s
expr: sum(lab_ready_cohort{window="30s",outcome="bad"}) and on() (time() - max(lab_queue_sample_timestamp_seconds) < 15)
- record: lab:burn_api:30s
expr: (lab:sli_api_bad:30s / lab:sli_api_total:30s / 0.01) and (lab:sli_api_total:30s > 0)
- record: lab:burn_ready:30s
expr: (lab:sli_ready_bad:30s / lab:sli_ready_total:30s / 0.05) and (lab:sli_ready_total:30s > 0)
- record: lab:sli_api_total:2m
expr: sum(increase(haproxy_frontend_http_responses_total{proxy="public"}[2m]))
- record: lab:sli_api_bad:2m
expr: sum(increase(haproxy_frontend_http_responses_total{proxy="public",code="5xx"}[2m])) or 0 * sum(increase(haproxy_frontend_http_responses_total{proxy="public"}[2m]))
- record: lab:sli_ready_total:2m
expr: sum(lab_ready_cohort{window="2m",outcome="total"}) and on() (time() - max(lab_queue_sample_timestamp_seconds) < 15)
- record: lab:sli_ready_bad:2m
expr: sum(lab_ready_cohort{window="2m",outcome="bad"}) and on() (time() - max(lab_queue_sample_timestamp_seconds) < 15)
- record: lab:burn_api:2m
expr: (lab:sli_api_bad:2m / lab:sli_api_total:2m / 0.01) and (lab:sli_api_total:2m > 0)
- record: lab:burn_ready:2m
expr: (lab:sli_ready_bad:2m / lab:sli_ready_total:2m / 0.05) and (lab:sli_ready_total:2m > 0)
- record: lab:sli_api_total:5m
expr: sum(increase(haproxy_frontend_http_responses_total{proxy="public"}[5m]))
- record: lab:sli_api_bad:5m
expr: sum(increase(haproxy_frontend_http_responses_total{proxy="public",code="5xx"}[5m])) or 0 * sum(increase(haproxy_frontend_http_responses_total{proxy="public"}[5m]))
- record: lab:sli_ready_total:5m
expr: sum(lab_ready_cohort{window="5m",outcome="total"}) and on() (time() - max(lab_queue_sample_timestamp_seconds) < 15)
- record: lab:sli_ready_bad:5m
expr: sum(lab_ready_cohort{window="5m",outcome="bad"}) and on() (time() - max(lab_queue_sample_timestamp_seconds) < 15)
- record: lab:burn_api:5m
expr: (lab:sli_api_bad:5m / lab:sli_api_total:5m / 0.01) and (lab:sli_api_total:5m > 0)
- record: lab:burn_ready:5m
expr: (lab:sli_ready_bad:5m / lab:sli_ready_total:5m / 0.05) and (lab:sli_ready_total:5m > 0)
- record: lab:sli_api_total:1h
expr: sum(increase(haproxy_frontend_http_responses_total{proxy="public"}[1h]))
- record: lab:sli_api_bad:1h
expr: sum(increase(haproxy_frontend_http_responses_total{proxy="public",code="5xx"}[1h])) or 0 * sum(increase(haproxy_frontend_http_responses_total{proxy="public"}[1h]))
- record: lab:sli_ready_total:1h
expr: sum(lab_ready_cohort{window="1h",outcome="total"}) and on() (time() - max(lab_queue_sample_timestamp_seconds) < 15)
- record: lab:sli_ready_bad:1h
expr: sum(lab_ready_cohort{window="1h",outcome="bad"}) and on() (time() - max(lab_queue_sample_timestamp_seconds) < 15)
- record: lab:burn_api:1h
expr: (lab:sli_api_bad:1h / lab:sli_api_total:1h / 0.01) and (lab:sli_api_total:1h > 0)
- record: lab:burn_ready:1h
expr: (lab:sli_ready_bad:1h / lab:sli_ready_total:1h / 0.05) and (lab:sli_ready_total:1h > 0)
- name: messenger-alerts
rules:
- alert: HighHTTPErrorRate
expr: (lab:sli_api_bad:30s / lab:sli_api_total:30s > 0.10) and (lab:sli_api_total:30s >= 5)
for: 10s
labels:
severity: warning
annotations:
description: "More than 10% ingress 5xx over 30s with at least five responses."
runbook_url: "infra/runbooks.md#api"
- alert: QueueLag
expr: (max(lab_oldest_job_age_seconds) > 15) and on() (time() - max(lab_queue_sample_timestamp_seconds) < 15)
for: 10s
labels:
severity: warning
annotations:
description: "Oldest unfinished image job has been older than 15s for 10s."
runbook_url: "infra/runbooks.md#queue"
- alert: APIBurnFast
expr: (lab:burn_api:30s > 12) and (lab:burn_api:2m > 12) and (lab:sli_api_total:30s >= 8) and (lab:sli_api_total:2m >= 20)
for: 10s
labels:
severity: critical
annotations:
description: "12x budget burn across both 30s and 2m."
runbook_url: "infra/runbooks.md#api"
- alert: APIBurnSlow
expr: (lab:burn_api:2m > 4) and (lab:burn_api:5m > 4) and (lab:sli_api_total:2m >= 8) and (lab:sli_api_total:5m >= 20)
for: 15s
labels:
severity: warning
annotations:
description: "4x budget burn across both 2m and 5m."
runbook_url: "infra/runbooks.md#api"
- alert: ReadyBurnFast
expr: (lab:burn_ready:30s > 12) and (lab:burn_ready:2m > 12) and (lab:sli_ready_total:30s >= 4) and (lab:sli_ready_total:2m >= 10)
for: 10s
labels:
severity: critical
annotations:
description: "12x budget burn across both 30s and 2m."
runbook_url: "infra/runbooks.md#queue"
- alert: ReadyBurnSlow
expr: (lab:burn_ready:2m > 4) and (lab:burn_ready:5m > 4) and (lab:sli_ready_total:2m >= 4) and (lab:sli_ready_total:5m >= 10)
for: 15s
labels:
severity: warning
annotations:
description: "4x budget burn across both 2m and 5m."
runbook_url: "infra/runbooks.md#queue"
- alert: TelemetryExportLoss
expr: sum by (exporter) (increase(otelcol_exporter_send_failed_spans_total[30s])) > 0
for: 5s
labels:
severity: warning
annotations:
description: "Collector could not export one or more trace spans over 30s."
runbook_url: "infra/runbooks.md#telemetry"
- alert: TelemetryBacklogUnavailable
expr: (time() - max(lab_queue_sample_timestamp_seconds) > 15) or absent(lab_queue_sample_timestamp_seconds)
for: 15s
labels:
severity: warning
annotations:
description: "No fresh PostgreSQL queue sample."
runbook_url: "infra/runbooks.md#queue"
+83
View File
@@ -0,0 +1,83 @@
{
"users": [
{
"name": "publisher",
"password_hash": "",
"hashing_algorithm": "rabbit_password_hashing_sha256",
"tags": []
},
{
"name": "worker",
"password_hash": "",
"hashing_algorithm": "rabbit_password_hashing_sha256",
"tags": []
},
{
"name": "ops-redeliver",
"password_hash": "",
"hashing_algorithm": "rabbit_password_hashing_sha256",
"tags": []
}
],
"vhosts": [
{
"name": "messenger"
}
],
"permissions": [
{
"user": "publisher",
"vhost": "messenger",
"configure": "^$",
"write": "^attachments$",
"read": "^$"
},
{
"user": "worker",
"vhost": "messenger",
"configure": "^$",
"write": "^$",
"read": "^attachment[.]process[.]v1$"
},
{
"user": "ops-redeliver",
"vhost": "messenger",
"configure": "^$",
"write": "^attachments$",
"read": "^$"
}
],
"exchanges": [
{
"name": "attachments",
"vhost": "messenger",
"type": "direct",
"durable": true,
"auto_delete": false,
"internal": false,
"arguments": {}
}
],
"queues": [
{
"name": "attachment.process.v1",
"vhost": "messenger",
"durable": true,
"auto_delete": false,
"arguments": {
"x-queue-type": "quorum",
"x-delivery-limit": -1
}
}
],
"bindings": [
{
"source": "attachments",
"destination": "attachment.process.v1",
"destination_type": "queue",
"vhost": "messenger",
"routing_key": "attachment.process.v1",
"arguments": {}
}
]
}
+1
View File
@@ -0,0 +1 @@
[rabbitmq_auth_mechanism_ssl].
+11
View File
@@ -0,0 +1,11 @@
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.cacertfile = /run/trust/ca.crt
ssl_options.certfile = /run/identity/server.crt
ssl_options.keyfile = /run/identity/server.key
ssl_options.verify = verify_peer
ssl_options.fail_if_no_peer_cert = true
ssl_cert_login_from = common_name
auth_mechanisms.1 = EXTERNAL
definitions.import_backend = local_filesystem
definitions.local.path = /lab/definitions.json
+121
View File
@@ -0,0 +1,121 @@
# Runbook лабораторной 6
Открыть дашборд **Lab 6 → Messenger · Lab 6**, выбрать последние 15 минут и обновление 5 секунд. Состояния правил доступны в Prometheus API через Grafana
`/api/datasources/proxy/uid/prometheus/api/v1/alerts`. Активное правило имеет состояние
`pending` или `firing`. После resolved оно исчезает из ответа. Историю firing также
можно увидеть через `ALERTS{alertstate="firing"}` в Explore → Prometheus.
## API
- Проверить публичную долю 5xx и отдельную долю 5xx API. Входная метрика включает
собственные 503 HAProxy, например при отсутствии готовых реплик.
- Если реплики готовы, открыть **Пулы API · ожидание** и отфильтровать ошибки в Explore → Loki
запросом `{service_name="messenger-api"} | json | status=503`.
- Если у клиента есть `X-Request-Id`, добавить `| request_id="<значение>"`. Открыть ссылку **Trace**.
Долгий `postgresql.pool.acquire` при растущем waiting указывает на ожидание пула.
Долгий `postgresql.execute` указывает на ожидание в БД. Если оба короткие, смотреть
дочерние операции и время, оставшееся в HTTP span.
- Проверить PostgreSQL через `./scripts/compose.sh ps postgres`. Для учебного lock
дождаться ROLLBACK и повторить запрос. Проверить 200, отсутствие текущих 5xx и
исчезновение **HighHTTPErrorRate**, **APIBurnFast**, **APIBurnSlow** после истечения окон.
## Queue
- Сравнить **Очередь · queued**, **Старейшая незавершённая работа** и **Worker · занятость и ёмкость**.
Рост возраста при исчезнувшей capacity указывает на потерю worker. При полной capacity
проверить длительность задач. При свободной capacity проверить broker и publisher.
- Проверить `./scripts/compose.sh ps worker publisher broker recovery`.
В Explore → Loki открыть `{service_name=~"messenger-worker|messenger-publisher"} | json`.
Для одной задачи открыть trace и сравнить интервалы между **publish**, **process** и **job.publish_ready**.
- После остановки worker запустить `./scripts/compose.sh start worker`. Проверить
ready загруженных файлов и нулевой backlog. У **QueueLag** разрешение связано с
фактическим возрастом. **ReadyBurnFast/Slow** могут остаться активными до выхода
пропущенных дедлайнов из окна.
- **TelemetryBacklogUnavailable** означает, что PostgreSQL или процесс recovery не
обновляют выборку. Проверить их состояние. В этот период SLI ready неизвестен.
## Telemetry
- При **TelemetryExportLoss** проверить **Collector · очередь экспорта**,
**Collector · потери на экспорте** и RSS. По label `exporter` определить backend.
- Выполнить `./scripts/compose.sh ps tempo loki otel-collector` и локально
проверить `./scripts/compose.sh logs --tail 30 otel-collector`.
- Вернуть остановленный backend через `./scripts/compose.sh start tempo` или
`./scripts/compose.sh start loki`. Создать новое вложение, проверить наличие
новой трассы и исчезновение alert. Прежние отброшенные пакеты не восстанавливаются.
## Лабораторная 7 — переход на OpenBao v2
Compose заменит контейнер `openbao` на том же сетевом имени и порту. Сервис
и `volume-init` будут монтировать `mtusi2026lab7_openbao_data_v2`.
Старый `mtusi2026lab7_openbao_data` останется в Docker без подключения к новой
конфигурации. Из корня проекта перед запуском проверьте наличие старого тома и
действительность PostgreSQL credentials, которыми наполняется новый KV.
```sh
export LAB7_STATE=/private/tmp/mtusi2026lab7-501
export LAB7_API_DB_ROLE=api_blue
./scripts/compose.sh config -q
docker volume inspect --format '{{.Name}}' mtusi2026lab7_openbao_data
./scripts/compose.sh exec -T postgres sh -ec '
for role in "$1" publisher worker recovery; do
if ! PGPASSWORD="$(cat "/run/identity/$role")" PGSSLMODE=verify-full \
PGSSLROOTCERT=/run/trust/ca.crt PGGSSENCMODE=disable \
psql -XAt -h postgres -U "$role" -d messenger -c "SELECT 1" >/dev/null 2>&1; then
printf "PostgreSQL credential check failed for %s\n" "$role" >&2
exit 1
fi
done
' sh "$LAB7_API_DB_ROLE"
```
При сбое проверки остановитесь до запуска OpenBao. Если активной ролью после
ротации стала `api_green` и её действующий пароль есть в защищённом
`$LAB7_STATE/postgres/api_green`, установите `LAB7_API_DB_ROLE=api_green` и
повторите проверку. Если действующий пароль был только в старом KV,
потребуется отдельно согласовать смену PostgreSQL credential.
После успешной проверки выполните команды по очереди. Остановитесь при ошибке.
```sh
./scripts/bootstrap.sh --openbao-only
python3 scripts/bao.py status
./scripts/compose.sh exec -T openbao bao status
docker volume inspect --format '{{.Name}}' mtusi2026lab7_openbao_data mtusi2026lab7_openbao_data_v2
./scripts/compose.sh up -d --wait --wait-timeout 120
```
Операторский файл нового экземпляра — `$LAB7_STATE/operator/openbao-v2.json`.
Создайте защищённую резервную копию вне временного каталога. Не выводите
содержимое файла. При таймауте или ошибке сохранения проверьте
`python3 scripts/bao.py status` и сохраните операторские файлы, включая
`.pending` и `.init-attempted`. Маркер блокирует новый запрос инициализации,
даже если сервер пока отвечает `initialized=False`. Если итоговый файл
сохранён и проверен, повторный bootstrap продолжит распечатывание и создание
отсутствующих настроек. При отсутствии итогового файла требуется ручная
проверка сохранённого ответа. Не удаляйте маркер для автоматического повтора.
## Проверки уровня 4 и ротация
Используйте отдельный Compose-проект и команды из [REPORT.md](../REPORT.md).
Порт изолированного OpenBao передаётся операторским командам через
`LAB7_OPENBAO_URL`; HTTPS и локальный CA обязательны.
- Для ротации PostgreSQL выполните `python3 scripts/rotate-db.py`. Скрипт проверяет старую
генерацию, создаёт пароль на неактивной роли, проверяет вход с TLS,
публикует через KV CAS и ждёт обе реплики и завершение старых подключений.
При неоднозначном результате CAS или ошибке переключения сначала проверьте
опубликованную роль и доступность реплик. `--retire-previous` проверяет
действующую генерацию и удаляет только пароль другой роли. Поддерживается
один оператор на локальный LAB7_STATE. В рабочем проекте требуется
предварительное согласование смены credentials.
- Для ротации leaf выполните `python3 scripts/rotate-leaf.py`. Сначала установите конфигурацию
HAProxy master-worker. Скрипт проверяет CA/SAN, атомарно переключает PEM,
выполняет graceful reload без ослабления mTLS, проверяет замену и только
затем отзывает старый leaf и загружает CRL в обе реплики. До отзыва сбой
возвращает предыдущий PEM. После отзыва сохраняется новый PEM; при частичном
применении CRL проверьте новый leaf и повторите reload оставшейся реплики.
- Для сканирования установите в отдельном окружении `pip-audit==2.9.0` и запустите
`SCAN_OUTPUT=/absolute/report-dir PIP_AUDIT=/path/to/pip-audit sh scripts/security-scan.sh`
после сборки образов. Ненулевой код означает находки или незавершённый скан;
различайте их по JSON и журналу сканера.
+22
View File
@@ -0,0 +1,22 @@
server:
http_listen_address: 127.0.0.1
http_listen_port: 13200
grpc_listen_address: 127.0.0.1
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
ingester:
max_block_duration: 1m
compactor:
compaction:
block_retention: 72h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
+17
View File
@@ -0,0 +1,17 @@
global
tune.ssl.cachesize 0
defaults
mode http
timeout connect 1s
timeout client 60s
timeout server 60s
retries 0
frontend api
bind :8444 ssl crt /run/identity/server.pem ca-file /run/trust/ca.crt crl-file /run/trust/ca.crl verify required no-tls-tickets ssl-min-ver TLSv1.2
http-request deny unless { ssl_c_s_dn(cn) -m str lb-to-api }
default_backend uvicorn
backend uvicorn
server local unix@/run/api/api.sock
+16
View File
@@ -0,0 +1,16 @@
defaults
mode http
timeout connect 2s
timeout client 30s
timeout server 30s
retries 0
frontend listener-3100
bind :3100 ssl crt /run/identity/server.pem ca-file /run/trust/ca.crt verify required ssl-min-ver TLSv1.2
http-request allow if { ssl_c_s_dn(cn) -m str collector-export } { method POST } { path /otlp/v1/logs }
http-request allow if { ssl_c_s_dn(cn) -m str grafana-query } { path_beg /loki/api/v1/ } !{ path /loki/api/v1/push /loki/api/v1/delete }
http-request deny
default_backend local-3100
backend local-3100
server localhost 127.0.0.1:13100
+30
View File
@@ -0,0 +1,30 @@
defaults
mode http
timeout connect 2s
timeout client 30s
timeout server 30s
retries 0
frontend listener-4318
bind :4318 ssl crt /run/identity/server.pem ca-file /run/trust/ca.crt verify required ssl-min-ver TLSv1.2
http-request deny unless { ssl_c_s_dn(cn) -m str api-a api-b publisher worker recovery } { method POST } { path /v1/metrics /v1/logs /v1/traces }
default_backend local-4318
backend local-4318
server localhost 127.0.0.1:14318
frontend listener-9464
bind :9464 ssl crt /run/identity/server.pem ca-file /run/trust/ca.crt verify required ssl-min-ver TLSv1.2
http-request deny unless { ssl_c_s_dn(cn) -m str prometheus-scrape } { path /metrics }
default_backend local-9464
backend local-9464
server localhost 127.0.0.1:19464
frontend listener-8888
bind :8888 ssl crt /run/identity/server.pem ca-file /run/trust/ca.crt verify required ssl-min-ver TLSv1.2
http-request deny unless { ssl_c_s_dn(cn) -m str prometheus-scrape } { path /metrics }
default_backend local-8888
backend local-8888
server localhost 127.0.0.1:18888
+15
View File
@@ -0,0 +1,15 @@
defaults
mode http
timeout connect 2s
timeout client 30s
timeout server 30s
retries 0
frontend listener-9090
bind :9090 ssl crt /run/identity/server.pem ca-file /run/trust/ca.crt verify required ssl-min-ver TLSv1.2
http-request deny unless { ssl_c_s_dn(cn) -m str grafana-query } { path_beg /api/v1/ }
http-request deny if { path_beg /api/v1/admin /api/v1/write /api/v1/otlp }
default_backend local-9090
backend local-9090
server localhost 127.0.0.1:19090
+22
View File
@@ -0,0 +1,22 @@
defaults
mode http
timeout connect 2s
timeout client 30s
timeout server 30s
retries 0
frontend listener-4318
bind :4318 ssl crt /run/identity/server.pem ca-file /run/trust/ca.crt verify required ssl-min-ver TLSv1.2
http-request deny unless { ssl_c_s_dn(cn) -m str collector-export } { method POST } { path /v1/traces }
default_backend local-4318
backend local-4318
server localhost 127.0.0.1:14318
frontend listener-3200
bind :3200 ssl crt /run/identity/server.pem ca-file /run/trust/ca.crt verify required ssl-min-ver TLSv1.2
http-request deny unless { ssl_c_s_dn(cn) -m str grafana-query } { path_beg /api/ }
default_backend local-3200
backend local-3200
server localhost 127.0.0.1:13200
+14
View File
@@ -0,0 +1,14 @@
fastapi==0.152.0
starlette==1.3.1
uvicorn==0.34.2
pydantic==2.11.4
psycopg[binary]==3.2.6
psycopg-pool==3.2.6
argon2-cffi==23.1.0
boto3==1.38.12
Pillow==13.0.0
pika==1.3.2
opentelemetry-api==1.45.2
opentelemetry-sdk==1.45.2
opentelemetry-exporter-otlp-proto-http==1.45.2
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env python3
"""Operator-only OpenBao bootstrap, unseal and KV operations over verified HTTPS."""
import argparse
import base64
import fcntl
import json
import os
import ssl
import stat
from urllib.error import HTTPError
from urllib.request import HTTPSHandler, Request, build_opener
from pki import STATE
BASE = os.environ.get("LAB7_OPENBAO_URL", "https://localhost:18200").rstrip("/") + "/v1/"
OPERATOR = STATE / "operator/openbao-v2.json"
INIT_ATTEMPT = OPERATOR.with_suffix(".init-attempted")
STAGED_OPERATOR = OPERATOR.with_suffix(".pending")
OPERATOR_LOCK = OPERATOR.with_suffix(".lock")
def request(path, body=None, token=None, method=None, accepted=(), timeout=4):
if not BASE.startswith("https://"):
raise ValueError("OpenBao operator endpoint requires HTTPS")
context = ssl.create_default_context(cafile=str(STATE / "trust/ca.crt"))
# Existing lab roots omit Key Usage. Keep certificate and hostname
# verification against the explicit lab CA on Python 3.13 and newer.
context.verify_flags &= ~ssl.VERIFY_X509_STRICT
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
payload = None if body is None else json.dumps(body).encode()
req = Request(BASE + path, data=payload, headers=headers, method=method)
try:
response = build_opener(HTTPSHandler(context=context)).open(req, timeout=timeout)
except HTTPError as exc:
if exc.code not in accepted:
raise RuntimeError(f"OpenBao operation {path} returned {exc.code}") from None
response = exc
with response:
data = response.read()
return json.loads(data) if data else {}
def status():
return request("sys/health", accepted=(429, 501, 503))
def private_operator_directory():
directory = OPERATOR.parent
directory.mkdir(mode=0o700, exist_ok=True)
metadata = directory.lstat()
if (not stat.S_ISDIR(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) != 0o700
or metadata.st_uid != os.getuid()):
raise RuntimeError("OpenBao operator directory must be owned by this user with mode 0700")
return directory
def validate_operator(material):
try:
encoded_shares = material["keys_base64"]
token = material["root_token"]
if isinstance(encoded_shares, list) and len(encoded_shares) == 3:
shares = [base64.b64decode(share, validate=True) for share in encoded_shares]
if len(set(shares)) == 3 and all(shares) and isinstance(token, str) and token:
return material
except (KeyError, TypeError, ValueError):
pass
raise RuntimeError("Invalid OpenBao operator material")
def operator():
private_operator_directory()
try:
with os.fdopen(os.open(OPERATOR, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)) as file:
metadata = os.fstat(file.fileno())
if (not stat.S_ISREG(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) != 0o600
or metadata.st_uid != os.getuid()):
raise RuntimeError("OpenBao operator file must be owned by this user with mode 0600")
return validate_operator(json.load(file))
except (OSError, ValueError):
raise RuntimeError("OpenBao operator file is unavailable or unreadable; reconcile it before continuing") from None
def initialize():
directory = private_operator_directory()
if any(os.path.lexists(path) for path in (OPERATOR, INIT_ATTEMPT, STAGED_OPERATOR)):
raise RuntimeError("Existing OpenBao v2 operator files or init attempt require manual reconciliation")
directory_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
parent_fd = os.open(directory.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(parent_fd)
finally:
os.close(parent_fd)
# Reserve one attempt even if the server responds after a client timeout.
with os.fdopen(os.open(INIT_ATTEMPT, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as marker:
marker.write("OpenBao v2 initialization attempted\n")
marker.flush()
os.fsync(marker.fileno())
fd = os.open(STAGED_OPERATOR, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w+") as staged:
os.fchmod(staged.fileno(), 0o600)
os.fsync(directory_fd)
material = validate_operator(request("sys/init", {"secret_shares": 3, "secret_threshold": 2},
timeout=180))
json.dump(material, staged)
staged.flush()
os.fsync(staged.fileno())
staged.seek(0)
if json.load(staged) != material:
raise RuntimeError("OpenBao operator file verification failed")
# Hard-link publication is atomic and refuses to replace an existing file.
os.link(STAGED_OPERATOR, OPERATOR)
os.fsync(directory_fd)
if operator() != material:
raise RuntimeError("Published OpenBao operator file verification failed")
STAGED_OPERATOR.unlink()
os.fsync(directory_fd)
except (OSError, RuntimeError, ValueError):
raise RuntimeError(
"OpenBao initialization did not complete locally. Preserve the operator files and "
"check status before manual reconciliation. Initialization will not be retried."
) from None
finally:
os.close(directory_fd)
def unseal():
if status().get("sealed"):
for share in operator()["keys_base64"]:
result = request("sys/unseal", {"key": share})
if not result["sealed"]:
break
else:
raise RuntimeError("Unseal did not reach the configured threshold")
def conninfo(role, password=None):
value = password or (STATE / "postgres" / role).read_text().strip()
return (f"host=postgres dbname=messenger user={role} password={value} "
"sslmode=verify-full sslrootcert=/run/trust/ca.crt gssencmode=disable")
def configure():
api_role = os.environ.get("LAB7_API_DB_ROLE", "api_blue")
if api_role not in ("api_blue", "api_green"):
raise RuntimeError("LAB7_API_DB_ROLE must be api_blue or api_green")
token = operator()["root_token"]
if "cert/" not in request("sys/auth", token=token):
request("sys/auth/cert", {"type": "cert"}, token)
if "kv/" not in request("sys/mounts", token=token):
request("sys/mounts/kv", {"type": "kv", "options": {"version": "2"}}, token)
ca = (STATE / "trust/ca.crt").read_text()
for role in ("api-a", "api-b", "publisher", "worker", "recovery"):
scope = "api" if role.startswith("api-") else role
policy = (f'path "kv/data/messenger/{scope}" {{ capabilities = ["read"] }}\n'
'path "auth/token/renew-self" { capabilities = ["update"] }')
policy_path = f"sys/policies/acl/{scope}"
if not request(policy_path, token=token, accepted=(404,)).get("data"):
request(policy_path, {"policy": policy}, token)
cert_path = f"auth/cert/certs/{role}"
if not request(cert_path, token=token, accepted=(404,)).get("data"):
request(cert_path, {"certificate": ca,
"allowed_dns_sans": [f"{role}.bao.lab"], "token_policies": [scope],
"token_no_default_policy": True, "token_type": "service",
"token_ttl": "20s", "token_explicit_max_ttl": "60s"}, token)
for scope in ("api", "publisher", "worker", "recovery"):
path = f"kv/data/messenger/{scope}"
if request(path, token=token, accepted=(404,)).get("data"):
continue
data = {"database_url": conninfo(api_role if scope == "api" else scope)}
if scope != "publisher":
data.update(s3_user="lab-" + scope, s3_password=(STATE / "s3" / scope).read_text().strip())
request(path, {"options": {"cas": 0}, "data": data}, token)
def prepare_local_dsn():
for role in ("migrator", "ops"):
directory = STATE / role
directory.mkdir(exist_ok=True)
path = directory / "dsn"
if not path.exists():
path.write_text(conninfo(role))
path.chmod(0o444)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("bootstrap", "unseal", "status", "local-dsn"))
action = parser.parse_args().action
if action == "local-dsn":
prepare_local_dsn()
return
if action in ("bootstrap", "unseal"):
private_operator_directory()
fd = os.open(OPERATOR_LOCK, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
if action == "bootstrap" and not status()["initialized"]:
initialize()
unseal()
if action == "bootstrap":
configure()
state = status()
print(f"OpenBao initialized={state['initialized']} sealed={state['sealed']}")
if __name__ == "__main__":
main()
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
case "$#:${1:-}" in
0:) python3 scripts/pki.py init; python3 scripts/bao.py local-dsn ;;
1:--openbao-only) ;;
*) echo 'Usage: scripts/bootstrap.sh [--openbao-only]' >&2; exit 2 ;;
esac
./scripts/compose.sh up -d openbao
attempt=0
until python3 scripts/bao.py status >/dev/null 2>&1; do
attempt=$((attempt + 1))
test "$attempt" -lt 60
sleep 1
done
python3 scripts/bao.py bootstrap
if [ "${1:-}" = --openbao-only ]; then
exit 0
fi
./scripts/compose.sh up -d --build postgres s3 broker migrate \
otel-collector otel-tls prometheus prometheus-tls loki loki-tls tempo tempo-tls grafana
./scripts/compose.sh run --rm s3-bootstrap
./scripts/compose.sh up -d --wait --wait-timeout 120
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Check effective Compose privileges and the actual image user defaults."""
import json
import subprocess
import sys
STATEFUL = {"postgres", "broker", "openbao", "s3"}
ROOT_BOOTSTRAP = {"postgres", "broker", "volume-init"}
PUBLISHED = {"lb": 8443, "openbao": 8200, "grafana": 3000}
def check(config, image_user):
findings = []
for name, service in config["services"].items():
def require(condition, message):
if not condition:
findings.append(f"{name}: {message}")
require(not service.get("privileged") and service.get("network_mode") != "host",
"privileged mode or host network")
require(not service.get("pid") and not service.get("ipc") == "host", "host process or IPC namespace")
require(all("docker.sock" not in str(mount) for mount in service.get("volumes", [])),
"Docker socket mount")
require("no-new-privileges:true" in service.get("security_opt", []), "no-new-privileges absent")
require(bool(service.get("mem_limit") and service.get("cpus") and service.get("pids_limit")),
"CPU/RAM/PID limit absent")
for port in service.get("ports", []):
require(port.get("host_ip") == "127.0.0.1" and port["target"] == PUBLISHED.get(name),
"unexpected published port")
effective = service.get("user") or image_user(service["image"])
if name not in ROOT_BOOTSTRAP:
require(bool(effective) and effective.split(":")[0] not in {"0", "root"}, "effective image user is root")
if name not in STATEFUL:
require(service.get("read_only"), "writable root filesystem")
require("ALL" in service.get("cap_drop", []), "global capability drop absent")
require(not service.get("cap_add") or (name == "volume-init" and service["cap_add"] == ["CHOWN"]),
"unexpected capability grant")
return findings
def main():
config = json.load(sys.stdin)
def image_user(image):
return subprocess.check_output(
["docker", "image", "inspect", "--format", "{{.Config.User}}", image], text=True
).strip()
findings = check(config, image_user)
if findings:
print("\n".join(findings))
raise SystemExit(1)
print(f"PASS: effective Docker hardening for {len(config['services'])} services")
if __name__ == "__main__":
main()
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
if [ -d /Applications/Docker.app/Contents/Resources/bin ]; then
export PATH="/Applications/Docker.app/Contents/Resources/bin:$PATH"
fi
export LAB7_STATE="${LAB7_STATE:-/private/tmp/mtusi2026lab7-$(id -u)}"
if [ -x /Applications/Docker.app/Contents/Resources/cli-plugins/docker-compose ]; then
exec /Applications/Docker.app/Contents/Resources/cli-plugins/docker-compose "$@"
fi
exec docker compose "$@"
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
python_absent() {
for file in /run/trust/ca.crt /run/identity/client.crt /run/identity/client.key; do
test -s "$file"
done
}
python_absent
export LAB_CA="$(cat /run/trust/ca.crt)"
export LAB_CERT="$(cat /run/identity/client.crt)"
export LAB_KEY="$(cat /run/identity/client.key)"
exec /run.sh
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
"""Create a disposable CA and role-specific credentials outside the worktree."""
import argparse
import os
from pathlib import Path
import secrets
import subprocess
ROOT = Path(__file__).resolve().parents[1]
STATE = Path(os.getenv("LAB7_STATE", f"/private/tmp/mtusi2026lab7-{os.getuid()}")).resolve()
def openssl(*args):
subprocess.run(["openssl", *map(str, args)], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, cwd=STATE / "authority")
def public(path):
path.chmod(0o444)
def issue(directory, stem, identity, usage, names=()):
target = STATE / directory
target.mkdir(mode=0o755, exist_ok=True)
cert, key = target / f"{stem}.crt", target / f"{stem}.key"
if cert.exists() and key.exists():
return
csr = STATE / "authority/request.pem"
extensions = STATE / "authority/extensions"
extensions.write_text("basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\n"
f"extendedKeyUsage={usage}\n"
+ ("subjectAltName=" + ",".join(names) + "\n" if names else ""))
openssl("req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj", f"/CN={identity}",
"-keyout", key, "-out", csr)
openssl("ca", "-batch", "-notext", "-config", "ca.cnf", "-extfile", extensions,
"-in", csr, "-out", cert)
public(cert)
public(key)
(target / f"{stem}.pem").write_bytes(cert.read_bytes() + key.read_bytes())
public(target / f"{stem}.pem")
def crl():
authority = STATE / "authority"
openssl("ca", "-config", "ca.cnf", "-gencrl", "-out", authority / "next.crl")
path = STATE / "trust/ca.crl"
public(authority / "next.crl")
(authority / "next.crl").replace(path)
def secret(directory, name):
path = STATE / directory / name
if not path.exists():
path.write_text(secrets.token_hex(24))
public(path)
def init():
if STATE == ROOT or ROOT in STATE.parents:
raise SystemExit("LAB7_STATE must be outside the repository")
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
STATE.chmod(0o700)
authority = STATE / "authority"
authority.mkdir(mode=0o700, exist_ok=True)
trust = STATE / "trust"
trust.mkdir(mode=0o755, exist_ok=True)
if not (authority / "ca.key").exists():
openssl("req", "-x509", "-newkey", "rsa:3072", "-nodes", "-days", "365",
"-addext", "keyUsage=critical,keyCertSign,cRLSign",
"-subj", "/CN=MTUSI Lab7 local CA", "-keyout", "ca.key", "-out", "ca.crt")
(authority / "ca.key").chmod(0o600)
(authority / "ca.cnf").write_text("""[ca]
default_ca = local
[local]
database = index.txt
new_certs_dir = issued
certificate = ca.crt
private_key = ca.key
serial = serial
default_md = sha256
default_days = 30
default_crl_days = 30
unique_subject = no
policy = names
[names]
commonName = supplied
""")
(authority / "issued").mkdir()
(authority / "index.txt").touch()
(authority / "serial").write_text("1000\n")
if not (trust / "ca.crt").exists():
(trust / "ca.crt").write_bytes((authority / "ca.crt").read_bytes())
public(trust / "ca.crt")
if not (trust / "ca.crl").exists():
crl()
for name in ("lb", "api-a-tls", "api-b-tls", "postgres", "s3", "broker",
"openbao", "otel", "prometheus", "loki", "tempo", "grafana"):
aliases = [f"DNS:{name}"]
if name in ("lb", "openbao", "grafana"):
aliases += ["DNS:localhost", "IP:127.0.0.1"]
if name == "otel":
aliases.append("DNS:otel-collector")
issue(name, "server", name, "serverAuth", aliases)
for source, target in (("server.crt", "public.crt"), ("server.key", "private.key")):
path = STATE / "s3" / target
if not path.exists():
path.write_bytes((STATE / "s3" / source).read_bytes())
public(path)
for name in ("api-a", "api-b", "publisher", "worker", "recovery"):
issue(name, "bao", name, "clientAuth", (f"DNS:{name}.bao.lab",))
issue(name, "otel", name, "clientAuth")
for name in ("publisher", "worker", "ops"):
issue(name, "amqp", name if name != "ops" else "ops-redeliver", "clientAuth")
for owner, role in (("lb", "lb-to-api"), ("otel", "collector-export"),
("prometheus", "prometheus-scrape"), ("grafana", "grafana-query"),
("probe", "prohibited-service")):
issue(owner, "client", role, "clientAuth")
(STATE / "s3/CAs").mkdir(exist_ok=True)
foreign = STATE / "probe/foreign.crt"
if not foreign.exists():
openssl("req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "10",
"-subj", "/CN=foreign", "-keyout", foreign.with_suffix(".key"), "-out", foreign)
public(foreign)
public(foreign.with_suffix(".key"))
(STATE / "rotation").mkdir(mode=0o755, exist_ok=True)
for directory, names in {
"postgres": ("admin", "migrator", "api_blue", "publisher", "worker", "recovery", "ops"),
"s3": ("admin", "api", "worker", "recovery"), "grafana": ("admin",),
}.items():
for name in names:
secret(directory, name)
operator = STATE / "operator"
operator.mkdir(mode=0o700, exist_ok=True)
print(STATE)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("init", "issue-lb", "revoke-lb"))
args = parser.parse_args()
if args.action == "init":
init()
elif args.action == "issue-lb":
issue("rotation", "client", "lb-to-api", "clientAuth")
else:
openssl("ca", "-config", "ca.cnf", "-revoke", STATE / "rotation/old.pem")
crl()
if __name__ == "__main__":
main()
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
./scripts/compose.sh restart openbao postgres s3 broker api-a api-b publisher worker recovery
attempt=0
until python3 scripts/bao.py unseal; do
attempt=$((attempt + 1))
test "$attempt" -lt 15
sleep 1
done
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Rotate API PostgreSQL access without invalidating the published KV generation."""
import argparse
import fcntl
import os
import secrets
import shlex
import subprocess
import time
from pathlib import Path
from bao import conninfo, operator, request
from pki import STATE
ROOT = Path(__file__).resolve().parents[1]
PATH = "kv/data/messenger/api"
ALTERNATE = {"api_blue": "api_green", "api_green": "api_blue"}
def compose(*arguments, data=None):
return subprocess.run([str(ROOT / "scripts/compose.sh"), *arguments], input=data,
capture_output=True, text=True, timeout=15, check=True).stdout.strip()
def sql(statement):
return compose("exec", "-T", "--user", "postgres", "postgres", "psql", "-XqAt",
"-v", "ON_ERROR_STOP=1", "-d", "messenger", data=statement)
def db_probe(info):
code = (
"import sys,psycopg; "
"c=psycopg.connect(sys.stdin.read(),connect_timeout=3); "
"print(c.execute('select session_user from pg_stat_ssl where pid=pg_backend_pid() and ssl').fetchone()[0]); "
"c.close()"
)
return compose("exec", "-T", "api-a", "python", "-c", code, data=info)
def read_generation(token):
document = request(PATH, token=token)["data"]
info = document["data"]["database_url"]
fields = dict(field.split("=", 1) for field in shlex.split(info))
role = fields.get("user")
if role not in ALTERNATE or fields.get("sslmode") != "verify-full":
raise RuntimeError("The published API credential does not match the supported roles and TLS mode")
return document, info, role
def await_active(role):
deadline = time.monotonic() + 50
while time.monotonic() < deadline:
for instance in ("api-a", "api-b"):
compose("exec", "-T", instance, "python", "/app/uds_probe.py")
count = sql(f"SELECT count(DISTINCT client_addr) FROM pg_stat_activity WHERE usename='{role}' AND backend_type='client backend';")
if count == "2":
return
time.sleep(1)
raise RuntimeError("Both replicas have not acquired the published role; the previous credential remains enabled")
def retire(token, current, info, active, old_info=None):
previous = ALTERNATE[active]
await_active(active)
deadline = time.monotonic() + 25
while sql(f"SELECT count(*) FROM pg_stat_activity WHERE usename='{previous}';") != "0":
if time.monotonic() >= deadline:
raise RuntimeError("Previous sessions did not drain; both credentials remain usable")
time.sleep(1)
# CAS protects the publication itself. A final version check also prevents
# retiring an identity after an unrelated change during convergence.
latest, _, _ = read_generation(token)
if latest["metadata"]["version"] != current["metadata"]["version"] or db_probe(info) != active:
raise RuntimeError("KV generation changed or TLS verification failed before retirement")
sql(f"ALTER ROLE {previous} PASSWORD NULL;")
if sql(f"SELECT (rolpassword IS NULL)::int FROM pg_authid WHERE rolname='{previous}';") != "1":
raise RuntimeError("Could not verify retirement of the previous password")
if old_info is not None:
try:
db_probe(old_info)
except subprocess.CalledProcessError as exc:
if "password authentication failed" not in exc.stderr:
raise RuntimeError("The previous password denial was not verified") from None
else:
raise RuntimeError("The previous password still authenticates")
if db_probe(info) != active:
raise RuntimeError("Published PostgreSQL credential could not be verified after retirement")
def rotate(token, resume=False):
current, old_info, active = read_generation(token)
if db_probe(old_info) != active:
raise RuntimeError("The published PostgreSQL credential did not pass the TLS probe")
if resume:
retire(token, current, old_info, active)
return
alternate = ALTERNATE[active]
password = secrets.token_hex(24)
sql("SET log_statement=none; SET log_min_error_statement=panic; "
f"ALTER ROLE {alternate} LOGIN PASSWORD '{password}';")
new_info = conninfo(alternate, password)
if db_probe(new_info) != alternate:
raise RuntimeError("The replacement PostgreSQL credential did not pass the TLS probe")
try:
request(PATH, {"data": dict(current["data"], database_url=new_info),
"options": {"cas": current["metadata"]["version"]}}, token)
except (OSError, RuntimeError, ValueError):
# A timeout can follow a committed KV write. Neither role is retired
# on uncertainty and blindly issuing another rotation is unsafe.
raise RuntimeError("KV CAS outcome uncertain; both credentials remain usable. Inspect KV and use --retire-previous.") from None
published, info, role = read_generation(token)
if info != new_info or role != alternate:
raise RuntimeError("OpenBao did not return the expected replacement generation")
retire(token, published, info, role, old_info)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--retire-previous", action="store_true",
help="verify the currently published generation and retire only the other role")
args = parser.parse_args()
lock = STATE / "operator/rotate-db.lock"
with os.fdopen(os.open(lock, os.O_CREAT | os.O_WRONLY | os.O_NOFOLLOW, 0o600), "w") as file:
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
rotate(operator()["root_token"], args.retire_previous)
print("PASS: both API replicas use the published TLS credential; the other password is retired")
if __name__ == "__main__":
try:
main()
except RuntimeError as exc:
raise SystemExit(str(exc)) from None
except (OSError, subprocess.SubprocessError, ValueError, KeyError):
raise SystemExit("Rotation stopped. Inspect the active KV generation before resuming; no credentials printed.") from None
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Rotate the allowlisted LB client leaf and roll the CRL across both API proxies."""
import fcntl
import hashlib
import os
import subprocess
import time
from pki import ROOT, STATE, issue, openssl, crl
CONFIG = "/usr/local/etc/haproxy/haproxy.cfg"
def compose(*args, capture=False):
return subprocess.run([str(ROOT / "scripts/compose.sh"), *args], check=True, timeout=45,
capture_output=capture).stdout
def reload(service):
host_file = STATE / ("lb/client.pem" if service == "lb" else "trust/ca.crl")
mounted_file = "/run/identity/client.pem" if service == "lb" else "/run/trust/ca.crl"
expected = hashlib.sha256(host_file.read_bytes()).hexdigest().encode()
for _ in range(25):
try:
actual = compose("exec", "-T", service, "sha256sum", mounted_file, capture=True).split()[0]
if expected == actual:
compose("exec", "-T", service, "haproxy", "-c", "-f", CONFIG, capture=True)
break
except subprocess.CalledProcessError:
pass
time.sleep(0.2)
else:
raise RuntimeError("HAProxy cannot read or validate the newly mounted TLS file")
before = compose("exec", "-T", service, "cat", "/proc/1/task/1/children", capture=True).split()
compose("exec", "-T", service, "sh", "-ec",
'tr "\\000" " " </proc/1/cmdline | grep -Eq "(^|/)haproxy .* -W |^haproxy -W "; kill -USR2 1')
for _ in range(25):
after = compose("exec", "-T", service, "cat", "/proc/1/task/1/children", capture=True).split()
if set(after).difference(before):
return
time.sleep(0.2)
raise RuntimeError("HAProxy did not start a replacement worker")
def probe(mode):
for attempt in range(5):
try:
compose("run", "--rm", "-T", "probe", mode)
return
except subprocess.CalledProcessError:
if attempt == 4:
raise
time.sleep(2)
def install(directory, name, data):
temporary = directory / (name + ".next")
with temporary.open("xb") as file:
os.fchmod(file.fileno(), 0o444)
file.write(data)
file.flush()
os.fsync(file.fileno())
temporary.replace(directory / name)
def rotate():
previous = STATE / "rotation"
lb = STATE / "lb"
target = previous / f"candidate-{time.time_ns()}"
issue(str(target), "client", "lb-to-api", "clientAuth", ("DNS:lb-to-api",))
openssl("verify", "-purpose", "sslclient", "-verify_hostname", "lb-to-api",
"-CAfile", STATE / "trust/ca.crt", target / "client.crt")
# Prove the intended identity is in SAN as well as the CN enforced by HAProxy.
subprocess.run(["openssl", "x509", "-in", str(target / "client.crt"), "-noout",
"-ext", "subjectAltName"], check=True, capture_output=True).stdout.index(b"DNS:lb-to-api")
old = (lb / "client.pem").read_bytes()
install(previous, "old.pem", old)
install(lb, "client.pem", (target / "client.pem").read_bytes())
try:
reload("lb")
probe("leaf-current")
except (OSError, RuntimeError, subprocess.SubprocessError):
install(lb, "client.pem", old)
reload("lb")
raise
# From here the replacement stays installed, including on partial CRL rollout.
openssl("ca", "-config", "ca.cnf", "-revoke", previous / "old.pem")
crl()
for service in ("api-a-tls", "api-b-tls"):
reload(service)
probe("leaf-current")
probe("leaf-revoked")
print("PASS: new LB leaf accepted; old leaf denied on both API TLS listeners")
if __name__ == "__main__":
try:
lock = STATE / "operator/rotate-leaf.lock"
with os.fdopen(os.open(lock, os.O_CREAT | os.O_WRONLY | os.O_NOFOLLOW, 0o600), "w") as file:
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
rotate()
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError):
raise SystemExit("Leaf rotation stopped; inspect active certificate and CRL before rerunning.") from None
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Output JSON reports. Exit nonzero on scanner findings or incomplete runs.
set -eu
cd "$(dirname "$0")/.."
: "${SCAN_OUTPUT:?Set SCAN_OUTPUT to a report directory}"
mkdir -p "$SCAN_OUTPUT"
out=$(cd "$SCAN_OUTPUT" && pwd -P)
mkdir -p "${SCAN_CACHE:-$out/cache}"
cache=$(cd "${SCAN_CACHE:-$out/cache}" && pwd -P)
audit=${PIP_AUDIT:-pip-audit}
scanner=aquasec/trivy:0.66.0@sha256:086971aaf400beebd94e8300fd8ea623774419597169156cec56eec5b00dfb1e
status=0
./scripts/compose.sh --profile operator --profile bootstrap config --format json |
python3 scripts/check-hardening.py > "$out/hardening.txt" || status=1
# Audit the exact installed dependency set, including transitive dependencies.
app_image=$(./scripts/compose.sh config --format json |
python3 -c 'import json,sys; print(json.load(sys.stdin)["services"]["migrate"]["image"])')
docker run --rm --network none --entrypoint python "$app_image" \
-m pip freeze > "$out/runtime-pins.txt"
"$audit" --no-deps --disable-pip -r "$out/runtime-pins.txt" -f json -o "$out/python.json" || status=1
"$audit" -r requirements-dev.txt -f json -o "$out/dev-python.json" || status=1
docker run --rm --mount "type=bind,src=$PWD,dst=/project,readonly" \
--mount "type=bind,src=$cache,dst=/cache" --mount "type=bind,src=$out,dst=/results" \
"$scanner" --cache-dir /cache \
config --skip-files /project/Dockerfile.example --misconfig-scanners dockerfile --exit-code 1 --format json \
--output /results/dockerfiles.json /project || status=1
./scripts/compose.sh --profile operator --profile bootstrap config --images | sort -u > "$out/images.txt"
while IFS= read -r image; do
name=$(printf '%s' "$image" | tr '/:@' '___')
archive=$(mktemp "$out/image.XXXXXX")
if docker save -o "$archive" "$image"; then
docker run --rm -e "TRIVY_SKIP_DB_UPDATE=${TRIVY_SKIP_DB_UPDATE:-false}" \
--mount "type=bind,src=$cache,dst=/cache" --mount "type=bind,src=$out,dst=/results" \
"$scanner" --cache-dir /cache \
image --input "/results/${archive##*/}" --scanners vuln --image-config-scanners misconfig \
--severity HIGH,CRITICAL --exit-code 1 --format json --output "/results/$name.json" || status=1
else
status=1
fi
if [ -f "$archive" ]; then unlink "$archive"; fi
done < "$out/images.txt"
exit "$status"
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?target API instance required}"
for service in api-a api-b; do
actual=$(./scripts/compose.sh exec -T "$service" python /app/uds_probe.py live) || continue
if [ "$actual" = "$TARGET_INSTANCE_ID" ]; then
if [ -n "${STOP_ONE_EVIDENCE:-}" ]; then
printf '%s\n' "$service" > "$STOP_ONE_EVIDENCE"
fi
exec ./scripts/compose.sh stop -t 2 "$service"
fi
done
exit 1
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Inventory comparable pip-audit and Trivy reports without counting duplicate paths."""
import argparse
from collections import Counter, defaultdict
import json
from pathlib import Path
def surface(package):
if package in {"pillow", "starlette", "fastapi", "opentelemetry-api"}:
return {
"pillow": "JPEG/PNG exposed; other codecs restricted",
"starlette": "ASGI/HTTP used; check the affected API",
"fastapi": "ASGI/HTTP used; check the affected API",
"opentelemetry-api": "trace context consumed from broker",
}[package]
if package in {"openssl", "libssl3", "libssl3t64", "libcrypto3", "gnutls", "libgnutls30"}:
return "TLS library present; verify process, platform and affected feature"
if package == "stdlib" or "/" in package:
return "Embedded Go dependency; module presence alone does not show reachable code"
return "Image package present; process and affected feature not established"
def advisory_id(aliases):
return min(aliases, key=lambda value: (not value.startswith("CVE-"), not value.startswith("GHSA-"), value))
def load(directory):
audit = json.loads((directory / "python.json").read_text())
images = (directory / "images.txt").read_text().splitlines()
rows = []
aliases = {}
python_entries = 0
image_counts = Counter()
for dependency in audit["dependencies"]:
for item in dependency.get("vulns", []):
python_entries += 1
group = {item["id"], *item.get("aliases", [])}
for key in group.copy():
group.update(aliases.get(key, ()))
for key in group:
aliases[key] = group
rows.append(("Python runtime", dependency["name"], dependency["version"], item["id"],
"not supplied", ", ".join(item["fix_versions"]), "pip-audit"))
for image in images:
stem = image.translate(str.maketrans("/:@", "___"))
report = json.loads((directory / f"{stem}.json").read_text())
if not report.get("Metadata", {}).get("ImageID"):
raise ValueError(f"Incomplete Trivy report for {image}")
for result in report.get("Results", []):
for item in result.get("Vulnerabilities", []):
image_counts[item["Severity"]] += 1
rows.append((image, item["PkgName"], item["InstalledVersion"], item["VulnerabilityID"],
item["Severity"], item.get("FixedVersion", ""), result["Target"]))
grouped = defaultdict(set)
for image, package, version, identifier, severity, fix, target in rows:
group = aliases.get(identifier, {identifier})
normalized = advisory_id(group)
grouped[image, package, version, normalized, severity, fix].add(target)
return grouped, python_entries, image_counts, aliases
def family(image):
repository = image.split("@", 1)[0].rsplit(":", 1)[0]
if repository.startswith("mtusi2026lab7-"):
return "local-" + repository.rsplit("-", 1)[-1]
return repository
def print_table(rows):
print("| Image | Package | Installed | ID | Severity | Vendor fix | Targets | Applicability review |")
print("| --- | --- | --- | --- | --- | --- | --- | --- |")
for (image, package, version, identifier, severity, fix), targets in sorted(rows.items()):
fields = (image, package, version, identifier, severity, fix or "not reported",
", ".join(sorted(targets)), surface(package))
print("| " + " | ".join(value.replace("|", "\\|").replace("\n", " ") for value in fields) + " |")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", type=Path)
parser.add_argument("--baseline", type=Path)
args = parser.parse_args()
grouped, python_entries, image_counts, aliases = load(args.directory)
identities = {row[3] for row in grouped if row[0] != "Python runtime"}
py_identities = {row[3] for row in grouped if row[0] == "Python runtime"}
print("# Inventory")
print()
print(f"Python input rows: {python_entries}, distinct advisory IDs after aliases: {len(py_identities)}.")
print(f"Image input rows: {sum(image_counts.values())} ({dict(sorted(image_counts.items()))}), "
f"distinct advisory IDs: {len(identities)}, CVE IDs: {sum(x.startswith('CVE-') for x in identities)}.")
if args.baseline:
old, _, _, old_aliases = load(args.baseline)
def coordinate(row):
image, package, _, identifier, _, _ = row
related = {identifier, *aliases.get(identifier, ()), *old_aliases.get(identifier, ())}
return family(image), package, advisory_id(related)
old_coordinates = {coordinate(row) for row in old}
new_coordinates = {coordinate(row) for row in grouped}
print("\n## Baseline findings absent from the new image or runtime\n")
print_table({row: targets for row, targets in old.items() if coordinate(row) not in new_coordinates})
print("\n## Newly reported placements\n")
print_table({row: targets for row, targets in grouped.items() if coordinate(row) not in old_coordinates})
print("\n## Grouped findings\n")
print_table(grouped)
if __name__ == "__main__":
main()
+19
View File
@@ -0,0 +1,19 @@
import http.client
import socket
import sys
class LocalConnection(http.client.HTTPConnection):
def connect(self):
self.sock = socket.socket(socket.AF_UNIX)
self.sock.settimeout(3)
self.sock.connect("/run/api/api.sock")
connection = LocalConnection("localhost")
connection.request("GET", "/health/" + ("live" if len(sys.argv) > 1 else "ready"))
response = connection.getresponse()
if response.status != 200:
raise SystemExit(1)
if len(sys.argv) > 1:
print(response.getheader("X-Instance-Id"))
+97
View File
@@ -0,0 +1,97 @@
# Уязвимости зависимостей и образов
Исходный снимок охватывает 44 Python-пакета и 12 образов. Python-аудит
содержит 68 записей, Trivy — 1302 HIGH и 97 CRITICAL. В Trivy это 283 идентификатора, в том числе 279 CVE, и 899 сочетаний ID, пакета и установленной версии. В pip-audit сопоставление алиасов оставило 68 отдельных advisory ID; они не суммируются с образом приложения. Записи повторяются между
бинарниками, пакетами и образами. При сравнении учитываются идентификаторы и
алиасы, экземпляры пакета, установленная версия и область использования.
## План изменений до обновлений
| Группа | Исходная версия и поверхность | Кандидат и совместимость | Решение о проверке |
| --- | --- | --- | --- |
| Pillow | 11.2.1, 59 записей. JPEG/PNG поступают извне. TIFF, шрифты и прочие форматы не входят в рабочий путь декодера. | 13.0.0 покрывает самые поздние исправления снимка. Проверить wheels для 3.11 и 3.13 и возможные изменения кодеков. | Высокий приоритет. Проверить MIME, EXIF, JPEG/WebP, сохранность оригинала и pipeline. |
| Starlette | 0.46.2, 7 записей. HTTP/маршрутизация используются. Multipart и файловые ответы Starlette отсутствуют в пути загрузки. | Starlette 1.3.1 и FastAPI 0.152.0 допускаются опубликованными ограничениями PyPI. | Проверить API, сессии, upload, заголовки и оба Python. |
| OpenTelemetry Python | 1.31.1, 2 записи. Извлечение trace context работает в Worker на входе из брокера. | Совместно обновить API, SDK и OTLP HTTP exporter до 1.45.2. Возможны изменения Logging SDK. | Проверить метрики, логи, трассы и отсутствие секретов. |
| Python, PostgreSQL, HAProxy, RabbitMQ, OpenBao | Наиболее важны активные сетевые библиотеки, PostgreSQL и брокер. Вспомогательные библиотеки разбираются отдельно от серверных путей. | Предпочесть исправленный патч той же ветки и совместимый OS-вариант. PostgreSQL 16.16 и HAProxy 3.0.32 — кандидаты. | Сборка, TLS/mTLS, ACL и failover. Для рабочего PostgreSQL проверить примечания по миграции. |
| Telemetry и Grafana | Loki 3.4.3, Tempo 2.7.2, Prometheus 3.2.1, Collector 0.123.0, Grafana 11.6.0. Используются TLS, HTTP/OTLP и query APIs. | Сначала патчи совместимых веток. Новый формат хранилища или удалённый конфиг требуют отдельной проверки. | Проверить Grafana, сигналы и datasource ACL. |
| MinIO и BusyBox | MinIO даёт 433 строки при 143 ID внутри образа. Есть повторы Go-модулей между двоичными файлами. BusyBox даёт 0 HIGH/CRITICAL. | MinIO менять после подтверждения pinned-релиза, ARM64, TLS, UID, IAM и формата данных. BusyBox сохраняется. | Для исправлений embedded Go нужен исправленный бинарник поставщика. OS-обновление его не заменяет. |
| Dev-validator | openapi-spec-validator 0.7.2 находится вне runtime. | Отдельный аудит dev-окружения. Обновление при наличии находок и прохождении OpenAPI 3.1. | Dev-инструменты остаются вне образа приложения. |
Источники кандидатов — [Pillow](https://pypi.org/project/Pillow/13.0.0/),
[OpenTelemetry SDK](https://pypi.org/project/opentelemetry-sdk/1.45.2/),
[FastAPI](https://pypi.org/project/fastapi/),
[PostgreSQL 16.16](https://www.postgresql.org/docs/16/release-16-16.html) и
[HAProxy 3.0](https://www.haproxy.org/bugs/bugs-3.0.html).
## Исходные группы образов
| Образ | Строк / ID внутри образа | Поверхность и ограничение вывода |
| --- | ---: | --- |
| App, Python 3.11.16 Bookworm | 153 / 88 | Python-декодер и ASGI доступны через API. Kerberos/GSSAPI установлен как OS-компонент; DSN приложения использует SCRAM и отключает GSS encryption. |
| PostgreSQL 16.8 | 260 / 143 | Сервер PostgreSQL, TLS и auth используются. Отдельно учитываются поставляемые инструменты и OS-пакеты. |
| HAProxy 3.0.9 Alpine | 31 / 18 | TLS, OpenSSL и обработка HTTP активны. CVE-2026-31789 ограничен 32-bit по описанию; образ испытаний ARM64. |
| RabbitMQ 4.1.4 | 7 / 4 | TLS и AMQP используются; apt/gpgv нужны при управлении образом. |
| OpenBao 2.7.3 | 9 / 4 | Alpine OpenSSL/BusyBox присутствуют. Применимость к основному Go TLS-процессу проверяется отдельно. |
| MinIO 2025.7.23 Debian | 433 / 143 | Основной S3-сервер доступен во внутренней сети. В отчёте есть отдельные находки для утилит и embedded Go dependencies. |
| Collector 0.123.0 | 81 / 77 | Активен OTLP/HTTP. Go gRPC и AMQP-модули в составе сборки не равнозначны включённым receivers. |
| Grafana 11.6.0 | 165 / 91 | HTTPS UI и datasource proxy активны; встроенные интеграции требуют проверки конфигурации. |
| Loki 3.4.3 | 55 / 52 | OTLP/HTTP ingest и query активны через proxy, внутренний gRPC отделён от ingress. |
| Tempo 2.7.2 | 93 / 76 | OTLP/HTTP ingest и trace query активны через proxy, внутренний gRPC отделён от ingress. |
| Prometheus 3.2.1 | 112 / 54 | Scrape и HTTP query используются; прочие transport modules проверяются отдельно. |
| BusyBox 1.37.0-musl | 0 / 0 | Одноразовый init и локальные healthcheck-утилиты. Здесь учтены только HIGH/CRITICAL. |
В полном инвентаре для каждой группы сохранены образ, пакет, версия,
CVE или advisory ID, severity сканера, доступная версия исправления и цели
сканирования. Повтор одного пакета в нескольких бинарниках отражается в поле
Targets. Уязвимость в версии поставляемого пакета и достижимый путь эксплуатации
оцениваются отдельно. Инвентарь воспроизводится так:
```sh
python3 scripts/summarize-security.py /path/to/baseline
python3 scripts/summarize-security.py /path/to/new-scan --baseline /path/to/baseline
```
## Повторное сканирование 4 декабря 2026 года
Trivy 0.66.0 проверил все 12 ARM64-образов с той же базой от 3 декабря
2026 года, 19:06 UTC. pip-audit 2.9.0 проверил 43 пакета, установленных
в обновлённом app image, и 18 пакетов dev-окружения. В обоих аудитах Python
0 находок. Исходные 68 записей относились к Pillow, Starlette и OpenTelemetry
API. Обновлены Pillow до 13.0.0, FastAPI до 0.152.0, Starlette до 1.3.1 и
OpenTelemetry до 1.45.2.
| Образ | HIGH / CRITICAL до | HIGH / CRITICAL после | ID после |
| --- | ---: | ---: | ---: |
| MinIO | 399 / 34 | 399 / 34 | 143 |
| BusyBox | 0 / 0 | 0 / 0 | 0 |
| OpenBao | 9 / 0 | 9 / 0 | 4 |
| HAProxy | 29 / 2 | 7 / 0 | 3 |
| App | 143 / 10 | 103 / 5 | 43 |
| Grafana | 155 / 10 | 157 / 6 | 90 |
| Loki | 53 / 2 | 25 / 0 | 22 |
| Collector | 74 / 7 | 71 / 7 | 74 |
| Prometheus | 108 / 4 | 66 / 0 | 31 |
| Tempo | 89 / 4 | 50 / 0 | 45 |
| PostgreSQL | 236 / 24 | 132 / 4 | 65 |
| RabbitMQ | 7 / 0 | 0 / 0 | 0 |
| Всего строк | 1302 / 97 | 1019 / 56 | 191 уникальный ID по всем образам |
Уникальные CVE по всему стенду сократились с 279 до 188. Сочетаний
ID/пакет/версия осталось 664 из 899. При сравнении по семейству образа,
пакету и ID исчезло 333 сочетания, появилось 39. В частности, у Grafana
выросло число строк HIGH с 155 до 157. Полный сравнительный инвентарь
перечисляет новые сочетания и версии исправлений.
| Остаточная группа | Применимость и обоснование |
| --- | --- |
| MinIO 2025.7.23, 433 строки | S3 и Go TLS используются. CVE-2026-33322 (OIDC) и CVE-2026-33419 (LDAP) относятся к отключённым в этой конфигурации провайдерам. Для CVE-2025-68121 в Go TLS применимость к используемому поведению сессий отдельно не подтверждалась. Изоляция S3, статические IAM identities и ACL снижают доступность снаружи, риск внутри стенда остаётся. Сохранён проверенный digest, пока нет проверенной замены с совместимыми TLS, IAM и данными. Обновление Debian-пакетов само по себе не исправляет встроенные Go-модули. |
| Collector, Grafana, Loki, Tempo, Prometheus | У Collector включён OTLP/HTTP; в его конфигурации отсутствуют AMQP и PostgreSQL receivers. Для CVE-2026-33186 в gRPC и CVE-2026-77405/77408/77411 в AMQP наличие модуля не устанавливает достижимость уязвимого пути. В Grafana provisioned datasources используют HTTP APIs Prometheus, Loki и Tempo. Это ограничивает сценарий с pgx (CVE-2026-33815/33816), оставляя другие зависимости и активные HTTP/TLS-пути предметом остаточного риска. |
| App и PostgreSQL | PostgreSQL, TLS и JPEG/PNG доступны по рабочим путям. Приложение использует SCRAM с `gssencmode=disable` и PostgreSQL вместо SQLite. Сканер всё равно учитывает Kerberos, SQLite и утилиты образов. Для CVE-2026-8376 в Perl условие 32-bit не выполняется на ARM64. Для других advisories Perl, zlib и libxml2 вывод ограничен путями, проверенными в приложении и сканером. |
| OpenBao и HAProxy | Сетевые TLS-пути активны. Находки OpenBao относятся к пакетам Alpine, в том числе OpenSSL и BusyBox; связь с основным Go-процессом не установлена. Для CVE-2026-31789 в OpenSSL заявлен сценарий 32-bit. Остаточные HIGH требуют оценки по используемым библиотекам и платформе. |
| Trivy misconfiguration | DS002 касается пользователя образа: PostgreSQL и RabbitMQ меняют UID в entrypoint, telemetry ограничена эффективным Compose. DS026 относится к healthchecks в Dockerfile, а healthchecks заданы в Compose. DS025 и DS029 относятся к сборке upstream-образов HAProxy и Grafana. Проверка эффективной конфигурации прошла для 25 сервисов. |
Исходные JSON, повторные JSON и сравнение сохранены соответственно в
`/private/tmp/lab7-grade4-scan`, `/private/tmp/lab7-security-rescan`
и `/private/tmp/lab7-security-comparison.md`. Код выхода 1 у общего скана
соответствует находкам Trivy. Наличие JSON подтверждено для каждого образа,
оба аудита Python завершены. Вывод ограничен снимком базы и конфигурацией стенда.
+30 -14
View File
@@ -1,19 +1,35 @@
# Модель угроз — заполнить
# Модель угроз лабораторной 7
## Активы и акторы
Активы — пароли и сессии пользователей, сообщения и вложения, права сервисов
в PostgreSQL, MinIO, RabbitMQ и OpenBao, CA и ключи, telemetry. Внешний клиент
может создавать запросы к ingress. Аутентифицированный посторонний может знать
UUID чата и вложения. Сервис со скомпрометированным сертификатом может обращаться
к своим сетям и пытаться использовать сертификат на соседних сервисах.
Оператор имеет локальный доступ к Docker и к CA. Компрометация оператора или
Docker-хоста находится за пределами модели одного учебного стенда.
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
Публичная граница — HTTPS ingress. На внутренней границе сервисы используют
проверяемый TLS, индивидуальные identities и ACL. Операторские материалы
хранятся вне исходников. Маршруты, порты, сроки и проверки перечислены в
[матрице доверия](../contracts/trust-matrix.md).
## Границы доверия
| Угроза | Компонент и контроль | Ожидаемое поведение | Наблюдение |
| --- | --- | --- | --- |
| Подмена сервера чужим CA или другим именем | Ingress, проверка цепочки и SAN | Доверенный HTTPS проходит, неверная цепочка или SAN отклоняются | `make test-security` отклонил пустой trust store. `probe matrix` проверяет неверный hostname. |
| Посторонний обращается к чужому вложению или подменяет X-User-Id | Bearer и проверка членства в чате | Metadata/content и прикрепление недоступны, X-User-Id не меняет личность | Публичный `make test` прошёл сценарии ACL и подмены заголовка. |
| Перехваченный или отозванный leaf используется для входа в API | API sidecars, allowlist CN и CRL | Новый leaf проходит, старый отклоняется на свежем соединении | `grade4_probe.py leaf`: старый leaf отклонён обеими репликами, 174 аутентифицированных запроса получили 200. |
| Worker использует доверенный сертификат для операций другой роли | RabbitMQ EXTERNAL и ACL | Worker не публикует; publisher не читает очередь; чужой CN отклоняется | `probe matrix` проверяет отказ 403 для операций и отказ EXTERNAL для чужой identity. |
| Сервис пытается прочитать чужой секрет или изменить policy | OpenBao cert auth и KV policy | Собственный путь читается, чужой и запись policy возвращают 403 | `probe matrix` проверяет api-a, api-b, worker и recovery. |
| Перебор паролей через обе API-реплики | PostgreSQL admission budget, слоты Argon2id | Лимит общий, 429 с Retry-After, при отказе БД — 503 | `grade4_probe.py login`: 40 допусков и 40 отказов. Серия запросов с KDF за 1,154 с дала 8×401 и 72×429. При остановке PostgreSQL обе реплики вернули 503 и восстановились после запуска. |
| Recovery удаляет используемый или опубликованный объект | PostgreSQL advisory locks и IAM MinIO | Удерживаемый staging и опубликованный результат сохраняются | В `recovery-test.sh` чтение под shared lock блокирует очистку, MinIO отклоняет удаление из results. |
| Произвольный декодер получает файл с поддельным MIME | Отдельный процесс Pillow, allowlist JPEG/PNG, лимиты размера и ресурсов | Синтетический TIFF, неверный MIME, битый файл и oversized IHDR отклоняются | `student-tests/render.py` проверяет эти случаи. |
| Пароль или Bearer попадает в диагностические данные | HTTP middleware, логирование и OTel | Заголовок авторизации и значения credentials отсутствуют в логах и трассах | `grade4_probe.py log-hygiene` проверил контейнерные логи и коррелированные записи Loki/Tempo. |
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
Оператор хранит CA и Shamir shares в каталоге 0700, операторский файл имеет
0600. После рестарта OpenBao оператор выполняет unseal исходными долями.
Приложения входят по cert auth, обновляют короткоживущий token и используют
ограниченный snapshot. При потере cert identity её доступ отзывается, связанный
секрет ротируется и подтверждается новым подключением. При недоступности OpenBao
верхняя граница локальной пригодности snapshot — 30 с по умолчанию.
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
| --- | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | TODO |
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
## Lifecycle и инциденты
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
Сканирование и применимость описаны в [отчёте](../REPORT.md#сканирование).
View File
+150
View File
@@ -0,0 +1,150 @@
import asyncio
import hashlib
import subprocess
import sys
import tempfile
import unicodedata
from uuid import UUID, uuid4
from botocore.exceptions import BotoCoreError, ClientError
from fastapi import HTTPException, Request
from fastapi.responses import StreamingResponse
from starlette.concurrency import run_in_threadpool
from starlette.requests import ClientDisconnect
from .database import get_connection
from .jobs import enqueue
from .telemetry import span
from .storage import s3, BUCKET
MAX_BYTES = 10 * 1024**2
upload_slots = asyncio.Semaphore(1)
def serialize(row):
result = {key: str(row[key]) for key in ('id', 'chat_id', 'owner_id')}
result.update({key: row[key] for key in ('filename', 'content_type', 'size_bytes', 'sha256', 'status')})
result.update({key: row[key].isoformat().replace('+00:00', 'Z') for key in ('created_at', 'updated_at')})
manifest = row.get('manifest') or {}
variants = [
dict(name=name, **{field: obj[field] for field in
('content_type', 'size_bytes', 'sha256', 'width', 'height')})
for name, obj in sorted(manifest.items()) if name != 'original'
]
return dict(result, variants=variants, error_code=row['error_code'])
def persist(path, chat, owner, filename, mime, size, checksum):
attachment_id = uuid4()
key = 'staging/' + str(attachment_id)
# The same lock is taken by cleanup before its final DB check/deletion.
# A process crash releases the transaction; an uncommitted object is later cleaned.
with get_connection() as conn:
with span("attachment.accept"), conn.transaction():
conn.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', (key,))
with open(path, 'rb') as source:
s3.put_object(Bucket=BUCKET, Key=key, Body=source, ContentLength=size, ContentType=mime)
row = conn.execute('''INSERT INTO attachments
(id, chat_id, owner_id, filename, object_key, size_bytes, content_type, sha256, staging_key, status)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING *''',
(attachment_id, UUID(chat), UUID(owner), filename, key, size, mime, checksum, key)).fetchone()
enqueue(conn, attachment_id, 1, accepted=True)
# Exiting transaction above commits before returning 202.
return serialize(row)
def accessible(attachment_id, user_id):
try:
aid = UUID(attachment_id)
except ValueError:
raise HTTPException(400, 'Неверный UUID') from None
with get_connection() as conn:
row = conn.execute('''SELECT a.*, j.manifest FROM attachments a
LEFT JOIN image_jobs j ON j.attachment_id=a.id AND j.pipeline_version=a.active_version
JOIN chat_members cm ON cm.chat_id=a.chat_id
WHERE a.id=%s AND cm.user_id=%s''', (aid, UUID(user_id))).fetchone()
if row is None:
raise HTTPException(404, 'Вложение не найдено')
return row
def register(app, current_user, get_chat):
@app.post('/api/v1/chats/{chat_id}/attachments', status_code=202)
async def upload(chat_id: str, request: Request):
user = await run_in_threadpool(current_user, request)
chat = await run_in_threadpool(get_chat, chat_id, request)
filename = request.query_params.get('filename', '')
if (not 1 <= len(filename) <= 255 or not filename.strip()
or any(c in '/\\' or unicodedata.category(c).startswith('C') for c in filename)):
raise HTTPException(400, 'Недопустимое имя файла')
mime = request.headers.get('content-type', '').split(';')[0].strip().lower()
if mime not in ('image/png', 'image/jpeg'):
raise HTTPException(415, 'Ожидается PNG или JPEG')
length = request.headers.get('content-length')
if length is not None:
if not length.isascii() or not length.isdecimal() or len(length) > 12:
raise HTTPException(400, 'Неверный размер')
if int(length) > MAX_BYTES:
raise HTTPException(413, 'Файл больше 10 MiB')
try:
await asyncio.wait_for(upload_slots.acquire(), timeout=30)
except asyncio.TimeoutError:
raise HTTPException(503, 'Загрузчик занят') from None
try:
with tempfile.NamedTemporaryFile(prefix='lab6-') as target:
size = 0
digest = hashlib.sha256()
try:
async with asyncio.timeout(30):
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BYTES:
raise HTTPException(413, 'Файл больше 10 MiB')
target.write(chunk)
digest.update(chunk)
except ClientDisconnect:
raise HTTPException(400, 'Загрузка прервана') from None
except TimeoutError:
raise HTTPException(400, 'Истекло время загрузки') from None
target.flush()
def validate():
try:
return subprocess.run([sys.executable, '-m', 'src.image_check', target.name, mime],
timeout=10, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode
except subprocess.TimeoutExpired:
return 15
code = await run_in_threadpool(validate)
if code != 0:
raise HTTPException(413 if code == 13 else 415, 'Недопустимое изображение')
return await run_in_threadpool(persist, target.name, chat['id'], user['id'], filename, mime, size, digest.hexdigest())
finally:
upload_slots.release()
@app.get('/api/v1/attachments/{attachment_id}')
def metadata(attachment_id: str, request: Request):
return serialize(accessible(attachment_id, current_user(request)['id']))
@app.get('/api/v1/attachments/{attachment_id}/content')
def content(attachment_id: str, request: Request):
row = accessible(attachment_id, current_user(request)['id'])
if row['status'] != 'ready':
raise HTTPException(409, 'Вложение не готово')
variant = row['manifest'].get(request.query_params.get('variant', 'original'))
if variant is None:
raise HTTPException(404, 'Вариант не найден')
obj = s3.get_object(Bucket=BUCKET, Key=variant['key'])
def chunks():
try:
for chunk in obj['Body'].iter_chunks(64 * 1024):
yield chunk
finally:
obj['Body'].close()
return StreamingResponse(chunks(), media_type=variant['content_type'], headers={
'Content-Length': str(variant['size_bytes']), 'X-Content-Type-Options': 'nosniff',
'Content-Disposition': 'attachment', 'Cache-Control': 'private, no-store'})
@app.exception_handler(BotoCoreError)
@app.exception_handler(ClientError)
async def storage_error(request, exc):
from .main import error_response
return error_response(request, 503, 'unavailable', 'Хранилище временно недоступно')
+95
View File
@@ -0,0 +1,95 @@
import base64
import binascii
import hashlib
import os
import re
import secrets
from datetime import datetime, timedelta, timezone
from argon2 import PasswordHasher, Type
from argon2.exceptions import InvalidHashError, VerifyMismatchError
memory = int(os.getenv("ARGON2_MEMORY_KIB", "65536"))
iterations = int(os.getenv("ARGON2_ITERATIONS", "3"))
parallelism = int(os.getenv("ARGON2_PARALLELISM", "4"))
if memory < 19456 or iterations < 2 or parallelism < 1:
raise ValueError("Argon2id configuration below the lab minimum")
password_hasher = PasswordHasher(
time_cost=iterations, memory_cost=memory, parallelism=parallelism, type=Type.ID,
)
def hash_password(password: str) -> str:
return password_hasher.hash(password)
def verify_password(password_hash: str, password: str) -> bool:
try:
return password_hasher.verify(password_hash, password)
except (VerifyMismatchError, InvalidHashError):
return False
def parse_basic(authorization: str | None) -> tuple[str, str] | None:
if not authorization:
return None
scheme, separator, credentials = authorization.partition(" ")
if not separator or scheme.lower() != "basic":
return None
try:
raw = base64.b64decode(credentials, validate=True)
decoded = raw.decode("utf-8")
username, password = decoded.split(":", 1)
except (ValueError, UnicodeError, binascii.Error):
return None
if not re.fullmatch(r"[a-z0-9_]{3,32}", username):
return None
if not 12 <= len(password) <= 128:
return None
return username, password
def parse_bearer(authorization: str | None) -> str | None:
if not authorization:
return None
scheme, separator, token = authorization.partition(" ")
if not separator or scheme.lower() != "bearer":
return None
if not re.fullmatch(r"[A-Za-z0-9._~+/-]+={0,2}", token) or len(token) > 512:
return None
return token
def create_token() -> str:
return secrets.token_urlsafe(32)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode("ascii")).hexdigest()
def session_expiration() -> datetime:
ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
if ttl < 1:
raise ValueError("SESSION_TTL_SECONDS must be positive")
return datetime.now(timezone.utc) + timedelta(seconds=ttl)
def format_datetime(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(
timespec="microseconds"
).replace("+00:00", "Z")
+34
View File
@@ -0,0 +1,34 @@
"""Mutual TLS transport with explicit broker identities and publisher confirms."""
import json
import os
import ssl
from contextlib import contextmanager
import pika
QUEUE = "attachment.process.v1"
EXCHANGE = "attachments"
@contextmanager
def channel():
context = ssl.create_default_context(cafile=os.environ["TLS_CA_FILE"])
context.load_cert_chain("/run/identity/amqp.crt", "/run/identity/amqp.key")
params = pika.ConnectionParameters(
host="broker", port=5671, virtual_host="messenger",
credentials=pika.credentials.ExternalCredentials(),
ssl_options=pika.SSLOptions(context, "broker"), connection_attempts=1,
socket_timeout=4, stack_timeout=8, blocked_connection_timeout=10, heartbeat=120,
)
connection = pika.BlockingConnection(params)
try:
yield connection, connection.channel()
finally:
if connection.is_open:
connection.close()
def send(ch, message, headers=None):
ch.basic_publish(EXCHANGE, QUEUE, json.dumps(message).encode(), mandatory=True,
properties=pika.BasicProperties(content_type="application/json", delivery_mode=2,
message_id=message["job_id"], headers=headers))
+254
View File
@@ -0,0 +1,254 @@
from uuid import UUID, uuid4
from .database import get_connection
def serialize_chat(row):
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(member_id) for member_id in row["member_ids"]],
"created_at": row["created_at"].isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
}
def serialize_message(row):
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"attachment_ids": [str(a) for a in row["attachment_ids"]],
"created_at": row["created_at"].isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
}
def create_chat(creator_id, title, member_ids):
chat_id = uuid4()
members = [UUID(member_id) for member_id in member_ids]
with get_connection() as conn:
with conn.transaction():
with conn.cursor() as cur:
cur.execute(
"""
SELECT id
FROM users
WHERE id = ANY(%s::uuid[])
""",
(members,),
)
existing = {row["id"] for row in cur.fetchall()}
if len(existing) != len(members):
return None
cur.execute(
"""
INSERT INTO chats (id, title, created_by)
VALUES (%s, %s, %s)
RETURNING id, title, created_at
""",
(chat_id, title, UUID(creator_id)),
)
chat = cur.fetchone()
cur.executemany(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (%s, %s)
""",
[(chat_id, member_id) for member_id in members],
)
return {
"id": str(chat["id"]),
"title": chat["title"],
"member_ids": member_ids,
"created_at": chat["created_at"].isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
}
def get_chat(chat_id, user_id):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT
c.id,
c.title,
c.created_at,
ARRAY(
SELECT cm2.user_id
FROM chat_members cm2
WHERE cm2.chat_id = c.id
ORDER BY cm2.user_id
) AS member_ids
FROM chats c
JOIN chat_members cm
ON cm.chat_id = c.id
WHERE c.id = %s
AND cm.user_id = %s
""",
(UUID(chat_id), UUID(user_id)),
)
row = cur.fetchone()
return serialize_chat(row) if row else None
def list_chats(user_id, limit, last_chat_id=None):
with get_connection() as conn:
with conn.cursor() as cur:
last_key = None
if last_chat_id is not None:
cur.execute(
"""
SELECT c.created_at, c.id
FROM chats c
JOIN chat_members cm
ON cm.chat_id = c.id
WHERE c.id = %s
AND cm.user_id = %s
""",
(UUID(last_chat_id), UUID(user_id)),
)
last_key = cur.fetchone()
if last_key is None:
return None
cur.execute(
"""
SELECT
c.id,
c.title,
c.created_at,
ARRAY(
SELECT cm2.user_id
FROM chat_members cm2
WHERE cm2.chat_id = c.id
ORDER BY cm2.user_id
) AS member_ids
FROM chats c
JOIN chat_members cm
ON cm.chat_id = c.id
WHERE cm.user_id = %s
AND (
%s::timestamptz IS NULL
OR (c.created_at, c.id) >
(%s::timestamptz, %s::uuid)
)
ORDER BY c.created_at, c.id
LIMIT %s
""",
(
UUID(user_id),
last_key["created_at"] if last_key else None,
last_key["created_at"] if last_key else None,
last_key["id"] if last_key else None,
limit + 1,
),
)
rows = cur.fetchall()
return [serialize_chat(row) for row in rows]
def create_message(chat_id, sender_id, text, key, attachment_ids):
# INSERT ON CONFLICT waits for a concurrent transaction on the same key.
# READ COMMITTED's next statement sees its committed result. Both the
# message and deduplication record commit together, or both roll back.
with get_connection() as conn:
with conn.transaction():
attachments = [UUID(a) for a in attachment_ids]
scope = (UUID(chat_id), UUID(sender_id), key)
conn.execute("""
DELETE FROM message_requests WHERE chat_id=%s AND sender_id=%s AND key=%s
AND created_at <= clock_timestamp() - interval '24 hours'
""", scope)
row = conn.execute(
"""INSERT INTO message_requests(chat_id, sender_id, key, text)
VALUES (%s, %s, %s, %s)
ON CONFLICT (chat_id, sender_id, key) DO NOTHING
RETURNING key""", (*scope, text)
).fetchone()
if row is None:
previous = conn.execute(
"""SELECT m.* FROM message_requests r
JOIN messages m ON m.id = r.message_id
WHERE r.chat_id=%s AND r.sender_id=%s AND r.key=%s""",
scope,
).fetchone()
if previous["text"] != text or previous["attachment_ids"] != attachments:
return "conflict"
return serialize_message(previous)
rows = conn.execute(
'SELECT id,status FROM attachments WHERE chat_id=%s AND id=ANY(%s::uuid[]) '
'ORDER BY id FOR SHARE', (UUID(chat_id), attachments)
).fetchall()
if len(rows) != len(attachments) or any(row['status'] == 'failed' for row in rows):
# No unfinished idempotency record may survive validation failure.
conn.execute('DELETE FROM message_requests WHERE chat_id=%s AND sender_id=%s AND key=%s', scope)
return None if len(rows) != len(attachments) else "attachment_failed"
message = conn.execute(
"""INSERT INTO messages(id, chat_id, sender_id, text, attachment_ids)
VALUES (%s, %s, %s, %s, %s) RETURNING *""",
(uuid4(), UUID(chat_id), UUID(sender_id), text, attachments),
).fetchone()
conn.execute(
"""UPDATE message_requests SET message_id=%s
WHERE chat_id=%s AND sender_id=%s AND key=%s""",
(message["id"], *scope),
)
return serialize_message(message)
def list_messages(chat_id, limit, last_message_id=None):
with get_connection() as conn:
with conn.cursor() as cur:
last_key = None
if last_message_id is not None:
cur.execute(
"""
SELECT created_at, id
FROM messages
WHERE chat_id = %s
AND id = %s
""",
(UUID(chat_id), UUID(last_message_id)),
)
last_key = cur.fetchone()
if last_key is None:
return None
# Разные формы SQL сохраняют индексный range scan и для generic plan.
# В SQL подставляется только константа; значения остаются параметрами.
cursor_condition = ""
params = [UUID(chat_id)]
if last_key is not None:
cursor_condition = "AND (created_at, id) > (%s, %s)"
params.extend([last_key["created_at"], last_key["id"]])
params.append(limit + 1)
cur.execute(
f"""
SELECT id, chat_id, sender_id, text, attachment_ids, created_at
FROM messages
WHERE chat_id = %s
{cursor_condition}
ORDER BY created_at, id
LIMIT %s
""",
params,
)
rows = cur.fetchall()
return [serialize_message(row) for row in rows]
+175
View File
@@ -0,0 +1,175 @@
"""Refresh bounded KV snapshots using renewable, certificate-authenticated tokens."""
import json
import logging
from math import isfinite
import os
import ssl
from threading import Event, Lock, Thread
from time import monotonic
from urllib.error import HTTPError, URLError
from urllib.request import HTTPSHandler, HTTPRedirectHandler, Request, build_opener
from .telemetry import log
SCOPES = {"api-a": "api", "api-b": "api", "publisher": "publisher",
"worker": "worker", "recovery": "recovery"}
class CredentialsUnavailable(Exception):
pass
class RefreshError(Exception):
def __init__(self, operation, reason, status=None):
self.operation = operation
self.reason = reason
self.status = status
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
class CredentialSource:
def __init__(self):
self.snapshot = {}
self.valid_until = 0
self.token = None
self.renew_at = self.token_until = 0
self.lock = Lock()
self.stop = Event()
self.last_failure = None
def request(self, path, operation, data=None):
headers = {"Content-Type": "application/json"}
if self.token and operation != "login":
headers["X-Vault-Token"] = self.token
request = Request(self.address + "/v1/" + path,
data=None if data is None else json.dumps(data).encode(),
headers=headers)
try:
with self.opener.open(request, timeout=2) as response:
return json.load(response)
except HTTPError as exc:
with exc:
reason = "forbidden" if exc.code == 403 else "http_error"
if exc.code == 404 and operation == "kv":
reason = "kv_missing"
elif exc.code == 400 and operation == "login":
reason = "certificate_auth_rejected"
elif exc.code == 429 or exc.code >= 500:
reason = "unavailable"
raise RefreshError(operation, reason, exc.code) from None
except (URLError, OSError) as exc:
cause = exc.reason if isinstance(exc, URLError) else exc
reason = "tls_error" if isinstance(cause, ssl.SSLError) else "unavailable"
raise RefreshError(operation, reason) from None
except ValueError:
raise RefreshError(operation, "invalid_response") from None
def set_token(self, response, operation):
try:
auth = response["auth"]
token, lease = auth["client_token"], auth["lease_duration"]
if not isinstance(token, str) or not token or type(lease) is not int or lease <= 0:
raise ValueError
except (TypeError, KeyError, ValueError):
raise RefreshError(operation, "invalid_response") from None
now = monotonic()
self.token = token
self.token_until = now + lease
self.renew_at = now + lease * 0.6
def refresh(self):
if self.token and monotonic() >= self.token_until:
self.token = None
if self.token and monotonic() >= self.renew_at:
try:
self.set_token(self.request("auth/token/renew-self", "renew", {}), "renew")
except RefreshError as exc:
if exc.status not in (400, 403):
raise
self.token = None
self.report_failure(exc)
if not self.token:
response = self.request("auth/cert/login", "login", {"name": self.role})
self.set_token(response, "login")
try:
document = self.request("kv/data/messenger/" + self.scope, "kv")["data"]
contents = document["data"]
fields = ("database_url",) if self.scope == "publisher" else (
"database_url", "s3_user", "s3_password"
)
if any(not isinstance(contents[key], str) or not contents[key] for key in fields):
raise ValueError
snapshot = {key: contents[key] for key in fields}
snapshot["version"] = document["metadata"]["version"]
except RefreshError as exc:
if exc.status == 403:
self.token = None
raise
except (KeyError, TypeError, ValueError):
raise RefreshError("kv", "invalid_response") from None
with self.lock:
self.snapshot = snapshot
self.valid_until = monotonic() + self.max_age
def report_failure(self, exc):
failure = (exc.operation, exc.reason, exc.status)
if failure != self.last_failure:
log("openbao_credentials_failure", logging.WARNING, role=self.role,
operation=exc.operation, reason=exc.reason, http_status=exc.status)
self.last_failure = failure
def refresh_once(self):
try:
self.refresh()
except RefreshError as exc:
if exc.reason in ("forbidden", "kv_missing", "invalid_response", "certificate_auth_rejected"):
with self.lock:
self.snapshot = {}
self.valid_until = 0
self.report_failure(exc)
else:
if self.last_failure is not None:
log("openbao_credentials_restored", role=self.role)
self.last_failure = None
def run(self):
while not self.stop.wait(self.interval):
self.refresh_once()
def start(self):
self.role = os.environ.get("BAO_ROLE")
if not self.role:
return # Only migration/operator commands use dedicated local files.
self.scope = SCOPES.get(self.role)
if not self.scope or os.environ.get("BAO_SCOPE", self.scope) != self.scope:
raise ValueError("Invalid OpenBao role/scope mapping")
self.address = os.environ["BAO_ADDR"].rstrip("/")
if not self.address.startswith("https://"):
raise ValueError("OpenBao must use HTTPS")
self.max_age = float(os.getenv("CREDENTIAL_MAX_AGE", "30"))
self.interval = float(os.getenv("CREDENTIAL_REFRESH_SECONDS", "2"))
if any(not isfinite(value) or value <= 0 for value in (self.max_age, self.interval)):
raise ValueError("OpenBao refresh intervals must be finite and positive")
try:
context = ssl.create_default_context(cafile=os.environ["TLS_CA_FILE"])
context.load_cert_chain("/run/identity/bao.crt", "/run/identity/bao.key")
except OSError:
self.report_failure(RefreshError("startup", "tls_configuration"))
raise CredentialsUnavailable("OpenBao TLS configuration is unusable") from None
self.opener = build_opener(NoRedirect(), HTTPSHandler(context=context))
self.stop.clear()
self.refresh_once()
Thread(target=self.run, daemon=True, name="openbao-refresh").start()
def get(self):
with self.lock:
if monotonic() >= self.valid_until:
raise CredentialsUnavailable("Рабочие учётные данные недоступны")
return self.snapshot.copy()
credentials = CredentialSource()
+111
View File
@@ -0,0 +1,111 @@
"""Role-scoped TLS database pools with generation switching and graceful draining."""
from contextlib import contextmanager
import sys
from dataclasses import dataclass
import logging
import os
from pathlib import Path
from threading import Lock
from opentelemetry.metrics import Observation
from psycopg import Cursor
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from .credentials import credentials
from .telemetry import meter, span
class TracedCursor(Cursor):
def execute(self, query, params=None, **kwargs):
with span("postgresql.execute", attributes={"db.system.name": "postgresql"}):
return super().execute(query, params, **kwargs)
def get_database_url():
return Path(os.environ["DATABASE_URL_FILE"]).read_text().strip()
@dataclass
class Generation:
conninfo: str
pool: ConnectionPool
borrowers: int = 0
retired: bool = False
active = None
lock = Lock()
logging.getLogger("psycopg.pool").setLevel(logging.CRITICAL)
def pool_stat(name):
def observe(_):
generation = active
if generation is None:
return [Observation(0)]
stats = generation.pool.get_stats()
value = stats["pool_size"] - stats["pool_available"] if name == "used" else stats.get(name, 0)
return [Observation(value)]
return observe
def open_database():
for metric, stat in (("used", "used"), ("waiting", "requests_waiting"), ("capacity", "pool_max")):
meter.create_observable_gauge("lab_db_pool_" + metric, callbacks=[pool_stat(stat)])
credentials.start()
def close_database():
credentials.stop.set()
with lock:
if active is not None:
active.pool.close()
def acquire():
global active
with lock:
conninfo = credentials.get()["database_url"] if os.getenv("BAO_ROLE") else get_database_url()
if active is None or active.conninfo != conninfo:
pool = ConnectionPool(
conninfo, min_size=1, max_size=int(os.getenv("DB_POOL_SIZE", "10")),
timeout=5, open=False,
kwargs={"row_factory": dict_row, "cursor_factory": TracedCursor,
"connect_timeout": 3, "options": "-c statement_timeout=5000"},
)
try:
pool.open(wait=True, timeout=5)
except BaseException:
pool.close()
raise
previous, active = active, Generation(conninfo, pool)
if previous:
previous.retired = True
if previous.borrowers == 0:
previous.pool.close()
active.borrowers += 1
return active
@contextmanager
def get_connection():
generation = acquire()
try:
manager = generation.pool.connection()
with span("postgresql.pool.acquire"):
connection = manager.__enter__()
try:
yield connection
except BaseException:
with span("postgresql.transaction.rollback"):
manager.__exit__(*sys.exc_info())
raise
else:
with span("postgresql.transaction.close"):
manager.__exit__(None, None, None)
finally:
with lock:
generation.borrowers -= 1
if generation.retired and generation.borrowers == 0:
generation.pool.close()
+44
View File
@@ -0,0 +1,44 @@
"""One-shot fault controls, enabled only by the operator on a disposable stand."""
import logging
import os
import time
from .database import get_connection
from .telemetry import log
ENABLED = os.getenv('PIPELINE_FAULTS') == '1'
def take(conn, attachment_id, version, point):
if not ENABLED:
return None
row = conn.execute("""
UPDATE pipeline_faults SET hit_at=clock_timestamp()
WHERE attachment_id=%s AND pipeline_version=%s AND point=%s AND hit_at IS NULL
RETURNING action
""", (attachment_id, version, point)).fetchone()
return row['action'] if row else None
def checkpoint(job, point):
if not ENABLED:
return None
key = (job['attachment_id'], job['pipeline_version'], point)
with get_connection() as conn:
action = take(conn, *key)
if action == 'crash':
log('pipeline_fault', logging.WARNING, point=point, action='crash', job_id=str(job['id']))
os._exit(86)
if action == 'pause':
log('pipeline_fault', logging.WARNING, point=point, action='pause', job_id=str(job['id']))
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
with get_connection() as conn:
row = conn.execute("""
SELECT released FROM pipeline_faults
WHERE attachment_id=%s AND pipeline_version=%s AND point=%s
""", key).fetchone()
if row is None or row['released']:
break
time.sleep(0.1)
return action
+25
View File
@@ -0,0 +1,25 @@
"""Isolated image decoder: bounded address space, CPU and parent wall timeout."""
import resource
import sys
import warnings
if sys.platform.startswith('linux'):
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024**2, 512 * 1024**2))
resource.setrlimit(resource.RLIMIT_CPU, (8, 8))
from PIL import Image
Image.MAX_IMAGE_PIXELS = 40_000_000
warnings.simplefilter('error', Image.DecompressionBombWarning)
try:
with Image.open(sys.argv[1], formats=("PNG", "JPEG")) as image:
if image.width * image.height > 40_000_000:
sys.exit(13)
actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(image.format)
if actual != sys.argv[2] or getattr(image, 'n_frames', 1) != 1:
sys.exit(15)
image.verify()
with Image.open(sys.argv[1], formats=("PNG", "JPEG")) as image:
image.load()
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
sys.exit(13)
except Exception:
sys.exit(15)
+164
View File
@@ -0,0 +1,164 @@
"""PostgreSQL owns execution state and the publication pointer."""
import os
import random
from psycopg.types.json import Jsonb
from .database import get_connection
from .telemetry import propagator, span
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS', '5'))
LEASE_SECONDS = int(os.getenv('JOB_TIMEOUT_SECONDS', '60'))
def enqueue(conn, attachment_id, version, *, accepted=False):
context = {}
propagator.inject(context)
job = conn.execute("""
INSERT INTO image_jobs(attachment_id,pipeline_version,trace_context,accepted_at)
VALUES (%s,%s,%s,CASE WHEN %s THEN clock_timestamp() END) RETURNING *
""", (attachment_id, version, Jsonb(context), accepted)).fetchone()
with span('outbox.enqueue'):
schedule(conn, job['id'])
return job
def schedule(conn, job_id, delay=0):
conn.execute('''
INSERT INTO job_outbox(job_id,publish_after)
VALUES (%s, clock_timestamp() + %s * interval '1 second')
ON CONFLICT (job_id) DO UPDATE SET publish_after=excluded.publish_after
''', (job_id, delay))
def event(conn, job, name, detail=None):
conn.execute('INSERT INTO job_events(job_id,attempt,event,detail) VALUES (%s,%s,%s,%s)',
(job['id'], job['attempt'], name, detail))
def carrier(job):
return dict(schema_version=1, type='attachment.process.v1', job_id=str(job['id']),
attachment_id=str(job['attachment_id']), pipeline_version=job['pipeline_version'],
attempt=job['attempt'], created_at=job['created_at'].isoformat().replace('+00:00', 'Z'))
def claim(message):
with get_connection() as conn:
job = conn.execute('SELECT * FROM image_jobs WHERE id=%s FOR NO KEY UPDATE',
(message['job_id'],)).fetchone()
if (job is None or job['attachment_id'] != message['attachment_id']
or job['pipeline_version'] != message['pipeline_version']
or job['attempt'] != message['attempt']):
return None
if job['state'] != 'queued':
event(conn, job, 'delivery_ignored', job['state'])
return None
attachment = lock_attachment(conn, job)
if attachment['desired_version'] != job['pipeline_version']:
supersede(conn, job)
return None
job = conn.execute('''
UPDATE image_jobs SET state='processing', fence=fence+1,
lease_until=clock_timestamp() + %s * interval '1 second'
WHERE id=%s RETURNING *
''', (LEASE_SECONDS, job['id'])).fetchone()
update_attachment(conn, job, 'processing')
event(conn, job, 'claimed', str(job['fence']))
return job, attachment
def lock_attachment(conn, job):
return conn.execute('SELECT * FROM attachments WHERE id=%s FOR NO KEY UPDATE',
(job['attachment_id'],)).fetchone()
def update_attachment(conn, job, state, error=None):
# While building a new version, continue serving the previously published version.
conn.execute('''
UPDATE attachments SET status=%s, error_code=%s, updated_at=clock_timestamp()
WHERE id=%s AND desired_version=%s AND active_version IS NULL
''', (state, error, job['attachment_id'], job['pipeline_version']))
def supersede(conn, job):
conn.execute("UPDATE image_jobs SET state='superseded', lease_until=NULL WHERE id=%s", (job['id'],))
event(conn, job, 'superseded')
def owned(conn, job):
current = conn.execute('''
SELECT *, lease_until > clock_timestamp() AS live FROM image_jobs WHERE id=%s FOR NO KEY UPDATE
''', (job['id'],)).fetchone()
return current['state'] == 'processing' and current['fence'] == job['fence'] and current['live']
def finish(job, manifest):
with get_connection() as conn:
if not owned(conn, job):
event(conn, job, 'fence_rejected', str(job['fence']))
return 'ignored', None
attachment = lock_attachment(conn, job)
if not owned(conn, job):
event(conn, job, 'fence_rejected', str(job['fence']))
return 'ignored', None
if attachment['desired_version'] != job['pipeline_version']:
supersede(conn, job)
return 'ignored', None
ready = conn.execute("""
UPDATE image_jobs SET first_ready_at=clock_timestamp(), state='ready', manifest=%s, lease_until=NULL,error_code=NULL WHERE id=%s RETURNING first_ready_at
""", (Jsonb(manifest), job['id'])).fetchone()
conn.execute("""
UPDATE attachments SET status='ready', active_version=%s, error_code=NULL,
object_key=%s, updated_at=clock_timestamp() WHERE id=%s
""", (job['pipeline_version'], manifest['original']['key'], attachment['id']))
event(conn, job, 'published')
latency = ((ready['first_ready_at'] - job['accepted_at']).total_seconds()
if job['accepted_at'] else None)
return 'ready', latency
def fail_locked(conn, job, reason, permanent=False):
attachment = lock_attachment(conn, job)
if attachment['desired_version'] != job['pipeline_version']:
supersede(conn, job)
return 'ignored'
failures = job['failures'] + 1
if permanent or failures >= MAX_ATTEMPTS:
code = reason if permanent else 'retry_exhausted'
conn.execute("""
UPDATE image_jobs SET state='failed', error_code=%s, lease_until=NULL, failures=%s WHERE id=%s
""", (code, failures, job['id']))
conn.execute('INSERT INTO job_dead_letters(job_id,attempt,error_code) VALUES (%s,%s,%s)',
(job['id'], job['attempt'], code))
update_attachment(conn, job, 'failed', code)
event(conn, job, 'dead_letter', reason)
return 'failed'
delay = min(30, 2 ** (failures - 1)) * random.uniform(0.75, 1.25)
conn.execute("""
UPDATE image_jobs SET state='queued', attempt=attempt+1, failures=%s,
lease_until=NULL,error_code=%s WHERE id=%s
""", (failures, reason, job['id']))
schedule(conn, job['id'], delay)
update_attachment(conn, job, 'queued')
event(conn, job, 'retry_scheduled', reason)
return 'retry'
def fail(job, reason, permanent=False):
with get_connection() as conn:
if owned(conn, job):
return fail_locked(conn, job, reason, permanent)
else:
event(conn, job, 'fence_rejected', str(job['fence']))
return 'ignored'
def recover_one():
with get_connection() as conn:
job = conn.execute("""
SELECT * FROM image_jobs WHERE state='processing' AND lease_until <= clock_timestamp()
ORDER BY lease_until LIMIT 1 FOR NO KEY UPDATE SKIP LOCKED
""").fetchone()
if job:
fail_locked(conn, job, 'lease_expired')
return job is not None
+46
View File
@@ -0,0 +1,46 @@
"""Shared admission budget and a separate per-process limit on expensive hashes."""
from contextlib import contextmanager
import os
from threading import BoundedSemaphore
from fastapi import HTTPException
from .database import get_connection
WINDOW = int(os.getenv("LOGIN_WINDOW_SECONDS", "10"))
LIMIT = int(os.getenv("LOGIN_WINDOW_LIMIT", "40"))
KDF_SLOTS = int(os.getenv("LOGIN_KDF_SLOTS", "2"))
if min(WINDOW, LIMIT, KDF_SLOTS) < 1:
raise ValueError("Login budgets must be positive")
SLOTS = BoundedSemaphore(KDF_SLOTS)
def limited(wait):
return HTTPException(429, "Слишком много попыток", headers={"Retry-After": str(wait)})
def admit():
with get_connection() as conn:
# Sample the DB clock after admission is serialized across replicas.
conn.execute("SELECT pg_advisory_xact_lock(70702)")
now = conn.execute("SELECT floor(extract(epoch FROM clock_timestamp()))::bigint AS n").fetchone()["n"]
bucket = now // WINDOW
row = conn.execute("""
INSERT INTO login_limits(scope, bucket, attempts) VALUES ('login', %s, 1)
ON CONFLICT(scope, bucket) DO UPDATE SET attempts = login_limits.attempts + 1
WHERE login_limits.attempts < %s RETURNING attempts
""", (bucket, LIMIT)).fetchone()
if row and row["attempts"] == 1:
conn.execute("DELETE FROM login_limits WHERE bucket < %s", (bucket - 1,))
if row is None:
raise limited(WINDOW - now % WINDOW)
@contextmanager
def kdf_slot():
if not SLOTS.acquire(blocking=False):
raise limited(1)
try:
yield
finally:
SLOTS.release()
+522
View File
@@ -0,0 +1,522 @@
"""Мессенджер: PostgreSQL хранит данные и сессии."""
import base64
import binascii
import json
from pathlib import Path
import re
from uuid import UUID, uuid4
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException as StarletteHTTPException
from psycopg import OperationalError, Error as DatabaseError
from psycopg_pool import PoolTimeout
from .auth import (
create_token,
format_datetime,
hash_password,
hash_token,
parse_basic,
parse_bearer,
session_expiration,
verify_password,
password_hasher,
)
from .credentials import CredentialsUnavailable
from .login_limits import admit, kdf_slot
from .telemetry import HTTP, INSTANCE_ID, configure
from .database import open_database, close_database, get_connection
from .user_repository import (
create_user as insert_user,
create_session,
find_session_user,
find_user_by_username,
revoke_session,
replace_password_hash,
serialize_user,
)
from .chat_repository import (
create_chat as insert_chat,
get_chat as find_chat,
list_chats as find_chats,
create_message as insert_message,
list_messages as find_messages,
)
app = FastAPI(title="MTUSI Messenger", version="1.7.0")
# Serve the mandatory contract in Swagger, including auth and request schemas.
OPENAPI_SCHEMA = json.loads(
(Path(__file__).resolve().parents[1] / "contracts/openapi.json").read_text()
)
app.openapi = lambda: OPENAPI_SCHEMA
configure("api")
DUMMY_HASH = hash_password(create_token())
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
500: "internal_error",
503: "unavailable",
}
def error_response(request, status_code, code, message):
return JSONResponse(
status_code=status_code,
content={
"error": {
"code": code,
"message": message,
"request_id": request.state.request_id,
}
},
)
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request.state.request_id = str(uuid4())
try:
response = await call_next(request)
except Exception:
response = error_response(
request, 500, "internal_error", "Внутренняя ошибка сервера"
)
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
@app.exception_handler(StarletteHTTPException)
async def http_error_handler(request: Request, exc: StarletteHTTPException):
response = error_response(
request,
exc.status_code,
ERROR_CODES.get(exc.status_code, "invalid_request"),
str(exc.detail),
)
if exc.headers:
response.headers.update(exc.headers)
return response
@app.exception_handler(CredentialsUnavailable)
@app.exception_handler(DatabaseError)
@app.exception_handler(PoolTimeout)
async def database_error_handler(request: Request, exc):
return error_response(request, 503, "unavailable", "База данных временно недоступна")
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(request, 400, "invalid_request", "Некорректные данные запроса")
async def read_json(request: Request):
"""415 — только для неправильного Content-Type; 400 — для неверного JSON."""
content_type = (
request.headers.get("content-type", "").split(";")[0].strip().lower()
)
if content_type != "application/json":
raise HTTPException(415, "Неподдерживаемый Content-Type")
try:
raw = bytearray()
async for chunk in request.stream():
if len(raw) + len(chunk) > 65536:
raise HTTPException(413, "JSON слишком большой")
raw.extend(chunk)
data = json.loads(raw)
except (ValueError, UnicodeError):
raise HTTPException(400, "Неверный JSON") from None
# [], строка, число, true, false, null — это корректный JSON,
# но НЕ объект, обязательный по контракту.
if not isinstance(data, dict):
raise HTTPException(400, "Ожидается JSON-объект")
return data
def get_current_user(request: Request):
token = parse_bearer(request.headers.get("Authorization"))
if token is None:
raise HTTPException(
401,
"Требуется действующий Bearer-токен",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
try:
user = find_session_user(hash_token(token))
except (OperationalError, PoolTimeout):
raise HTTPException(
503,
"База данных временно недоступна",
) from None
if user is None:
raise HTTPException(
401,
"Недействительная или истёкшая сессия",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
return user
def get_limit(request: Request):
"""Проверяем длину ДО int(): 5000 цифр должны дать 400, а не 500."""
limit_raw = request.query_params.get("limit", "50")
if not limit_raw.isascii() or not limit_raw.isdecimal():
raise HTTPException(400, "Неверный limit")
significant = limit_raw.lstrip("0")
if not significant or len(significant) > 3:
raise HTTPException(400, "Неверный limit")
limit = int(significant) # Теперь строка содержит максимум 3 цифры.
if not 1 <= limit <= 100:
raise HTTPException(400, "limit должен быть от 1 до 100")
return limit
def encode_cursor(first_id, last_id):
raw = f"{first_id}|{last_id}".encode("ascii")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_cursor(cursor):
try:
if not cursor or len(cursor) > 256:
raise ValueError("empty or too long")
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.b64decode(
padded, altchars=b"-_", validate=True
).decode("ascii")
first_id, last_id = raw.split("|")
return str(UUID(first_id)), str(UUID(last_id))
except (ValueError, UnicodeError, binascii.Error):
raise HTTPException(400, "Неверный cursor") from None
# ---- Health ----
@app.get("/health/live")
def health_live():
return {"status": "ok"}
@app.get("/health/ready")
def health_ready():
try:
with get_connection() as conn:
conn.execute("SELECT 1")
from .storage import s3, BUCKET
s3.list_objects_v2(Bucket=BUCKET, Prefix="originals/", MaxKeys=1)
except (OperationalError, PoolTimeout):
raise HTTPException(503, "База данных недоступна") from None
return {"status": "ok"}
# ---- Users ----
@app.post("/api/v1/users", status_code=201)
async def create_user(request: Request):
data = await read_json(request)
if set(data) != {"username", "display_name", "password"}:
raise HTTPException(400, "Неверные поля пользователя")
username = data["username"]
display_name = data["display_name"]
password = data["password"]
if not isinstance(username, str) or not re.fullmatch(
r"[a-z0-9_]{3,32}", username
):
raise HTTPException(400, "Недопустимый username")
if (
not isinstance(display_name, str)
or not 1 <= len(display_name) <= 100
or not display_name.strip()
):
raise HTTPException(400, "Недопустимое имя пользователя")
if not isinstance(password, str) or not 12 <= len(password) <= 128:
raise HTTPException(400, "Пароль должен содержать 12–128 символов")
def bounded_hash():
with kdf_slot():
return hash_password(password)
password_hash = await run_in_threadpool(bounded_hash)
user = await run_in_threadpool(insert_user, username, display_name, password_hash)
if user is None:
raise HTTPException(409, "Username уже занят")
return user
@app.get("/api/v1/users/me")
def get_me(request: Request):
return get_current_user(request)
@app.post("/api/v1/auth/sessions", status_code=201)
def login(request: Request):
admit()
credentials = parse_basic(request.headers.get("Authorization"))
if credentials is None:
raise HTTPException(
401,
"Неверные учётные данные",
headers={
"WWW-Authenticate":
'Basic realm="messenger", charset="UTF-8"'
},
)
username, password = credentials
user_row = find_user_by_username(username)
with kdf_slot():
password_hash = user_row["password_hash"] if user_row else DUMMY_HASH
valid = verify_password(password_hash, password)
replacement = (
hash_password(password)
if user_row and valid and password_hasher.check_needs_rehash(password_hash)
else None
)
if not user_row or not valid:
raise HTTPException(
401, "Неверные учётные данные",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
)
if replacement is not None:
replace_password_hash(user_row["id"], password_hash, replacement)
token = create_token()
expires_at = session_expiration()
create_session(user_row["id"], hash_token(token), expires_at)
return {
"token": token,
"token_type": "Bearer",
"expires_at": format_datetime(expires_at),
"user": serialize_user(user_row),
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def logout(request: Request):
get_current_user(request)
token = parse_bearer(request.headers.get("Authorization"))
if not revoke_session(hash_token(token)):
raise HTTPException(
401,
"Недействительная сессия",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
from fastapi import Response
return Response(status_code=204)
# ---- Chats ----
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request):
user = await run_in_threadpool(get_current_user, request)
data = await read_json(request)
if set(data) != {"title", "member_ids"}:
raise HTTPException(400, "Неверные поля чата")
title = data["title"]
member_ids = data["member_ids"]
if not isinstance(title, str) or not 1 <= len(title) <= 100 or not title.strip():
raise HTTPException(400, "Недопустимое название чата")
if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100:
raise HTTPException(400, "Неверный список участников")
normalized_ids = []
for member_id in member_ids:
if not isinstance(member_id, str):
raise HTTPException(400, "Неверный ID участника")
try:
normalized_ids.append(str(UUID(member_id)))
except ValueError:
raise HTTPException(400, "Неверный UUID участника") from None
if len(normalized_ids) != len(set(normalized_ids)):
raise HTTPException(400, "Участники повторяются")
if user["id"] not in normalized_ids:
raise HTTPException(400, "Создатель должен быть участником")
chat = await run_in_threadpool(insert_chat, user["id"], title, normalized_ids)
if chat is None:
raise HTTPException(400, "Неизвестный участник")
return chat
@app.get("/api/v1/chats")
def list_chats(request: Request):
user = get_current_user(request)
limit = get_limit(request)
cursor = request.query_params.get("cursor")
last_chat_id = None
if cursor is not None:
cursor_user_id, last_chat_id = decode_cursor(cursor)
if cursor_user_id != user["id"]:
raise HTTPException(400, "Неверный cursor")
rows = find_chats(user["id"], limit, last_chat_id)
if rows is None:
raise HTTPException(400, "Неверный cursor")
has_more = len(rows) > limit
page = rows[:limit]
next_cursor = (
encode_cursor(user["id"], page[-1]["id"])
if has_more and page
else None
)
return {"items": page, "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, request: Request):
user = get_current_user(request)
try:
chat_id = str(UUID(chat_id))
except ValueError:
raise HTTPException(400, "Неверный UUID чата") from None
chat = find_chat(chat_id, user["id"])
if chat is None:
raise HTTPException(404, "Чат не найден")
return chat
# ---- Messages ----
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def send_message(chat_id: str, request: Request):
user = await run_in_threadpool(get_current_user, request)
chat = await run_in_threadpool(get_chat, chat_id, request)
data = await read_json(request)
if "text" not in data or set(data) - {"text", "attachment_ids"}:
raise HTTPException(400, "Неверные поля сообщения")
text = data["text"]
attachment_ids = data.get("attachment_ids", [])
if not isinstance(attachment_ids, list) or len(attachment_ids) > 10:
raise HTTPException(400, "Неверный список вложений")
try:
if any(not isinstance(a, str) for a in attachment_ids):
raise ValueError()
attachment_ids = [str(UUID(a)) for a in attachment_ids]
if len(set(attachment_ids)) != len(attachment_ids):
raise ValueError()
except ValueError:
raise HTTPException(400, "Неверные ID вложений") from None
if not isinstance(text, str) or len(text) > 4000 or (not text.strip() and not attachment_ids):
raise HTTPException(400, "Недопустимый текст сообщения")
key = request.headers.get("Idempotency-Key", "")
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
raise HTTPException(400, "Неверный Idempotency-Key")
message = await run_in_threadpool(insert_message, chat["id"], user["id"], text, key, attachment_ids)
if message == "attachment_failed":
raise HTTPException(409, "Обработка вложения завершилась ошибкой")
if message == "conflict":
raise HTTPException(409, "Ключ использован для другого сообщения")
if message is None:
raise HTTPException(404, "Чат не найден")
return message
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: str, request: Request):
chat = get_chat(chat_id, request)
limit = get_limit(request)
cursor = request.query_params.get("cursor")
last_message_id = None
if cursor is not None:
cursor_chat_id, last_message_id = decode_cursor(cursor)
if cursor_chat_id != chat["id"]:
raise HTTPException(400, "Неверный cursor")
rows = find_messages(chat["id"], limit, last_message_id)
if rows is None:
raise HTTPException(400, "Неверный cursor")
has_more = len(rows) > limit
page = rows[:limit]
next_cursor = (
encode_cursor(chat["id"], page[-1]["id"])
if has_more and page
else None
)
return {"items": page, "next_cursor": next_cursor}
@app.on_event("startup")
async def start_database_pool():
await run_in_threadpool(open_database)
@app.on_event("shutdown")
async def stop_database_pool():
await run_in_threadpool(close_database)
from .attachments import register
register(app, get_current_user, get_chat)
app.add_middleware(HTTP)
+16
View File
@@ -0,0 +1,16 @@
"""One-shot migrations, serialized and recorded in PostgreSQL."""
from pathlib import Path
import psycopg
from .database import get_database_url
with psycopg.connect(get_database_url()) as conn:
with conn.transaction():
conn.execute("SELECT pg_advisory_xact_lock(310026)")
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())")
for path in sorted((Path(__file__).resolve().parents[1] / "db/migrations").glob("*.sql")):
if not conn.execute("SELECT 1 FROM schema_migrations WHERE name=%s", (path.name,)).fetchone():
conn.execute(path.read_text())
conn.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (path.name,))
print("Applied", path.name, flush=True)
else:
print("Already applied", path.name, flush=True)
+91
View File
@@ -0,0 +1,91 @@
"""Local administrative commands. Run from the trusted Compose project."""
import argparse
import json
from .broker import channel, send
from .database import close_database, get_connection, open_database
from .jobs import carrier, enqueue, event, schedule
def reprocess(attachment_id, version):
with get_connection() as conn:
row = conn.execute('SELECT * FROM attachments WHERE id=%s FOR NO KEY UPDATE', (attachment_id,)).fetchone()
if not row or version <= row['desired_version']:
raise ValueError('Version must increase for an existing attachment')
if row['active_version'] is None and row['staging_key'] is None and row['object_key'].startswith('staging/'):
raise ValueError('Original expired')
conn.execute("""
UPDATE attachments SET desired_version=%s,
status=CASE WHEN active_version IS NULL THEN 'queued' ELSE status END,
error_code=NULL,updated_at=clock_timestamp() WHERE id=%s
""", (version, attachment_id))
job = enqueue(conn, attachment_id, version)
event(conn, job, 'reprocess_requested')
return carrier(job)
def replay(job_id):
with get_connection() as conn:
row = conn.execute('SELECT * FROM image_jobs WHERE id=%s FOR NO KEY UPDATE', (job_id,)).fetchone()
if not row or row['state'] != 'failed':
raise ValueError('Replay requires a failed job')
attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR NO KEY UPDATE',
(row['attachment_id'],)).fetchone()
if attachment['desired_version'] != row['pipeline_version']:
raise ValueError('Replay requires the current pipeline version')
if attachment['staging_key'] is None and attachment['object_key'].startswith('staging/'):
raise ValueError('Staging retention expired')
conn.execute("""
UPDATE job_dead_letters SET replayed_at=clock_timestamp() WHERE job_id=%s AND attempt=%s
""", (job_id, row['attempt']))
updated = conn.execute("""
UPDATE image_jobs SET state='queued', attempt=attempt+1, failures=0,
error_code=NULL WHERE id=%s RETURNING *
""", (job_id,)).fetchone()
conn.execute("""
UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp()
WHERE id=%s AND active_version IS NULL
""", (row['attachment_id'],))
schedule(conn, job_id)
event(conn, updated, 'operator_replay')
return carrier(updated)
def redeliver(job_id):
with get_connection() as conn:
row = conn.execute('SELECT * FROM image_jobs WHERE id=%s', (job_id,)).fetchone()
if not row:
raise ValueError('Job not found')
message = carrier(row)
with channel() as (_, ch):
ch.confirm_delivery()
send(ch, message, row['trace_context'])
return message
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
new = commands.add_parser('reprocess')
new.add_argument('attachment_id')
new.add_argument('version', type=int, choices=[1, 2])
commands.add_parser('replay').add_argument('job_id')
commands.add_parser('redeliver').add_argument('job_id')
args = parser.parse_args()
open_database()
try:
if args.command == 'reprocess':
result = reprocess(args.attachment_id, args.version)
elif args.command == 'replay':
result = replay(args.job_id)
else:
result = redeliver(args.job_id)
print(json.dumps(result))
except ValueError as exc:
parser.exit(2, f'{exc}\n')
finally:
close_database()
if __name__ == '__main__':
main()
+29
View File
@@ -0,0 +1,29 @@
"""Check recent progress by the service loop in this container."""
from pathlib import Path
import time
PROGRESS = Path('/tmp/pipeline-progress')
MAX_IDLE_SECONDS = 60
_last_write = float('-inf')
def mark_progress():
global _last_write
now = time.monotonic()
if now - _last_write >= 1:
PROGRESS.touch()
_last_write = now
def clear_progress():
global _last_write
PROGRESS.unlink(missing_ok=True)
_last_write = float('-inf')
if __name__ == '__main__':
try:
healthy = time.time() - PROGRESS.stat().st_mtime < MAX_IDLE_SECONDS
except FileNotFoundError:
healthy = False
raise SystemExit(0 if healthy else 1)
+33
View File
@@ -0,0 +1,33 @@
import logging
import signal
from threading import Event
import pika
from psycopg import OperationalError
from psycopg_pool import PoolTimeout
from botocore.exceptions import BotoCoreError, ClientError
from .credentials import CredentialsUnavailable
from .pipeline_health import mark_progress, clear_progress
from .database import open_database, close_database
from .telemetry import configure, log
def serve(loop, role):
configure(role)
stopping = Event()
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, lambda *_: stopping.set())
clear_progress()
open_database()
try:
while not stopping.is_set():
try:
loop(stopping, mark_progress)
except (CredentialsUnavailable, OperationalError, PoolTimeout, BotoCoreError, ClientError, pika.exceptions.AMQPError, OSError) as exc:
clear_progress()
log('dependency_failure', logging.WARNING, error_type=type(exc).__name__)
stopping.wait(1)
finally:
clear_progress()
close_database()
+59
View File
@@ -0,0 +1,59 @@
"""Drain committed outbox rows, deleting only after a positive broker confirm."""
import logging
import os
from .broker import channel, send
from .database import get_connection
from .faults import take
from .jobs import carrier, event
from .process import serve
from .telemetry import SpanKind, log, propagator, span
def publish_one(ch):
with get_connection() as conn:
job = conn.execute("""
SELECT j.* FROM job_outbox o JOIN image_jobs j ON j.id=o.job_id
WHERE o.publish_after <= clock_timestamp()
ORDER BY o.publish_after LIMIT 1 FOR UPDATE OF o SKIP LOCKED
""").fetchone()
if job is None:
return False
if job['state'] != 'queued':
conn.execute('DELETE FROM job_outbox WHERE job_id=%s', (job['id'],))
return True
args = (job['attachment_id'], job['pipeline_version'])
crash_before = take(conn, *args, 'before_publish') == 'crash'
if not crash_before:
parent = propagator.extract(job['trace_context'] or {})
labels = {'messaging.system': 'rabbitmq', 'messaging.destination.name': 'attachment.process.v1',
'job.attempt': job['attempt']}
with span('attachment.process.v1 publish', context=parent,
kind=SpanKind.PRODUCER, attributes=labels):
headers = {}
propagator.inject(headers)
send(ch, carrier(job), headers)
log('broker_confirmed', attempt=job['attempt'])
crash_after = take(conn, *args, 'after_confirm') == 'crash'
if not crash_after:
conn.execute('DELETE FROM job_outbox WHERE job_id=%s', (job['id'],))
event(conn, job, 'broker_confirmed')
if crash_before or crash_after:
point = 'before_publish' if crash_before else 'after_confirm'
log('pipeline_fault', logging.WARNING, point=point, action='crash', job_id=str(job['id']))
os._exit(86)
return True
def loop(stopping, progress):
with channel() as (connection, ch):
ch.confirm_delivery()
while not stopping.is_set():
if not publish_one(ch):
connection.process_data_events(time_limit=0.2)
stopping.wait(0.1)
progress()
if __name__ == '__main__':
serve(loop, 'publisher')
+39
View File
@@ -0,0 +1,39 @@
"""Read one authoritative backlog and exact, matured ready SLO cohorts."""
from time import time
from .broker import QUEUE
from .database import get_connection
from .telemetry import meter, oldest_age, queue_depth, ready_cohort
sample_time = meter.create_gauge('lab_queue_sample_timestamp', unit='s')
DEADLINE = 10
WINDOWS = {'30s': 30, '2m': 120, '5m': 300, '15m': 900, '1h': 3600}
def observe():
with get_connection() as conn:
backlog = conn.execute("""
SELECT count(*) FILTER (WHERE state='queued') AS depth,
COALESCE(EXTRACT(EPOCH FROM statement_timestamp()-min(created_at)), 0) AS age
FROM image_jobs WHERE state IN ('queued','processing')
""").fetchone()
cohorts = conn.execute("""
WITH bounds AS (
SELECT statement_timestamp() - %s * interval '1 second' AS maturity
)
SELECT w.label, count(j.accepted_at) AS total,
count(*) FILTER (WHERE j.accepted_at IS NOT NULL AND (
j.first_ready_at IS NULL OR
j.first_ready_at > j.accepted_at + %s * interval '1 second')) AS bad
FROM unnest(%s::text[], %s::int[]) AS w(label, seconds)
CROSS JOIN bounds LEFT JOIN image_jobs j
ON j.accepted_at > bounds.maturity - w.seconds * interval '1 second'
AND j.accepted_at <= bounds.maturity
GROUP BY w.label
""", (DEADLINE, DEADLINE, list(WINDOWS), list(WINDOWS.values()))).fetchall()
queue_depth.set(backlog['depth'], {'queue': QUEUE})
oldest_age.set(max(0, float(backlog['age'])), {'queue': QUEUE})
sample_time.set(time())
for row in cohorts:
for outcome in ('total', 'bad'):
ready_cohort.set(row[outcome], {'window': row['label'], 'outcome': outcome})
+114
View File
@@ -0,0 +1,114 @@
"""Reclaim expired jobs and remove staging after safe publication or retention."""
from datetime import datetime, timedelta, timezone
import os
import time
from botocore.exceptions import ClientError
from .database import get_connection
from .jobs import recover_one
from .process import serve
from .queue_metrics import observe
from .storage import BUCKET, s3
RETENTION = int(os.getenv('STAGING_RETENTION_SECONDS', '86400'))
def lock_staging(conn, key):
return conn.execute('SELECT pg_try_advisory_xact_lock(hashtextextended(%s,0)) AS ok',
(key,)).fetchone()['ok']
def detach_staging(key, cutoff):
with get_connection() as conn:
if not lock_staging(conn, key):
return False
row = conn.execute("""
SELECT id,status,active_version,object_key,updated_at
FROM attachments WHERE staging_key=%s FOR NO KEY UPDATE
""", (key,)).fetchone()
if not row:
return False
if row['active_version'] is not None:
if row['object_key'] == key or row['object_key'].startswith('staging/'):
return False
elif row['status'] != 'failed' or row['updated_at'] >= cutoff:
return False
conn.execute('UPDATE attachments SET staging_key=NULL WHERE id=%s', (row['id'],))
# Commit the detach before deleting. Replay and reprocess can no longer use
# a failed attachment's staging even if the DELETE succeeds but times out.
return True
def delete_unreferenced(key):
with get_connection() as conn:
if not lock_staging(conn, key):
return
if conn.execute("""
SELECT 1 FROM attachments
WHERE staging_key=%s OR (object_key=%s AND status <> 'failed')
""", (key, key)).fetchone():
return
try:
s3.delete_object(Bucket=BUCKET, Key=key)
except ClientError as exc:
if exc.response.get('Error', {}).get('Code') != 'NoSuchKey':
raise
def cleanup():
cutoff = datetime.now(timezone.utc) - timedelta(seconds=RETENTION)
# Start from PostgreSQL so an already absent object cannot leave a dangling
# staging pointer that would otherwise be invisible to the S3 listing.
after = 'staging/'
while True:
with get_connection() as conn:
rows = conn.execute("""
SELECT staging_key FROM attachments
WHERE staging_key > %s AND staging_key LIKE 'staging/%%'
AND (active_version IS NOT NULL OR (status='failed' AND updated_at < %s))
ORDER BY staging_key LIMIT 100
""", (after, cutoff)).fetchall()
if not rows:
break
for row in rows:
key = row['staging_key']
if detach_staging(key, cutoff):
delete_unreferenced(key)
after = rows[-1]['staging_key']
# An upload that did not commit, or a detached object whose delete failed,
# becomes eligible for collection from S3 after retention.
params = {'Bucket': BUCKET, 'Prefix': 'staging/'}
while True:
page = s3.list_objects_v2(**params)
for obj in page.get('Contents', []):
if obj['LastModified'] < cutoff and obj['Key'].startswith('staging/'):
delete_unreferenced(obj['Key'])
if not page.get('IsTruncated'):
break
params['ContinuationToken'] = page['NextContinuationToken']
def loop(stopping, progress):
next_cleanup = next_observation = 0
while not stopping.is_set():
# Bound each batch so an expired-job backlog cannot starve cleanup.
for _ in range(100):
if stopping.is_set() or not recover_one():
break
progress()
if stopping.is_set():
break
if time.monotonic() >= next_observation:
observe()
next_observation = time.monotonic() + 3
if time.monotonic() >= next_cleanup:
cleanup()
next_cleanup = time.monotonic() + 15
progress()
stopping.wait(0.5)
if __name__ == '__main__':
serve(loop, 'recovery')
+49
View File
@@ -0,0 +1,49 @@
"""Bounded subprocess for untrusted image decoding and resizing."""
import resource
import sys
import warnings
from pathlib import Path
from PIL import Image, ImageOps
# Linux runtime. macOS does not implement RLIMIT_AS with the same semantics.
if sys.platform.startswith('linux'):
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024**2, 512 * 1024**2))
resource.setrlimit(resource.RLIMIT_CPU, (15, 16))
Image.MAX_IMAGE_PIXELS = 40_000_000
warnings.simplefilter('error', Image.DecompressionBombWarning)
def fit(image, bound):
width, height = image.size
largest = max(width, height)
if largest <= bound:
return image
return image.resize((max(1, width * bound // largest), max(1, height * bound // largest)),
Image.Resampling.LANCZOS)
def render(directory, version):
with Image.open(directory / 'original', formats=("PNG", "JPEG")) as source:
image = ImageOps.exif_transpose(source)
if 'A' in image.getbands() or 'transparency' in image.info:
rgba = image.convert('RGBA')
del image
image = Image.new('RGB', rgba.size, 'white')
image.paste(rgba, mask=rgba.getchannel('A'))
del rgba
else:
image = image.convert('RGB')
image.info.clear()
jpeg_quality, webp_quality = {1: (85, 82), 2: (90, 88)}[version]
fit(image, 256).save(directory / 'thumbnail', format='JPEG', quality=jpeg_quality)
ImageOps.fit(image, (128, 128), Image.Resampling.LANCZOS).save(
directory / 'crop', format='JPEG', quality=jpeg_quality)
fit(image, 1280).save(directory / 'optimized', format='WEBP', quality=webp_quality, method=4)
if __name__ == '__main__':
try:
render(Path(sys.argv[1]), int(sys.argv[2]))
except (OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning):
sys.exit(15)
+40
View File
@@ -0,0 +1,40 @@
"""Private S3 access using bounded credentials and sanitized spans."""
import os
from threading import Lock
import boto3
from botocore.config import Config
from .credentials import credentials
from .telemetry import span
BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
class Storage:
def __init__(self):
self.lock = Lock()
self.keys = None
self.client = None
def __getattr__(self, name):
def call(*args, **kwargs):
with self.lock:
snapshot = credentials.get()
keys = snapshot["s3_user"], snapshot["s3_password"]
if keys != self.keys:
self.client = boto3.client(
"s3", endpoint_url="https://s3:9000", region_name="us-east-1",
aws_access_key_id=keys[0], aws_secret_access_key=keys[1],
verify=os.environ["TLS_CA_FILE"],
config=Config(connect_timeout=2, read_timeout=5,
retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}),
)
self.keys = keys
client = self.client
with span(f"s3.{name}"):
return getattr(client, name)(*args, **kwargs)
return call
s3 = Storage()
+165
View File
@@ -0,0 +1,165 @@
"""Bounded OTLP SDKs and a deliberately small set of telemetry attributes."""
from contextlib import contextmanager
import json
import logging
import os
import resource
import sys
from datetime import datetime, timezone
from time import perf_counter, process_time, time
from uuid import uuid4
from opentelemetry import metrics, trace
from opentelemetry._logs import set_logger_provider
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.sampling import ALWAYS_ON
from opentelemetry.trace import SpanKind, Status, StatusCode
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
INSTANCE_ID = str(uuid4())
JOB = {'job_type': 'attachment.process.v1'}
propagator = TraceContextTextMapPropagator()
tracer = trace.get_tracer(__name__)
meter = metrics.get_meter(__name__)
http_requests = meter.create_counter('lab_http_requests')
http_duration = meter.create_histogram('lab_http_duration', unit='s')
job_results = meter.create_counter('lab_job_results')
job_duration = meter.create_histogram('lab_job_duration', unit='s')
time_to_ready = meter.create_histogram('lab_time_to_ready', unit='s')
queue_depth = meter.create_gauge('lab_queue_depth')
oldest_age = meter.create_gauge('lab_oldest_job_age', unit='s')
ready_cohort = meter.create_gauge('lab_ready_cohort')
worker_busy = 0
service_name = 'messenger'
log_handler = None
def configure(role):
global service_name, log_handler
service_name = f'messenger-{role}'
if not os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT'):
return
attributes = Resource.create({
'service.name': service_name, 'service.version': '1.7.0',
'service.instance.id': INSTANCE_ID, 'deployment.environment.name': 'lab',
})
traces = TracerProvider(resource=attributes, sampler=ALWAYS_ON)
traces.add_span_processor(BatchSpanProcessor(
OTLPSpanExporter(timeout=2), max_queue_size=512, max_export_batch_size=128))
trace.set_tracer_provider(traces)
logs = LoggerProvider(resource=attributes)
logs.add_log_record_processor(BatchLogRecordProcessor(
OTLPLogExporter(timeout=2), max_queue_size=512, max_export_batch_size=128))
set_logger_provider(logs)
log_handler = LoggingHandler(logger_provider=logs)
views = [
View(instrument_name='lab_http_duration', aggregation=ExplicitBucketHistogramAggregation(
[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60])),
View(instrument_name='lab_job_duration', aggregation=ExplicitBucketHistogramAggregation(
[0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 60, 120])),
View(instrument_name='lab_time_to_ready', aggregation=ExplicitBucketHistogramAggregation(
[0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 60, 120, 300])),
]
reader = PeriodicExportingMetricReader(OTLPMetricExporter(timeout=2),
export_interval_millis=5000, export_timeout_millis=2000)
metrics.set_meter_provider(MeterProvider(resource=attributes, metric_readers=[reader], views=views))
meter.create_observable_counter('lab_process_cpu', unit='s',
callbacks=[lambda _: [metrics.Observation(process_time())]])
# /proc reports resident pages of this process (the container runs Linux).
meter.create_observable_gauge('lab_process_rss', unit='By', callbacks=[rss])
meter.create_observable_gauge('lab_process_alive', callbacks=[lambda _: [metrics.Observation(1)]])
meter.create_observable_gauge('lab_process_heartbeat', unit='s',
callbacks=[lambda _: [metrics.Observation(time())]])
if role == 'worker':
meter.create_observable_gauge('lab_worker_busy', callbacks=[lambda _: [metrics.Observation(worker_busy)]])
meter.create_observable_gauge('lab_worker_capacity', callbacks=[lambda _: [metrics.Observation(1)]])
def rss(_):
try:
with open('/proc/self/statm') as stats:
value = int(stats.read().split()[1]) * os.sysconf('SC_PAGE_SIZE')
except OSError:
value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * (1 if sys.platform == 'darwin' else 1024)
return [metrics.Observation(value)]
def log(event, severity=logging.INFO, **fields):
payload = {'timestamp': datetime.now(timezone.utc).isoformat(),
'severity': logging.getLevelName(severity), 'service.name': service_name,
'event': event, **fields}
context = trace.get_current_span().get_span_context()
if context.is_valid:
payload.update(trace_id=f'{context.trace_id:032x}', span_id=f'{context.span_id:016x}')
body = json.dumps(payload, separators=(',', ':'))
print(body, flush=True)
if log_handler:
record = logging.LogRecord(__name__, severity, __file__, 0, body, (), None)
record.event = event
log_handler.handle(record)
@contextmanager
def span(name, **options):
if not options.get("kind") and not trace.get_current_span().get_span_context().is_valid:
yield trace.get_current_span()
return
with tracer.start_as_current_span(name, record_exception=False,
set_status_on_exception=False, **options) as active:
try:
yield active
except Exception as exc:
active.set_status(StatusCode.ERROR)
active.set_attribute('error.type', type(exc).__name__)
raise
class HTTP:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope['type'] != 'http' or scope['path'] in ('/health/live', '/health/ready'):
await self.app(scope, receive, send)
return
method = scope['method']
if method not in ('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'):
method = 'OTHER'
headers = {key.decode(): value.decode('latin1') for key, value in scope['headers']
if key in (b'traceparent', b'tracestate')}
status = 500
started = perf_counter()
async def capture(message):
nonlocal status
if message['type'] == 'http.response.start':
status = message['status']
await send(message)
with span(method, kind=SpanKind.SERVER, context=propagator.extract(headers)) as active:
try:
await self.app(scope, receive, capture)
finally:
route = getattr(scope.get('route'), 'path', 'unmatched')
active.update_name(f'{method} {route}')
active.set_attributes({'http.request.method': method, 'http.route': route,
'http.response.status_code': status})
if status >= 500:
active.set_status(Status(StatusCode.ERROR))
labels = {'method': method, 'route': route, 'status_class': f'{status // 100}xx'}
http_requests.add(1, labels)
http_duration.record(perf_counter() - started, labels)
log('http_request', logging.ERROR if status >= 500 else logging.INFO,
method=method, route=route, status=status,
request_id=scope.get('state', {}).get('request_id'))
+100
View File
@@ -0,0 +1,100 @@
from uuid import uuid4
from psycopg.errors import UniqueViolation
from .database import get_connection
def serialize_user(row):
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": row["created_at"].isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
}
def create_user(username, display_name, password_hash):
with get_connection() as conn:
with conn.cursor() as cur:
try:
cur.execute(
"""
INSERT INTO users (
id, username, display_name, password_hash
)
VALUES (%s, %s, %s, %s)
RETURNING id, username, display_name, created_at
""",
(uuid4(), username, display_name, password_hash),
)
return serialize_user(cur.fetchone())
except UniqueViolation:
conn.rollback()
return None
def find_user_by_username(username):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT id, username, display_name,
password_hash, created_at
FROM users
WHERE username = %s
""",
(username,),
)
return cur.fetchone()
def create_session(user_id, token_hash, expires_at):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO sessions (
id, user_id, token_hash, expires_at
)
VALUES (%s, %s, %s, %s)
""",
(uuid4(), user_id, token_hash, expires_at),
)
def revoke_session(token_hash):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE sessions
SET revoked_at = NOW()
WHERE token_hash = %s
AND revoked_at IS NULL
AND expires_at > NOW()
RETURNING id
""",
(token_hash,),
)
return cur.fetchone() is not None
def find_session_user(token_hash):
with get_connection() as conn:
row = conn.execute("""
SELECT u.id, u.username, u.display_name, u.created_at
FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = %s AND s.revoked_at IS NULL
AND s.expires_at > NOW()
""", (token_hash,)).fetchone()
return serialize_user(row) if row else None
def replace_password_hash(user_id, previous, replacement):
with get_connection() as conn:
conn.execute("""
UPDATE users SET password_hash = %s WHERE id = %s AND password_hash = %s
""", (replacement, user_id, previous))
+185
View File
@@ -0,0 +1,185 @@
"""One in-flight delivery per worker process. ACK follows the durable decision."""
from datetime import datetime
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile
from time import perf_counter
from uuid import UUID
from botocore.exceptions import BotoCoreError, ClientError
from PIL import Image
from .credentials import credentials
from .database import get_connection
from .broker import QUEUE, channel
from .faults import checkpoint
from .jobs import claim, fail, finish
from .process import serve
from .storage import BUCKET, s3
from . import telemetry as otel
VARIANTS = {'thumbnail': 'image/jpeg', 'crop': 'image/jpeg', 'optimized': 'image/webp'}
class PermanentError(Exception):
pass
def original(attachment):
key = attachment['object_key']
if key.startswith('staging/'):
with get_connection() as conn:
# Keep cleanup out until the entire source has been buffered.
conn.execute('SELECT pg_advisory_xact_lock_shared(hashtextextended(%s,0))', (key,))
current = conn.execute('SELECT staging_key FROM attachments WHERE id=%s',
(attachment['id'],)).fetchone()
if not current or current['staging_key'] != key:
raise PermanentError('source_missing')
data = read_original(key)
else:
data = read_original(key)
if (len(data) != attachment['size_bytes']
or hashlib.sha256(data).hexdigest() != attachment['sha256']):
raise PermanentError('source_checksum_mismatch')
return data
def read_original(key):
try:
body = s3.get_object(Bucket=BUCKET, Key=key)['Body']
except ClientError as exc:
if exc.response.get('Error', {}).get('Code') in ('NoSuchKey', '404'):
raise PermanentError('source_missing') from None
raise
with otel.span('s3.read_original'):
try:
return body.read(10 * 1024**2 + 1)
finally:
body.close()
def put(job, variant, data, mime, dimensions=None):
checksum = hashlib.sha256(data).hexdigest()
key = f'results/{job["attachment_id"]}/v{job["pipeline_version"]}/{variant}/{checksum}'
s3.put_object(Bucket=BUCKET, Key=key, Body=data, ContentType=mime)
entry = dict(key=key, sha256=checksum, size_bytes=len(data), content_type=mime)
if dimensions:
entry.update(width=dimensions[0], height=dimensions[1])
return entry
def process(job, attachment):
data = original(attachment)
with tempfile.TemporaryDirectory(prefix='pipeline-') as target:
directory = Path(target)
(directory / 'original').write_bytes(data)
with otel.span('image.render'):
proc = subprocess.run([sys.executable, '-m', 'src.render_image', target,
str(job['pipeline_version'])], timeout=20, check=False)
if proc.returncode:
raise PermanentError('invalid_image' if proc.returncode == 15 else 'processing_limit')
action = checkpoint(job, 'before_s3')
if action == 'permanent':
raise PermanentError('invalid_image')
if action == 'temporary':
raise OSError('injected transient error')
manifest = {'original': put(job, 'original', data, attachment['content_type'])}
for variant, mime in VARIANTS.items():
path = directory / variant
with Image.open(path) as image:
dimensions = image.size
manifest[variant] = put(job, variant, path.read_bytes(), mime, dimensions)
checkpoint(job, 'after_s3')
return manifest
def handle(ch, method, properties, body):
headers = (properties.headers or {}) if properties else {}
context = otel.propagator.extract({key: value for key, value in headers.items()
if key in ('traceparent', 'tracestate') and isinstance(value, str)})
labels = {'messaging.system': 'rabbitmq', 'messaging.destination.name': QUEUE,
'messaging.message.redelivered': bool(method.redelivered)}
with otel.span(f'{QUEUE} process', context=context, kind=otel.SpanKind.CONSUMER,
attributes=labels) as active:
handle_delivery(ch, method, body, active)
def handle_delivery(ch, method, body, active):
try:
message = json.loads(body)
if (type(message['schema_version']) is not int or message['schema_version'] != 1
or message['type'] != QUEUE
or any(type(message[field]) is not int or message[field] < 1
for field in ('pipeline_version', 'attempt'))):
raise ValueError('Invalid carrier')
if datetime.fromisoformat(message['created_at']).tzinfo is None:
raise ValueError('Missing UTC offset')
for field in ('job_id', 'attachment_id'):
message[field] = UUID(message[field])
except (ValueError, TypeError, KeyError, AttributeError):
ch.basic_reject(method.delivery_tag, requeue=False)
return
active.set_attribute('job.attempt', message['attempt'])
with otel.span('job.claim'):
claimed = claim(message)
if claimed:
job, attachment = claimed
started = perf_counter()
otel.worker_busy = 1
outcome = 'interrupted'
try:
outcome = process_job(job, attachment)
if outcome == 'ready':
checkpoint(job, 'after_commit')
finally:
otel.worker_busy = 0
labels = dict(otel.JOB, outcome=outcome)
otel.job_duration.record(perf_counter() - started, labels)
otel.job_results.add(1, labels)
active.set_attribute('job.outcome', outcome)
if outcome in ('failed', 'retry', 'interrupted'):
active.set_status(otel.StatusCode.ERROR)
otel.log('job_attempt', attempt=job['attempt'], outcome=outcome)
else:
active.set_attribute('job.outcome', 'ignored')
otel.log('delivery_ignored')
ch.basic_ack(method.delivery_tag)
def process_job(job, attachment):
try:
manifest = process(job, attachment)
except PermanentError as exc:
return fail(job, str(exc), permanent=True)
except subprocess.TimeoutExpired:
return fail(job, 'processing_limit', permanent=True)
except ClientError:
return fail(job, 'storage_unavailable')
except (BotoCoreError, OSError):
return fail(job, 'temporary_failure')
with otel.span('job.publish_ready'):
outcome, latency = finish(job, manifest)
if latency is not None:
otel.time_to_ready.record(max(0, latency), otel.JOB)
return outcome
def loop(stopping, progress):
with channel() as (connection, ch):
ch.basic_qos(prefetch_count=1)
while not stopping.is_set():
credentials.get()
method, properties, body = ch.basic_get(QUEUE, auto_ack=False)
if method:
handle(ch, method, properties, body)
else:
connection.process_data_events(time_limit=0.2)
progress()
if __name__ == '__main__':
serve(loop, 'worker')
+28
View File
@@ -0,0 +1,28 @@
"""Measure the configured per-replica Argon2id slot budget on the app image."""
from concurrent.futures import ThreadPoolExecutor
from math import ceil
import resource
from time import perf_counter
from src.auth import hash_password, iterations, memory, parallelism, verify_password
from src.login_limits import KDF_SLOTS
def timed_verify(encoded):
started = perf_counter()
assert not verify_password(encoded, "another synthetic password")
return (perf_counter() - started) * 1000
def main():
encoded = hash_password("synthetic benchmark password")
timed_verify(encoded)
with ThreadPoolExecutor(max_workers=KDF_SLOTS) as executor:
samples = sorted(executor.map(lambda _: timed_verify(encoded), range(24)))
print(f"Argon2id memory={memory} KiB time={iterations} lanes={parallelism} slots={KDF_SLOTS} "
f"samples={len(samples)} p50={samples[11]:.1f}ms p95={samples[ceil(.95 * len(samples)) - 1]:.1f}ms "
f"peak_rss={resource.getrusage(resource.RUSAGE_SELF).ru_maxrss} KiB")
if __name__ == "__main__":
main()
+8
View File
@@ -0,0 +1,8 @@
# Use with a unique COMPOSE_PROJECT_NAME and a new LAB7_STATE.
services:
openbao:
ports: !override ["127.0.0.1:28200:8200"]
lb:
ports: !override ["127.0.0.1:28443:8443"]
grafana:
ports: !override ["127.0.0.1:23007:3000"]
+224
View File
@@ -0,0 +1,224 @@
"""Isolated API qualification. Sends synthetic requests only to the grade-4 port."""
import argparse
import base64
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import http.client
import json
import os
from pathlib import Path
import ssl
import subprocess
from time import monotonic, sleep, time
from uuid import uuid4
from observability import Grafana, wait
ROOT = Path(__file__).resolve().parents[1]
WINDOW = int(os.getenv("LOGIN_WINDOW_SECONDS", "10"))
LIMIT = int(os.getenv("LOGIN_WINDOW_LIMIT", "40"))
def call(context, method, path, *, data=None, token=None, authorization=None):
connection = http.client.HTTPSConnection("localhost", 28443, context=context, timeout=5)
headers = {"Content-Type": "application/json"}
if token or authorization:
headers["Authorization"] = authorization or "Bearer " + token
try:
connection.request(method, path, None if data is None else json.dumps(data), headers)
reply = connection.getresponse()
return (reply.status, reply.getheader("X-Instance-Id"), reply.getheader("Retry-After"),
reply.read(), reply.getheader("X-Request-Id"))
finally:
connection.close()
def next_window():
sleep(WINDOW - time() % WINDOW + 0.15)
def login(context):
next_window()
start = monotonic()
path = "/api/v1/auth/sessions"
with ThreadPoolExecutor(max_workers=12) as executor:
replies = list(executor.map(lambda _: call(context, "POST", path), range(LIMIT * 2)))
assert monotonic() - start < WINDOW - 1
assert Counter(row[0] for row in replies) == {401: LIMIT, 429: LIMIT}
assert len({row[1] for row in replies if row[0] == 401 and row[1]}) == 2
assert all(row[2] and 1 <= int(row[2]) <= WINDOW for row in replies if row[0] == 429)
print(f"PASS: {LIMIT} shared admissions and {LIMIT} throttled across both API replicas")
next_window()
basic = base64.b64encode(b"absent_fixture_user:synthetic_password").decode()
start = monotonic()
with ThreadPoolExecutor(max_workers=12) as executor:
replies = list(executor.map(lambda _: call(context, "POST", path,
authorization="Basic " + basic), range(LIMIT * 2)))
elapsed = monotonic() - start
counts = Counter(row[0] for row in replies)
assert elapsed < WINDOW - 1 and counts.keys() == {401, 429}
assert counts[401] <= LIMIT and sum(counts.values()) == LIMIT * 2
assert call(context, "GET", "/health/ready")[0] == 200
print(f"PASS: wrong-password burst {elapsed:.3f}s: {counts[401]} rejected after hash, {counts[429]} throttled")
next_window()
assert call(context, "POST", path)[0] == 401
print("PASS: admissions resume in the next window")
def rehash(context):
username = "rehash_" + uuid4().hex[:12]
password = uuid4().hex
assert call(context, "POST", "/api/v1/users", data={
"username": username, "display_name": "Rehash fixture", "password": password
})[0] == 201
compose = ["sh", str(ROOT / "scripts/compose.sh"), "exec", "-T", "api-a", "python", "-c"]
code = """
import json, sys
from argon2 import PasswordHasher
import psycopg
from src.credentials import credentials
from src.auth import password_hasher
username, password, operation = json.load(sys.stdin)
credentials.start()
with psycopg.connect(credentials.get()["database_url"]) as conn:
old = PasswordHasher(memory_cost=19456, time_cost=2, parallelism=1)
if operation == "seed":
conn.execute("UPDATE users SET password_hash=%s WHERE username=%s", (old.hash(password), username))
else:
value = conn.execute("SELECT password_hash FROM users WHERE username=%s", (username,)).fetchone()[0]
assert password_hasher.verify(value, password) and not password_hasher.check_needs_rehash(value)
credentials.stop.set()
"""
subprocess.run([*compose, code], input=json.dumps([username, password, "seed"]), text=True, check=True)
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
next_window()
assert call(context, "POST", "/api/v1/auth/sessions", authorization="Basic " + basic)[0] == 201
subprocess.run([*compose, code], input=json.dumps([username, password, "verify"]), text=True, check=True)
print("PASS: successful login rehashed an older Argon2id profile")
def rotation(context, kind):
username = "rotate_" + uuid4().hex[:12]
password = uuid4().hex
assert call(context, "POST", "/api/v1/users", data={
"username": username, "display_name": "Rotation fixture", "password": password
})[0] == 201
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
result = call(context, "POST", "/api/v1/auth/sessions", authorization="Basic " + basic)
assert result[0] == 201
token = json.loads(result[3])["token"]
counts = Counter()
instances = set()
with subprocess.Popen(["python3", str(ROOT / "scripts" / f"rotate-{kind}.py")], cwd=ROOT) as process:
while process.poll() is None:
try:
status, instance, *_ = call(context, "GET", "/api/v1/users/me", token=token)
counts[status] += 1
if status == 200 and instance:
instances.add(instance)
except (OSError, http.client.HTTPException):
counts["transport_error"] += 1
sleep(0.1)
print(f"During {kind} rotation: {dict(counts)}, API replicas observed: {len(instances)}")
assert process.returncode == 0 and counts.keys() == {200} and len(instances) == 2
def log_hygiene(context):
username, password = "logs_" + uuid4().hex[:12], uuid4().hex
assert call(context, "POST", "/api/v1/users", data={
"username": username, "display_name": "Log fixture", "password": password
})[0] == 201
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
next_window()
result = call(context, "POST", "/api/v1/auth/sessions", authorization="Basic " + basic)
assert result[0] == 201
token = json.loads(result[3])["token"]
authenticated = call(context, "GET", "/api/v1/users/me", token=token)
assert authenticated[0] == 200
logs = subprocess.check_output(
["sh", str(ROOT / "scripts/compose.sh"), "logs", "--no-color",
"api-a", "api-b", "worker", "recovery", "postgres", "otel-collector"], text=True
)
grafana = Grafana("https://localhost:23007")
secrets = (password, token, basic)
assert all(value not in logs for value in secrets)
for request_id in (result[4], authenticated[4]):
assert request_id
query = '{service_name="messenger-api"} | json | request_id="' + request_id + '"'
telemetry = wait(lambda: grafana.logs(query), timeout=45)
trace_id = next(log["trace_id"] for log in telemetry if log.get("trace_id"))
spans = wait(lambda: grafana.trace(trace_id), timeout=45)
sampled = json.dumps((telemetry, spans))
assert all(value not in sampled for value in secrets)
subprocess.run(
["sh", str(ROOT / "scripts/compose.sh"), "exec", "-T", "--user", "postgres", "postgres",
"psql", "-Xq", "-v", "ON_ERROR_STOP=1", "-d", "messenger"],
input=f"UPDATE sessions SET expires_at=now()-interval '1 second' WHERE user_id="
f"(SELECT id FROM users WHERE username='{username}');",
text=True, check=True,
)
assert call(context, "GET", "/api/v1/users/me", token=token)[0] == 401
print("PASS: container logs and correlated Loki/Tempo records exclude synthetic credentials")
print("PASS: the same bearer is denied after session expiry")
def await_ready(context, status, seconds):
deadline = monotonic() + seconds
while monotonic() < deadline:
try:
if call(context, "GET", "/health/ready")[0] == status:
return
except (OSError, http.client.HTTPException):
pass
sleep(0.5)
raise AssertionError(f"Readiness did not reach HTTP {status}")
def availability(context, kind):
compose = ["sh", str(ROOT / "scripts/compose.sh")]
if kind == "login-recovery":
subprocess.run([*compose, "stop", "postgres"], check=True)
try:
subprocess.run([*compose, "run", "--rm", "-T", "probe", "login-unavailable"], check=True)
finally:
subprocess.run([*compose, "start", "postgres"], check=True)
await_ready(context, 200, 45)
next_window()
assert call(context, "POST", "/api/v1/auth/sessions")[0] == 401
print("PASS: both login endpoints fail closed with PostgreSQL down and recover after restart")
else:
seal = "import bao; bao.request('sys/seal', token=bao.operator()['root_token'], method='PUT')"
subprocess.run(["python3", "-c", seal], env=dict(os.environ, PYTHONPATH=str(ROOT / "scripts")), check=True)
try:
await_ready(context, 503, 45)
finally:
subprocess.run(["python3", str(ROOT / "scripts/bao.py"), "unseal"], check=True)
await_ready(context, 200, 45)
print("PASS: sealed OpenBao drains bounded snapshots, fails closed, and recovers after unseal")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("test", choices=("login", "rehash", "db", "leaf", "login-recovery",
"sealed", "log-hygiene"))
args = parser.parse_args()
if (not os.environ.get("COMPOSE_PROJECT_NAME", "").startswith("lab7-grade4-")
or "grade4.compose.yaml" not in os.environ.get("COMPOSE_FILE", "")
or os.environ.get("LAB7_OPENBAO_URL") != "https://localhost:28200"):
parser.error("Use the isolated Compose override and OpenBao port documented in REPORT.md")
context = ssl.create_default_context(cafile=str(Path(os.environ["LAB7_STATE"]) / "trust/ca.crt"))
if args.test == "login":
login(context)
elif args.test == "rehash":
rehash(context)
elif args.test == "log-hygiene":
log_hygiene(context)
elif args.test in ("login-recovery", "sealed"):
availability(context, args.test)
else:
rotation(context, args.test)
if __name__ == "__main__":
main()
+451
View File
@@ -0,0 +1,451 @@
#!/usr/bin/env python3
"""Read live Grafana data sources and run bounded faults in Compose lab6."""
import argparse
import base64
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import json
import ssl
import os
from pathlib import Path
import subprocess
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
COMPOSE = ROOT / 'scripts/compose.sh'
FIXTURE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
ROUTE = '/api/v1/chats/{chat_id}/messages'
SUPPRESS = (HTTPError, URLError, TimeoutError)
def now():
return datetime.now(timezone.utc).isoformat()
def compose(*args, capture=True):
result = subprocess.run([COMPOSE, *args], cwd=ROOT, check=True, text=True,
capture_output=capture, timeout=75)
return result.stdout
def sql_command(statement):
return [COMPOSE, 'exec', '-T', '--user', 'postgres', 'postgres', 'psql', '-XAt', '-v', 'ON_ERROR_STOP=1',
'-U', 'postgres', '-d', 'messenger', '-c', statement]
def sql(statement):
return subprocess.check_output(sql_command(statement), text=True, timeout=10).strip()
def wait(action, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
result = action()
except SUPPRESS:
result = None
if result:
return result
time.sleep(1)
raise AssertionError(f'timeout after {timeout}s')
class Grafana:
def __init__(self, url):
self.url = url
state = Path(os.getenv("LAB7_STATE", f"/private/tmp/mtusi2026lab7-{os.getuid()}"))
password = (state / "grafana/admin").read_text().strip()
self.context = ssl.create_default_context(cafile=str(state / "trust/ca.crt"))
self.headers = {'Authorization': 'Basic ' + base64.b64encode(f'admin:{password}'.encode()).decode()}
def get(self, path, **params):
query = '?' + urlencode(params) if params else ''
with urlopen(Request(self.url + path + query, headers=self.headers), timeout=10, context=self.context) as response:
return json.load(response)
def proxy(self, uid, path, **params):
return self.get(f'/api/datasources/proxy/uid/{uid}{path}', **params)
def prom(self, expression, timestamp=None):
params = {'query': expression}
if timestamp is not None:
params['time'] = timestamp
return self.proxy('prometheus', '/api/v1/query', **params)['data']['result']
def scalar(self, expression):
values = self.prom(expression)
return float(values[0]['value'][1]) if values else None
def alerts(self):
return {item['labels']['alertname']: item['state']
for item in self.proxy('prometheus', '/api/v1/alerts')['data']['alerts']}
def logs(self, query):
data = self.proxy('loki', '/loki/api/v1/query_range', query=query, limit=50,
start=int((time.time()-600)*1e9), end=time.time_ns())['data']['result']
return [json.loads(line) for stream in data for _, line, *_ in stream['values']]
def trace(self, trace_id):
trace = self.proxy('tempo', f'/api/traces/{trace_id}')
spans = []
for batch in trace.get('batches', trace.get('resourceSpans', [])):
resource = {item['key']: next(iter(item['value'].values()))
for item in batch['resource']['attributes']}
for scope in batch['scopeSpans']:
for span in scope['spans']:
spans.append(dict(span, service_name=resource['service.name']))
return spans
def save(name, data):
(ROOT / 'evidence' / (name + '.json')).write_text(json.dumps(data, indent=2, ensure_ascii=False,
allow_nan=False) + '\n')
def upload(client, actor, chat, trace_id=None):
headers = {'Content-Type': 'image/png'}
if trace_id:
headers.update(traceparent=f'00-{trace_id}-0123456789abcdef-01', tracestate='lab=synthetic')
return client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
202, actor=actor, raw=FIXTURE, headers=headers, schema='Attachment')
def raw_read(client, actor, chat, trace_id=None):
headers = {'Authorization': 'Bearer ' + actor['token']}
if trace_id:
headers['traceparent'] = f'00-{trace_id}-0123456789abcdef-01'
request = Request(client.base + ROUTE.format(chat_id=chat['id']), headers=headers)
started = time.monotonic()
try:
response = urlopen(request, timeout=10, context=ssl.create_default_context(cafile=os.environ["CA_FILE"]))
except HTTPError as exc:
response = exc
except (URLError, TimeoutError):
return {'status': 0, 'seconds': time.monotonic()-started}
with response:
response.read()
return {'status': response.code, 'seconds': time.monotonic()-started,
'request_id': response.headers.get('X-Request-Id')}
def verify(client, grafana, retry):
actor, _, _, chat = client.bootstrap()
trace_id = uuid4().hex
marker = upload(client, actor, chat, trace_id)
started = time.time()
client.wait_ready(actor, marker['json'])
if retry:
# Stop uses a local, fixed Compose service. Resume even after an assertion.
compose('stop', 'worker')
try:
trace_id = uuid4().hex
marker = upload(client, actor, chat, trace_id)
attachment_id = marker['json']['id']
sql(f"""INSERT INTO pipeline_faults(attachment_id,pipeline_version,point,action)
VALUES ('{attachment_id}',1,'before_s3','temporary')""")
finally:
compose('start', 'worker')
client.wait_ready(actor, marker['json'])
request_id = marker['headers']['X-Request-Id']
required = {'attachment.accept', 'outbox.enqueue', 's3.put_object', 's3.read_original',
'job.claim', 'job.publish_ready', 'postgresql.execute', 'postgresql.transaction.close'}
def complete_trace():
spans = grafana.trace(trace_id)
by_id = {item['spanId']: item for item in spans}
consumers = [item for item in spans if item['kind'] in (5, 'SPAN_KIND_CONSUMER')]
if len(consumers) < (2 if retry else 1):
return None
for consumer in consumers:
producer = by_id.get(consumer.get('parentSpanId'))
if not producer or producer.get('parentSpanId') not in by_id:
return None
return spans if required <= {item['name'] for item in spans} else None
spans = wait(complete_trace)
check(required <= {s['name'] for s in spans}, 'missing spans along upload path')
by_id = {s['spanId']: s for s in spans}
consumers = [s for s in spans if s['kind'] in (5, 'SPAN_KIND_CONSUMER')]
check(len(consumers) >= (2 if retry else 1), 'consumer / retry span absent')
for consumer in consumers:
producer = by_id[consumer['parentSpanId']]
check(producer['kind'] in (4, 'SPAN_KIND_PRODUCER'), 'consumer parent must be producer')
check(by_id[producer['parentSpanId']]['name'] == 'attachment.accept', 'producer parent mismatch')
query = '{service_name=~"messenger-api|messenger-worker|messenger-publisher"} | json | trace_id="' + trace_id + '"'
logs = wait(lambda: (rows if (rows := grafana.logs(query)) and
{'messenger-api', 'messenger-worker', 'messenger-publisher'}
<= {row['service.name'] for row in rows} else None))
check(any(row.get('request_id') == request_id for row in logs), 'request id not correlated')
check(all(row['trace_id'] == trace_id for row in logs), 'different trace IDs in Loki')
if retry:
check({'retry','ready'} <= {row.get('outcome') for row in logs}, 'retry and ready should be in one trace')
prometheus = grafana.proxy('prometheus', '/api/v1/query_exemplars', query='lab_http_duration_seconds_bucket',
start=started-15, end=time.time())['data']
dashboard = grafana.get('/api/dashboards/uid/messenger-lab6')['dashboard']
metrics = {}
for panel in dashboard['panels']:
if panel['datasource']['uid'] != 'prometheus':
continue
metrics[panel['title']] = {target['expr']: grafana.prom(target['expr']) for target in panel['targets']}
save('signals-retry' if retry else 'signals', {
'timestamp': now(), 'trace_id': trace_id, 'request_id': request_id, 'spans': spans, 'logs': logs,
'dashboard_queries': metrics, 'exemplar_count': sum(len(x['exemplars']) for x in prometheus),
})
class Incident:
queries = {
'queue_depth': 'max(lab_queue_depth)', 'oldest_seconds': 'max(lab_oldest_job_age_seconds)',
'api_waiting': 'sum(lab_db_pool_waiting{service_name="messenger-api"})',
'api_pool_used': 'sum(lab_db_pool_used{service_name="messenger-api"})',
'workers': 'sum(lab_worker_capacity)', 'api_p95': 'histogram_quantile(0.95,sum by(le)(rate(lab_http_duration_seconds_bucket[30s])))',
'api_burn_30s': 'lab:burn_api:30s', 'api_burn_2m': 'lab:burn_api:2m',
'api_burn_5m': 'lab:burn_api:5m',
'ready_burn_30s': 'lab:burn_ready:30s', 'ready_burn_2m': 'lab:burn_ready:2m',
'ready_burn_5m': 'lab:burn_ready:5m',
'ready_burn_1h': 'lab:burn_ready:1h', 'api_burn_1h': 'lab:burn_api:1h',
'ready_cohort_1h': 'lab:sli_ready_total:1h', 'api_cohort_1h': 'lab:sli_api_total:1h',
'collector_rss': 'otelcol_process_memory_rss_bytes',
'tempo_queue': 'sum(otelcol_exporter_queue_size{exporter="otlphttp/tempo"})',
'tempo_queue_limit': 'sum(otelcol_exporter_queue_capacity{exporter="otlphttp/tempo"})',
'tempo_drop': 'sum(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"})',
'tempo_enqueue_drop': 'sum(otelcol_exporter_enqueue_failed_spans_total{exporter="otlphttp/tempo"})',
}
def __init__(self, grafana, name):
self.grafana, self.name = grafana, name
self.started = time.time()
self.data = {'started': now(), 'samples': [], 'markers': {}}
def mark(self, name):
self.data['markers'][name] = {'timestamp': now(), 't': round(time.time()-self.started, 2)}
def sample(self, phase):
t = time.time()
alerts = self.grafana.alerts()
row = {'phase': phase, 't': round(t-self.started, 2), 'timestamp': now(), 'alerts': alerts}
# A single Prometheus query gets metrics at the same evaluation timestamp.
expression = ' or '.join(f'label_replace(({expr}),"measurement","{key}","","")'
for key, expr in self.queries.items())
for result in self.grafana.prom(expression, t):
value = float(result['value'][1])
if abs(value) < float('inf'):
row[result['metric']['measurement']] = value
self.data['samples'].append(row)
save(self.name, self.data)
return row
def settle(self, names, phase='recovery', timeout=330, predicate=None):
deadline = time.monotonic()+timeout
while time.monotonic() < deadline:
row = self.sample(phase)
if names.isdisjoint(row['alerts']) and (predicate is None or predicate(row)):
self.mark('resolved')
return
time.sleep(5)
raise AssertionError('alerts did not resolve')
def finish(self):
transitions = {}
names = {name for row in self.data['samples'] for name in row['alerts']}
for name in sorted(names):
fired = next((row for row in self.data['samples']
if row['alerts'].get(name) == 'firing'), None)
if fired is None:
continue
resolved = next((row for row in self.data['samples']
if row['t'] > fired['t'] and name not in row['alerts']), None)
transitions[name] = {'firing_t': fired['t'], 'resolved_t': resolved['t'] if resolved else None}
self.data['transitions'] = transitions
save(self.name, self.data)
def queue_incident(client, grafana):
actor, _, _, chat = client.bootstrap()
trial = Incident(grafana, 'incident-queue')
target = {'QueueLag', 'ReadyBurnFast', 'ReadyBurnSlow'}
trial.settle(target, phase='baseline', timeout=330)
attachments = []
compose('stop', 'worker')
trial.mark('worker_stopped')
fired = set()
try:
deadline = time.monotonic()+140
while time.monotonic() < deadline:
start = time.monotonic()
attachments.append(upload(client, actor, chat)['json'])
if len(attachments) % 3 == 1:
row = trial.sample('worker_stopped')
fired.update(name for name, state in row['alerts'].items() if state == 'firing')
time.sleep(max(0, 2 - (time.monotonic()-start)))
check(target <= fired, 'queue / ready burn alerts did not all fire')
samples = [row for row in trial.data['samples'] if row['phase'] == 'worker_stopped']
check(max(row.get('queue_depth', 0) for row in samples) > 10, 'no backlog growth')
check(max(row.get('oldest_seconds', 0) for row in samples) > 30, 'no age growth')
finally:
compose('start', 'worker')
trial.mark('worker_restarted')
trial.finish()
for attachment in attachments:
client.wait_ready(actor, attachment)
trial.mark('all_ready')
trial.data['accepted'] = len(attachments)
trial.settle(target, predicate=lambda row: row.get('queue_depth') == 0 and row.get('oldest_seconds') == 0)
trial.finish()
def db_incident(client, grafana, spike):
actor, _, _, chat = client.bootstrap()
trial = Incident(grafana, 'incident-db-spike' if spike else 'incident-db-long')
target = {'HighHTTPErrorRate', 'APIBurnFast', 'APIBurnSlow'}
trial.settle(target, phase='baseline')
statuses = Counter()
trace_id = uuid4().hex
if spike:
# A real short PostgreSQL lock. First warm the same route at 3 requests/s.
deadline = time.monotonic() + 125
while time.monotonic() < deadline:
start = time.monotonic()
reading = raw_read(client, actor, chat)
statuses[f'baseline_{reading["status"]}'] += 1
time.sleep(max(0, 1/3-(time.monotonic()-start)))
lock_seconds = 7 if spike else 140
# The transaction lock is released by PostgreSQL even if this client exits.
statement = (f"SET statement_timeout='{lock_seconds+2}s'; "
f'BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep({lock_seconds}); ROLLBACK')
lock = subprocess.Popen(sql_command(statement), cwd=ROOT, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
fired = set()
probe = None
try:
wait(lambda: sql("""SELECT count(*) FROM pg_locks
WHERE relation='messages'::regclass AND mode='AccessExclusiveLock'
AND granted""") == '1', timeout=6)
trial.mark('db_lock_acquired')
with ThreadPoolExecutor(max_workers=32) as pool:
first = pool.submit(raw_read, client, actor, chat, trace_id)
concurrency = 11 if spike else 30
load = [pool.submit(raw_read, client, actor, chat) for _ in range(concurrency)]
trial.sample('db_lock')
for response in load:
statuses[str(response.result()['status'])] += 1
probe = first.result()
statuses[str(probe['status'])] += 1
while lock.poll() is None:
start = time.monotonic()
# Fixed number of in-flight requests, no client retries.
if spike:
reads = [pool.submit(raw_read, client, actor, chat)]
else:
reads = [pool.submit(raw_read, client, actor, chat) for _ in range(6)]
row = trial.sample('db_lock')
fired.update(name for name, state in row['alerts'].items() if state == 'firing')
for response in reads:
statuses[str(response.result()['status'])] += 1
time.sleep(max(0, 1-(time.monotonic()-start)))
finally:
lock.wait(timeout=lock_seconds+5)
trial.mark('db_lock_released')
trial.finish()
check(probe and probe['status'] == 503, 'locked SQL did not yield expected API 503')
spans = wait(lambda: grafana.trace(trace_id))
sql_spans = [span for span in spans if span['name'] == 'postgresql.execute']
check(any(int(span['endTimeUnixNano'])-int(span['startTimeUnixNano']) >= 4e9 for span in sql_spans),
'trace does not distinguish a slow DB query')
request_id = probe['request_id']
logs = wait(lambda: grafana.logs('{service_name="messenger-api"} | json | request_id="' + request_id + '"'))
check(any(row['trace_id'] == trace_id and row['status'] == 503 for row in logs), 'no correlated HTTP error log')
trial.data.update(statuses=dict(statuses), failing_probe=probe, trace_id=trace_id, spans=spans, logs=logs)
check(raw_read(client, actor, chat)['status'] == 200, 'DB did not recover')
if spike:
deadline = time.monotonic()+45
while time.monotonic() < deadline:
trial.sample('post_spike')
for _ in range(9):
reading = raw_read(client, actor, chat)
statuses[f'recovery_{reading["status"]}'] += 1
time.sleep(1/3)
observations = [row['alerts'] for row in trial.data['samples']]
check(not any(set(row) & {'APIBurnFast','APIBurnSlow'} for row in observations),
'short spike caused an API burn alert')
else:
check(target <= fired, 'sustained DB incident did not fire all API alerts')
trial.data['statuses'] = dict(statuses)
trial.finish()
trial.settle(target)
trial.finish()
def telemetry_incident(client, grafana):
actor, _, _, chat = client.bootstrap()
trial = Incident(grafana, 'incident-telemetry')
base = trial.sample('baseline')
check(base.get('collector_rss', 0) > 0, 'collector RSS metric missing')
compose('stop', 'tempo')
trial.mark('tempo_stopped')
confirmed = 0
try:
deadline = time.monotonic()+50
while time.monotonic() < deadline:
client.message(actor, chat, 'synthetic upload during trace outage')
marker = upload(client, actor, chat)
client.wait_ready(actor, marker['json'])
confirmed += 1
if confirmed % 3 == 1:
trial.sample('tempo_stopped')
time.sleep(1)
finally:
compose('start', 'tempo')
trial.mark('tempo_restarted')
trial.finish()
trial.data['writes_and_ready'] = confirmed
loss = lambda row: row.get('tempo_drop', 0)+row.get('tempo_enqueue_drop', 0)
check(max(map(loss, trial.data['samples'])) > loss(base), 'trace losses not observed')
wait(lambda: trace_after_recovery(client, grafana, actor, chat),
timeout=100)
trial.mark('new_trace_available')
trial.settle({'TelemetryExportLoss'})
trial.finish()
def trace_after_recovery(client, grafana, actor, chat):
trace_id = uuid4().hex
upload(client, actor, chat, trace_id)
try:
return wait(lambda: grafana.trace(trace_id), timeout=8)
except AssertionError:
return None
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('test', choices=['signals', 'retry', 'queue', 'spike', 'db', 'telemetry'])
parser.add_argument('--base-url', default='https://localhost:8443')
parser.add_argument('--grafana', default='https://localhost:3007')
args = parser.parse_args()
client, grafana = Client(args.base_url), Grafana(args.grafana)
if args.test in ('signals', 'retry'):
verify(client, grafana, args.test == 'retry')
else:
{
'queue': queue_incident,
'spike': lambda c,g: db_incident(c,g,True),
'db': lambda c,g: db_incident(c,g,False),
'telemetry': telemetry_incident,
}[args.test](client, grafana)
print(f'PASS {args.test} {now()}')
if __name__ == '__main__':
main()
+366
View File
@@ -0,0 +1,366 @@
#!/usr/bin/env python3
"""Destructive fault injection for a disposable, dedicated LAB6 Compose project."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
from image_probe import jpeg_size
COMPOSE = str(ROOT / 'scripts/compose.sh')
def compose(*args):
return subprocess.run([COMPOSE, *args], check=True, text=True, capture_output=True, timeout=120).stdout.strip()
def sql(query):
return compose('exec', '-T', '--user', 'postgres', 'postgres', 'psql', '-XAt', '-v', 'ON_ERROR_STOP=1',
'-U', 'postgres', '-d', 'messenger', '-c', query)
def job(attachment, version=1):
return json.loads(sql(f"""SELECT row_to_json(j) FROM image_jobs j
WHERE attachment_id='{attachment['id']}' AND pipeline_version={version}"""))
def events(job_id, name):
return int(sql(f"SELECT count(*) FROM job_events WHERE job_id='{job_id}' AND event='{name}'"))
def operator(command, identifier, *args):
return json.loads(compose('run', '--rm', '-T', 'ops', command,
identifier, *args))
def wait(predicate, description, timeout=105):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return
time.sleep(0.2)
raise AssertionError(f'timeout: {description}')
def arm(attachment, point, action, version=1):
sql(f"""INSERT INTO pipeline_faults(attachment_id,pipeline_version,point,action)
VALUES ('{attachment['id']}',{version},'{point}','{action}')""")
def hit(attachment, point, release=False):
scope = f"attachment_id='{attachment['id']}' AND pipeline_version=1 AND point='{point}'"
wait(lambda: sql(f'SELECT hit_at IS NOT NULL FROM pipeline_faults WHERE {scope}') == 't', point)
if release:
sql(f'UPDATE pipeline_faults SET released=true WHERE {scope}')
def objects(attachment, version):
prefix = f"results/{attachment['id']}/v{version}/"
# Operator-only inspection on the disposable stand keeps Recovery's IAM
# policy limited to staging. MinIO prints relative keys for this prefix.
code = '''
MC_CONFIG_DIR=$(mktemp -d)
export MC_CONFIG_DIR
trap 'rm -rf "$MC_CONFIG_DIR"' EXIT
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
cp /run/trust/ca.crt "$MC_CONFIG_DIR/certs/CAs/lab.crt"
mc alias set local https://s3:9000 labroot "$(cat /run/identity/admin)" >/dev/null 2>&1
mc --json ls --recursive "local/messenger-attachments/$1"
'''
lines = compose('exec', '-T', 's3', 'sh', '-ec', code, 'sh', prefix).splitlines()
return sorted(prefix + json.loads(line)['key'] for line in lines)
def report(name, started, attachment, **metrics):
print(json.dumps(dict(scenario=name, result='PASS', seconds=round(time.monotonic() - started, 3),
attachment_id=attachment['id'], **metrics), ensure_ascii=False), flush=True)
def service_health(service):
return [json.loads(line)['Health'] for line in
compose('ps', '--format', 'json', service).splitlines()]
def experiments(client):
sql('GRANT SELECT, UPDATE(hit_at) ON pipeline_faults TO publisher, worker')
compose('up', '-d', '--no-deps', '--wait', 'publisher', 'worker')
worker_count = compose('ps', '-q', 'worker').splitlines()
check(len(worker_count) >= 2, 'two workers are required')
for service in ('publisher', 'worker'):
enabled = compose('exec', '-T', service, 'printenv', 'PIPELINE_FAULTS')
check(enabled == '1', f'fault injection disabled on {service}')
alice, bob, eve, chat = client.bootstrap()
def upload():
return client.attachment(alice, chat)
def meta(attachment, status=200):
return client.call('GET', '/api/v1/attachments/' + attachment['id'], status,
actor=bob, schema='Attachment')['json']
def verify(attachment, content, version=1):
wait(lambda: job(attachment, version)['state'] == 'ready', f'job v{version} ready')
ready = meta(attachment)
check(ready['status'] == 'ready', 'attachment is not ready')
row = job(attachment, version)
active = int(sql(f"SELECT active_version FROM attachments WHERE id='{attachment['id']}'"))
check(active == version, 'wrong active version')
check(events(row['id'], 'published') == 1, 'expected one published manifest')
check(set(row['manifest']) == {'original', 'thumbnail', 'crop', 'optimized'}, 'manifest incomplete')
check(set(objects(attachment, version)) == {v['key'] for v in row['manifest'].values()},
'unexpected keys or duplicated side effects')
path = '/api/v1/attachments/' + attachment['id'] + '/content?variant='
check({v['name'] for v in ready['variants']} == {'thumbnail', 'crop', 'optimized'}, 'wrong API variants')
for variant, entry in row['manifest'].items():
downloaded = client.call('GET', path + variant, actor=bob)
data = downloaded['bytes']
check(downloaded['headers'].get_content_type() == entry['content_type'], 'wrong MIME')
check(len(data) == entry['size_bytes'], 'wrong size')
check(hashlib.sha256(data).hexdigest() == entry['sha256'], 'wrong checksum')
if variant == 'original':
check(data == content, 'original changed')
elif variant == 'optimized':
check(data[:4] == b'RIFF' and data[8:12] == b'WEBP', 'invalid WebP signature')
check((entry['width'], entry['height']) == (320, 200), 'WebP must not be enlarged')
else:
expected = (256, 160) if variant == 'thumbnail' else (128, 128)
check(jpeg_size(data) == expected, 'wrong JPEG dimensions')
return row
started = time.monotonic()
key = 'concurrent-message-' + chat['id']
def post_message(_):
return client.message(alice, chat, 'concurrent', key=key)
with ThreadPoolExecutor(max_workers=6) as executor:
responses = list(executor.map(post_message, range(6)))
check(len({response['json']['id'] for response in responses}) == 1, 'concurrent writes created duplicates')
check(len({response['headers']['X-Instance-Id'] for response in responses}) >= 2,
'concurrent requests did not reach two API instances')
report('concurrent_message', started, {'id': None}, requests=6)
started = time.monotonic()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png'
fixture = (ROOT / 'tests/fixtures/sample.png').read_bytes()
client.call('POST', path, 404, actor=eve, raw=fixture, headers={'Content-Type': 'image/png'})
client.call('POST', path, 415, actor=alice, raw=fixture, headers={'Content-Type': 'image/jpeg'})
client.call('POST', path, 415, actor=alice, raw=b'not a png', headers={'Content-Type': 'image/png'})
client.call('POST', path, 413, actor=alice, raw=b'',
headers={'Content-Type': 'image/png', 'Content-Length': '10485761'})
report('upload_validation', started, {'id': None}, statuses=[404, 415, 415, 413])
started = time.monotonic()
compose('stop', '-t', '1', 'broker')
try:
attachment, content = upload()
row = job(attachment)
check(meta(attachment)['status'] == 'queued', 'upload did not remain queued')
check(sql(f"SELECT count(*) FROM job_outbox WHERE job_id='{row['id']}'") == '1',
'lost intent during real broker outage')
wait(lambda: service_health('publisher') == ['unhealthy']
and service_health('worker') == ['unhealthy'] * len(worker_count),
'AMQP outage reflected in publisher and worker health', timeout=45)
finally:
compose('start', 'broker')
verify(attachment, content)
wait(lambda: service_health('publisher') == ['healthy']
and service_health('worker') == ['healthy'] * len(worker_count),
'publisher and all workers became healthy again', timeout=45)
report('broker_unavailable', started, attachment, attempt=1, pipeline_health_recovered=True)
for point in ('before_publish', 'after_confirm', 'before_s3', 'after_s3', 'after_commit'):
started = time.monotonic()
compose('stop', '-t', '1', 'publisher')
if point in ('before_publish', 'after_confirm'):
compose('stop', '-t', '1', 'worker')
attachment, content = upload()
arm(attachment, point, 'crash')
compose('start', 'publisher')
hit(attachment, point)
if point in ('before_publish', 'after_confirm'):
job_id = job(attachment)['id']
wait(lambda: events(job_id, 'broker_confirmed'), 'outbox drained after publisher crash')
compose('start', 'worker')
if point in ('before_s3', 'after_s3'):
keys = objects(attachment, 1)
check(len(keys) == (0 if point == 'before_s3' else 4), 'wrong S3 effects at crash')
check(job(attachment)['state'] == 'processing', 'manifest was already committed at crash')
row = verify(attachment, content)
wanted = {'before_s3': 2, 'after_s3': 2}.get(point, 1)
check(row['attempt'] == wanted, f'wrong attempt after {point}')
crash_logs = [json.loads(line[line.index('{'):]) for line in
compose('logs', '--no-color', 'publisher', 'worker').splitlines()
if '"event":"pipeline_fault"' in line]
check(any(item['point'] == point and item['action'] == 'crash' and item['job_id'] == row['id']
for item in crash_logs), 'missing crash log')
if point in ('after_commit', 'after_confirm'):
wait(lambda: events(row['id'], 'delivery_ignored'), 'duplicate delivery ignored')
report(point, started, attachment, attempt=row['attempt'], published=1)
started = time.monotonic()
compose('stop', '-t', '1', 'publisher')
attachment, content = upload()
arm(attachment, 'before_s3', 'pause')
compose('start', 'publisher')
hit(attachment, 'before_s3')
initial = job(attachment)
operator('redeliver', initial['id'])
wait(lambda: events(initial['id'], 'delivery_ignored'), 'parallel duplicate rejected')
check(events(initial['id'], 'claimed') == 1, 'duplicate obtained live lease')
current = verify(attachment, content)
check(current['fence'] > initial['fence'] and current['attempt'] == 2, 'lease was not reclaimed')
hit(attachment, 'before_s3', release=True)
wait(lambda: events(initial['id'], 'fence_rejected'), 'old attempt fenced')
ignored = events(initial['id'], 'delivery_ignored')
operator('redeliver', initial['id'])
wait(lambda: events(initial['id'], 'delivery_ignored') > ignored, 'completed duplicate rejected')
check(verify(attachment, content)['manifest'] == current['manifest'], 'duplicate changed the manifest')
report('duplicate_and_fencing', started, attachment, fence=current['fence'], attempt=current['attempt'])
started = time.monotonic()
compose('stop', '-t', '1', 'publisher')
attachment, content = upload()
arm(attachment, 'after_s3', 'pause')
compose('start', 'publisher')
hit(attachment, 'after_s3')
operator('reprocess', attachment['id'], '2')
second = verify(attachment, content, 2)
hit(attachment, 'after_s3', release=True)
old = job(attachment)
wait(lambda: job(attachment)['state'] == 'superseded' or events(old['id'], 'fence_rejected'),
'v1 completed after v2 without publication')
ignored = events(old['id'], 'delivery_ignored')
operator('redeliver', old['id'])
wait(lambda: events(old['id'], 'delivery_ignored') > ignored, 'reordered v1 redelivery ignored')
check(verify(attachment, content, 2)['manifest'] == second['manifest'], 'v1 changed v2')
check(events(old['id'], 'published') == 0, 'v1 published despite newer version')
report('reorder_in_flight', started, attachment, active_version=2)
started = time.monotonic()
compose('stop', '-t', '1', 'publisher')
attachment, content = upload()
old = job(attachment)
second = operator('reprocess', attachment['id'], '2')
operator('redeliver', second['job_id'])
verify(attachment, content, 2)
check(job(attachment)['state'] == 'queued', 'v1 must still be queued before late delivery')
operator('redeliver', old['id'])
wait(lambda: events(old['id'], 'superseded') == 1, 'late v1 delivery superseded')
check(events(old['id'], 'claimed') == 0, 'late v1 obtained a lease')
compose('start', 'publisher')
check(not objects(attachment, 1), 'late v1 produced S3 side effects')
verify(attachment, content, 2)
report('late_old_delivery', started, attachment, active_version=2)
started = time.monotonic()
attachment, content = upload()
first = verify(attachment, content)
compose('stop', '-t', '1', 'publisher')
try:
operator('reprocess', attachment['id'], '2')
check(meta(attachment)['status'] == 'ready', 'reprocessing hid the published version')
visible = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content?variant=thumbnail',
actor=bob)['bytes']
check(hashlib.sha256(visible).hexdigest() == first['manifest']['thumbnail']['sha256'],
'published version changed before v2 commit')
finally:
compose('start', 'publisher')
second = verify(attachment, content, 2)
for name in ('thumbnail', 'crop', 'optimized'):
check(first['manifest'][name]['sha256'] != second['manifest'][name]['sha256'], 'v2 did not change bytes')
operator('redeliver', first['id'])
wait(lambda: events(first['id'], 'delivery_ignored'), 'duplicate of published v1')
check(verify(attachment, content, 2)['manifest'] == second['manifest'], 'old duplicate changed v2')
report('atomic_version_switch', started, attachment, active_version=2)
for action in ('temporary', 'permanent'):
started = time.monotonic()
compose('stop', '-t', '1', 'publisher')
attachment, content = upload()
arm(attachment, 'before_s3', action)
compose('start', 'publisher')
initial = job(attachment)
if action == 'permanent':
wait(lambda: job(attachment)['state'] == 'failed', 'permanent failure')
check(meta(attachment)['error_code'] == 'invalid_image', 'unsafe or wrong error code')
path = '/api/v1/attachments/' + attachment['id'] + '/content'
client.call('GET', path, 409, actor=bob)
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': '', 'attachment_ids': [attachment['id']]},
headers={'Idempotency-Key': attachment['id']})
check(sql(f"SELECT error_code FROM job_dead_letters WHERE job_id='{initial['id']}'") == 'invalid_image',
'missing DLQ entry')
operator('replay', initial['id'])
check(sql(f"SELECT replayed_at IS NOT NULL FROM job_dead_letters WHERE job_id='{initial['id']}'") == 't',
'missing replay audit')
completed = verify(attachment, content)
check(completed['attempt'] == 2, 'expected two attempts')
if action == 'temporary':
check(events(initial['id'], 'retry_scheduled') == 1, 'missing transient retry')
report(action + '_error', started, attachment, attempt=2)
stable_attachment, stable_content = attachment, content
stable_manifest = completed['manifest']
started = time.monotonic()
compose('stop', '-t', '1', 'worker')
attachment, content = upload()
row = job(attachment)
wait(lambda: events(row['id'], 'broker_confirmed'), 'durable queue entry')
check(meta(attachment)['status'] == 'queued', 'worker processed despite stop')
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=bob)
message = client.message(alice, chat, '', attachments=[attachment['id']])['json']
compose('restart', 'postgres', 's3', 'broker', 'api-a', 'api-b', 'lb', 'publisher', 'recovery')
wait(lambda: health(client), 'HAProxy readiness')
check(not compose('ps', '-q', 'worker'), 'restart brought workers back too early')
check(meta(attachment)['status'] == 'queued', 'confirmed job changed before worker restart')
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=bob)
compose('start', 'worker')
verify(attachment, content)
page = client.call('GET', f"/api/v1/chats/{chat['id']}/messages", actor=bob,
schema='MessagePage')['json']
check(any(item['id'] == message['id'] and attachment['id'] in item['attachment_ids']
for item in page['items']), 'attachment link did not survive restart')
wait(lambda: sql(f"SELECT staging_key IS NULL FROM attachments WHERE id='{attachment['id']}'") == 't',
'recovery cleaned staging after publication')
wait(lambda: service_health('recovery') == ['healthy'], 'recovery health after restart')
check(verify(stable_attachment, stable_content)['manifest'] == stable_manifest,
'published attachment changed on restart')
check(job(attachment)['attempt'] == 1, 'broker restart lost the original delivery')
report('restart_with_queued_attachment', started, attachment, attempt=1,
message_link_preserved=True, staging_cleaned=True)
def health(client):
try:
client.call('GET', '/health/ready')
except (OSError, AssertionError):
return False
return True
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default='https://localhost:8443')
parser.add_argument('--disposable', action='store_true', required=True,
help='confirm this is an isolated test project')
args = parser.parse_args()
if (not os.environ.get('COMPOSE_PROJECT_NAME', '').startswith('lab7-grade4-')
or 'grade4.compose.yaml' not in os.environ.get('COMPOSE_FILE', '')
or args.base_url.rstrip('/') != 'https://localhost:28443'):
parser.error('Use the isolated Compose project documented in REPORT.md')
try:
try:
experiments(Client(args.base_url))
finally:
sql('REVOKE SELECT, UPDATE(hit_at) ON pipeline_faults FROM publisher, worker')
except (AssertionError, OSError, ValueError, subprocess.SubprocessError) as exc:
# Subprocess output can include internal details. Keep the public summary short.
print('FAIL:', str(exc), file=sys.stderr)
raise SystemExit(1)
+68
View File
@@ -0,0 +1,68 @@
#!/bin/sh
# Use an isolated loopback network and tmpfs storage. No Compose services or volumes.
set -eu
cd "$(dirname "$0")/.."
root=$PWD
app_image=${RECOVERY_TEST_APP_IMAGE:-mtusi2026lab7-app:local}
pg_image=${RECOVERY_TEST_PG_IMAGE:-postgres:16.16-bookworm@sha256:cd0e9518bda5f2ea667ff84d22795d089720c883f288e215d97ce57437e8ef37}
s3_image=bitnamilegacy/minio:2025.7.23-debian-12-r5@sha256:6dabb4a2088c9a79908de3bc05f4586c23ad2182c8908e7e3acbf61c1467fb20
work=$(mktemp -d)
work=$(cd "$work" && pwd -P)
pg=
s3=
cleanup() {
if [ -n "$s3" ]; then docker stop "$s3" >/dev/null 2>&1 || :; fi
if [ -n "$pg" ]; then docker stop "$pg" >/dev/null 2>&1 || :; fi
rm -f "$work"/ca.key "$work"/ca.crt "$work"/ca.srl "$work"/server.csr \
"$work"/server.ext "$work"/certs/private.key "$work"/certs/public.crt
rmdir "$work"/certs "$work"
}
trap cleanup EXIT
mkdir "$work/certs"
openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj '/CN=Recovery test CA' \
-addext 'keyUsage=critical,keyCertSign,cRLSign' -keyout "$work/ca.key" -out "$work/ca.crt" >/dev/null 2>&1
openssl req -new -newkey rsa:2048 -nodes -subj '/CN=localhost' \
-keyout "$work/certs/private.key" -out "$work/server.csr" >/dev/null 2>&1
printf '%s\n' 'subjectAltName=IP:127.0.0.1' 'extendedKeyUsage=serverAuth' > "$work/server.ext"
openssl x509 -req -in "$work/server.csr" -CA "$work/ca.crt" -CAkey "$work/ca.key" \
-CAcreateserial -days 1 -extfile "$work/server.ext" -out "$work/certs/public.crt" >/dev/null 2>&1
pg=$(docker run --rm -d --network none --tmpfs /var/lib/postgresql/data \
-e POSTGRES_DB=recovery_test -e POSTGRES_HOST_AUTH_METHOD=trust "$pg_image")
for attempt in $(seq 1 30); do
if docker exec "$pg" pg_isready -h 127.0.0.1 -U postgres -d recovery_test >/dev/null 2>&1; then break; fi
test "$attempt" -lt 30
sleep 1
done
# Scratch MinIO runs as root solely to read the host-owned disposable TLS key.
s3=$(docker run --rm -d --network "container:$pg" --user 0:0 \
--tmpfs /data --tmpfs /certs --tmpfs /bitnami/minio/data \
--mount "type=bind,src=$work,dst=/fixture,readonly" \
--mount "type=bind,src=$root/infra/minio,dst=/policy,readonly" \
-e MINIO_ROOT_USER=fixture-admin -e MINIO_ROOT_PASSWORD=fixture-admin-password \
--entrypoint /opt/bitnami/minio/bin/minio "$s3_image" server /data --certs-dir /fixture/certs)
for attempt in $(seq 1 30); do
if docker exec "$s3" curl -fsS --cacert /fixture/ca.crt https://127.0.0.1:9000/minio/health/ready >/dev/null 2>&1; then break; fi
test "$attempt" -lt 30
sleep 1
done
docker exec "$s3" sh -ec '
export MC_CONFIG_DIR=/tmp/recovery-test-mc
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
cp /fixture/ca.crt "$MC_CONFIG_DIR/certs/CAs/fixture.crt"
mc alias set fixture https://127.0.0.1:9000 fixture-admin fixture-admin-password >/dev/null
mc mb fixture/messenger-attachments >/dev/null
mc admin user add fixture lab-recovery fixture-recovery-password >/dev/null
mc admin policy create fixture lab-recovery /policy/recovery.json >/dev/null
mc admin policy attach fixture lab-recovery --user lab-recovery >/dev/null
'
docker run --rm --network "container:$pg" \
--mount "type=bind,src=$root,dst=/workspace,readonly" \
--mount "type=bind,src=$work/ca.crt,dst=/fixture-ca.crt,readonly" \
-w /workspace -e PYTHONDONTWRITEBYTECODE=1 \
-e 'RECOVERY_TEST_DSN=host=127.0.0.1 dbname=recovery_test user=postgres' \
-e RECOVERY_TEST_S3=https://127.0.0.1:9000 -e RECOVERY_TEST_CA=/fixture-ca.crt \
-e RECOVERY_TEST_ADMIN_USER=fixture-admin -e RECOVERY_TEST_ADMIN_PASSWORD=fixture-admin-password \
-e RECOVERY_TEST_SCOPED_USER=lab-recovery -e RECOVERY_TEST_SCOPED_PASSWORD=fixture-recovery-password \
--entrypoint python "$app_image" -m unittest discover -s student-tests -p 'test_recovery_*.py' -v
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Check image encoders, geometry, EXIF orientation and alpha on local fixtures."""
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import zlib
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
FIXTURE = ROOT / 'tests/fixtures/sample.png'
def render(directory, version):
subprocess.run([sys.executable, '-m', 'src.render_image', str(directory), str(version)],
cwd=ROOT, check=True)
outputs = {}
for variant, format_name in [('thumbnail', 'JPEG'), ('crop', 'JPEG'), ('optimized', 'WEBP')]:
with Image.open(directory / variant) as image:
image.load()
assert image.format == format_name
assert not image.getexif()
outputs[variant] = (image.size, (directory / variant).read_bytes())
return outputs
def validate(path, mime):
return subprocess.run([sys.executable, '-m', 'src.image_check', str(path), mime],
cwd=ROOT, timeout=10, check=False).returncode
def main():
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp)
original = directory / 'original'
data = FIXTURE.read_bytes()
original.write_bytes(data)
assert validate(original, 'image/png') == 0
assert validate(original, 'image/jpeg') == 15
original.write_bytes(b'corrupt')
assert validate(original, 'image/png') == 15
Image.new('RGB', (1, 1)).save(original, format='TIFF')
assert validate(original, 'image/png') == 15
# Rewrite only IHDR, with a valid CRC, to exercise the pre-decode limit.
header = data[12:16] + struct.pack('>II', 10000, 10000) + data[24:29]
original.write_bytes(data[:12] + header + struct.pack('>I', zlib.crc32(header)) + data[33:])
assert validate(original, 'image/png') == 13
original.write_bytes(data)
print('PASS: PNG validation, MIME mismatch, corrupt input and pixel cap before decoding')
first = render(directory, 1)
assert first == render(directory, 1)
second = render(directory, 2)
assert first.keys() == second.keys()
for variant, shape in [('thumbnail', (256, 160)), ('crop', (128, 128)), ('optimized', (320, 200))]:
assert first[variant][0] == second[variant][0] == shape
assert first[variant][1] != second[variant][1]
assert original.read_bytes() == data
print('PASS: fixture geometry, original preserved, deterministic v1, different v2')
transparent = Image.new('RGBA', (7, 3), (255, 0, 0, 0))
transparent.save(original, format='PNG')
alpha = render(directory, 1)
assert alpha['thumbnail'][0] == (7, 3)
with Image.open(directory / 'thumbnail') as thumbnail:
assert thumbnail.getpixel((0, 0)) == (255, 255, 255)
rotated = Image.new('RGB', (17, 31), 'red')
exif = rotated.getexif()
exif[274] = 6
rotated.save(original, format='JPEG', exif=exif)
assert render(directory, 1)['thumbnail'][0] == (31, 17)
print('PASS: alpha on white, no upscaling, EXIF orientation applied and metadata removed')
if __name__ == '__main__':
main()
+70
View File
@@ -0,0 +1,70 @@
import importlib.util
from pathlib import Path
import sys
import unittest
from unittest.mock import patch
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
def load(name):
spec = importlib.util.spec_from_file_location(name, SCRIPTS / (name + ".py"))
module = importlib.util.module_from_spec(spec)
with patch.object(sys, "path", [str(SCRIPTS), *sys.path]):
spec.loader.exec_module(module)
return module
db = load("rotate-db")
hardening = load("check-hardening")
class RotationSafetyTest(unittest.TestCase):
def setUp(self):
self.old = db.conninfo("api_blue", "fixture")
self.new = db.conninfo("api_green", "replacement")
self.document = {"metadata": {"version": 2}, "data": {"database_url": self.old, "extra": "fixture"}}
self.read = self.enterContext(patch.object(db, "read_generation",
return_value=(self.document, self.old, "api_blue")))
self.probe = self.enterContext(patch.object(db, "db_probe", side_effect=["api_blue", "api_green"]))
self.sql = self.enterContext(patch.object(db, "sql"))
self.request = self.enterContext(patch.object(db, "request"))
self.enterContext(patch.object(db.secrets, "token_hex", return_value="replacement"))
def test_timeout_during_cas_preserves_both_login_passwords(self):
self.request.side_effect = TimeoutError()
with self.assertRaisesRegex(RuntimeError, "CAS outcome uncertain"):
db.rotate("synthetic token")
self.assertIn("ALTER ROLE api_green LOGIN", self.sql.call_args.args[0])
self.sql.assert_called_once()
self.assertEqual(self.request.call_args.args[1]["options"]["cas"], 2)
self.assertEqual(self.request.call_args.args[1]["data"]["extra"], "fixture")
def test_replica_convergence_failure_never_retires_old_password(self):
current = {"metadata": {"version": 3}, "data": {"database_url": self.new}}
self.read.side_effect = [(self.document, self.old, "api_blue"), (current, self.new, "api_green")]
with patch.object(db, "await_active", side_effect=RuntimeError("replica unavailable")):
with self.assertRaisesRegex(RuntimeError, "replica unavailable"):
db.rotate("synthetic token")
self.sql.assert_called_once()
def test_cas_generation_change_during_retire_preserves_other_password(self):
self.sql.return_value = "0"
with patch.object(db, "await_active"):
with self.assertRaisesRegex(RuntimeError, "generation changed"):
db.retire("synthetic token", {"metadata": {"version": 1}}, self.old, "api_blue")
self.assertTrue(all("ALTER" not in item.args[0] for item in self.sql.call_args_list))
class HardeningTest(unittest.TestCase):
def test_flags_root_and_docker_socket(self):
service = {"image": "example", "read_only": True, "cap_drop": ["ALL"],
"security_opt": ["no-new-privileges:true"], "mem_limit": 1, "cpus": 1, "pids_limit": 1,
"volumes": [{"source": "/var/run/docker.sock"}]}
failures = hardening.check({"services": {"worker": service}}, lambda _: "0")
self.assertTrue(any("Docker socket" in item for item in failures))
self.assertTrue(any("root" in item for item in failures))
if __name__ == "__main__":
unittest.main()
+223
View File
@@ -0,0 +1,223 @@
"""Integration tests for a disposable database and bucket, see recovery-test.sh."""
from contextlib import contextmanager
import hashlib
import multiprocessing
import os
from pathlib import Path
from threading import Event, Thread
import unittest
from unittest.mock import patch
from uuid import uuid4
import boto3
from botocore.exceptions import ClientError
import psycopg
from psycopg.conninfo import conninfo_to_dict
from psycopg.rows import dict_row
from src import jobs, recovery, worker
DSN = os.getenv("RECOVERY_TEST_DSN")
ROOT = Path(__file__).resolve().parents[1]
BUCKET = "messenger-attachments"
DATA = b"synthetic attachment"
def reclaim(barrier, queue):
barrier.wait(timeout=10)
queue.put(jobs.recover_one())
def collect_staging(barrier):
barrier.wait(timeout=10)
recovery.cleanup()
@unittest.skipUnless(DSN, "requires the disposable recovery-test.sh stand")
class RecoveryTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if conninfo_to_dict(DSN).get("dbname") != "recovery_test":
raise ValueError("The integration database must be named recovery_test")
with psycopg.connect(DSN) as conn:
conn.execute("CREATE ROLE api_runtime; CREATE ROLE publisher; CREATE ROLE worker; "
"CREATE ROLE recovery; CREATE ROLE ops")
for path in sorted((ROOT / "db/migrations").glob("*.sql")):
conn.execute(path.read_text())
cls.manage = cls.client("RECOVERY_TEST_ADMIN")
cls.scoped = cls.client("RECOVERY_TEST_SCOPED")
@staticmethod
def client(prefix):
return boto3.client("s3", endpoint_url=os.environ["RECOVERY_TEST_S3"],
verify=os.environ["RECOVERY_TEST_CA"], region_name="us-east-1",
aws_access_key_id=os.environ[prefix + "_USER"],
aws_secret_access_key=os.environ[prefix + "_PASSWORD"])
@contextmanager
def connection(self, role=None):
with psycopg.connect(DSN, row_factory=dict_row) as conn:
if role:
conn.execute({"recovery": "SET LOCAL ROLE recovery", "worker": "SET LOCAL ROLE worker"}[role])
yield conn
def setUp(self):
for module in (jobs, recovery):
self.enterContext(patch.object(module, "get_connection", lambda: self.connection("recovery")))
self.enterContext(patch.object(worker, "get_connection", lambda: self.connection("worker")))
self.enterContext(patch.object(recovery, "s3", self.scoped))
self.enterContext(patch.object(worker, "s3", self.manage))
for obj in self.manage.list_objects_v2(Bucket=BUCKET).get("Contents", []):
self.manage.delete_object(Bucket=BUCKET, Key=obj["Key"])
with self.connection() as conn:
conn.execute("TRUNCATE users CASCADE")
self.owner, self.chat = uuid4(), uuid4()
conn.execute("INSERT INTO users (id,username,display_name,password_hash)"
" VALUES (%s,'fixture','Fixture','unused')", (self.owner,))
conn.execute("INSERT INTO chats (id,title,created_by) VALUES (%s,'Fixture',%s)",
(self.chat, self.owner))
def attachment(self, status="queued", *, upload=True):
aid = uuid4()
key = f"staging/{aid}"
if upload:
self.manage.put_object(Bucket=BUCKET, Key=key, Body=DATA)
checksum = hashlib.sha256(DATA).hexdigest()
with self.connection() as conn:
conn.execute("""
INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,size_bytes,
content_type,sha256,staging_key,status,error_code,updated_at)
VALUES (%s,%s,%s,'fixture.png',%s,%s,'image/png',%s,%s,%s,%s,now()-interval '2 days')
""", (aid, self.chat, self.owner, key, len(DATA), checksum, key, status,
"fixture_error" if status == "failed" else None))
return aid, key
def staging(self, aid):
with self.connection() as conn:
return conn.execute("SELECT staging_key FROM attachments WHERE id=%s", (aid,)).fetchone()["staging_key"]
def exists(self, key):
return any(obj["Key"] == key for obj in self.manage.list_objects_v2(
Bucket=BUCKET, Prefix=key).get("Contents", []))
def test_two_processes_reschedule_one_expired_job_once(self):
aid, _ = self.attachment()
with self.connection() as conn:
job = conn.execute("""
INSERT INTO image_jobs (attachment_id,pipeline_version,state,fence,lease_until)
VALUES (%s,1,'processing',3,now()-interval '1 second') RETURNING *
""", (aid,)).fetchone()
ctx = multiprocessing.get_context("fork")
barrier, queue = ctx.Barrier(2), ctx.Queue()
processes = [ctx.Process(target=reclaim, args=(barrier, queue)) for _ in range(2)]
for process in processes:
process.start()
self.assertEqual(sorted(queue.get(timeout=15) for _ in processes), [False, True])
for process in processes:
process.join(10)
self.assertEqual(process.exitcode, 0)
with self.connection() as conn:
current = conn.execute("SELECT state,attempt,failures,lease_until FROM image_jobs WHERE id=%s",
(job["id"],)).fetchone()
self.assertEqual(current, {"state": "queued", "attempt": 2, "failures": 1, "lease_until": None})
self.assertEqual(conn.execute("SELECT count(*) AS n FROM job_outbox WHERE job_id=%s",
(job["id"],)).fetchone()["n"], 1)
self.assertEqual(conn.execute(
"SELECT count(*) AS n FROM job_events WHERE event='retry_scheduled'"
).fetchone()["n"], 1)
self.assertEqual(jobs.fail(job, "late worker"), "ignored")
def test_cleanup_keeps_queued_and_recent_orphan_and_handles_missing(self):
queued, queued_key = self.attachment()
missing, _ = self.attachment("failed", upload=False)
failed, failed_key = self.attachment("failed")
recent = "staging/recent-orphan"
self.manage.put_object(Bucket=BUCKET, Key=recent, Body=DATA)
recovery.cleanup()
recovery.cleanup()
self.assertEqual(self.staging(queued), queued_key)
self.assertTrue(self.exists(queued_key))
self.assertTrue(self.exists(recent))
self.assertIsNone(self.staging(missing))
self.assertIsNone(self.staging(failed))
self.assertFalse(self.exists(failed_key))
with patch.object(recovery, "RETENTION", 0):
recovery.cleanup()
self.assertFalse(self.exists(recent))
self.assertTrue(self.exists(queued_key))
def test_cleanup_respects_worker_read_lock_and_published_original(self):
aid, key = self.attachment()
result = f"results/{aid}/v1/original/fixture"
self.manage.put_object(Bucket=BUCKET, Key=result, Body=DATA)
with self.connection() as conn:
attachment = conn.execute("SELECT * FROM attachments WHERE id=%s", (aid,)).fetchone()
conn.execute("""
INSERT INTO image_jobs (attachment_id,pipeline_version,state,manifest)
VALUES (%s,1,'ready',jsonb_build_object('original',jsonb_build_object('key',%s::text)))
""", (aid, result))
conn.execute("UPDATE attachments SET active_version=1,status='ready',object_key=%s WHERE id=%s",
(result, aid))
at_read, release = Event(), Event()
outcome = []
def buffered_read(source_key):
at_read.set()
if not release.wait(5):
raise TimeoutError("test reader was not released")
return DATA
with patch.object(worker, "read_original", side_effect=buffered_read):
reader = Thread(target=lambda: outcome.append(worker.original(attachment)))
reader.start()
try:
self.assertTrue(at_read.wait(5))
recovery.cleanup()
self.assertEqual(self.staging(aid), key)
self.assertTrue(self.exists(key))
finally:
release.set()
reader.join(5)
self.assertEqual(outcome, [DATA])
recovery.cleanup()
self.assertIsNone(self.staging(aid))
self.assertFalse(self.exists(key))
self.assertTrue(self.exists(result))
with self.assertRaises(ClientError):
self.scoped.delete_object(Bucket=BUCKET, Key=result)
def test_delete_timeout_does_not_restore_replayable_pointer(self):
aid, key = self.attachment("failed")
delete = self.scoped.delete_object
def lose_response(**kwargs):
delete(**kwargs)
raise TimeoutError("synthetic lost delete response")
with patch.object(self.scoped, "delete_object", side_effect=lose_response):
with self.assertRaises(TimeoutError):
recovery.cleanup()
self.assertIsNone(self.staging(aid))
self.assertFalse(self.exists(key))
recovery.cleanup()
recovery.cleanup()
def test_two_cleanup_processes_leave_active_staging_alone(self):
queued, queued_key = self.attachment()
failed, failed_key = self.attachment("failed")
ctx = multiprocessing.get_context("fork")
barrier = ctx.Barrier(2)
collectors = [ctx.Process(target=collect_staging, args=(barrier,)) for _ in range(2)]
for collector in collectors:
collector.start()
for collector in collectors:
collector.join(10)
self.assertEqual(collector.exitcode, 0)
self.assertEqual(self.staging(queued), queued_key)
self.assertTrue(self.exists(queued_key))
self.assertIsNone(self.staging(failed))
self.assertFalse(self.exists(failed_key))
if __name__ == "__main__":
unittest.main()
+149
View File
@@ -0,0 +1,149 @@
import io
import json
import os
import ssl
import unittest
from unittest.mock import Mock, patch
from urllib.error import HTTPError, URLError
import boto3
from botocore.stub import Stubber
from src import credentials as bao, storage
def response(payload):
return io.BytesIO(json.dumps(payload).encode())
def http_error(status):
return HTTPError("https://bao.invalid", status, "private diagnostic", {}, io.BytesIO(b"private body"))
class StorageTest(unittest.TestCase):
def test_positional_paginator_and_keyword_s3_calls(self):
client = boto3.client("s3", region_name="us-east-1",
aws_access_key_id="fixture", aws_secret_access_key="fixture")
proxy = storage.Storage()
key = {"Bucket": "bucket", "Key": "staging/key"}
with Stubber(client) as stub, patch.dict(os.environ, TLS_CA_FILE="/test/ca"), \
patch.object(storage.boto3, "client", return_value=client) as factory, \
patch.object(storage.credentials, "get") as get:
get.return_value = {"s3_user": "fixture", "s3_password": "fixture"}
stub.add_response("list_objects_v2", {"IsTruncated": True, "NextContinuationToken": "next"},
{"Bucket": "bucket", "Prefix": "staging/"})
stub.add_response("list_objects_v2", {"IsTruncated": False},
{"Bucket": "bucket", "Prefix": "staging/", "ContinuationToken": "next"})
paginator = proxy.get_paginator("list_objects_v2")
self.assertEqual(len(list(paginator.paginate(Bucket="bucket", Prefix="staging/"))), 2)
stub.add_response("put_object", {}, dict(key, Body=b"sample"))
self.assertEqual(proxy.put_object(**key, Body=b"sample"), {})
stub.add_response("get_object", {"Body": b"sample"}, key)
self.assertEqual(proxy.get_object(**key)["Body"], b"sample")
stub.add_response("delete_object", {}, key)
self.assertEqual(proxy.delete_object(**key), {})
factory.assert_called_once()
get.return_value = {"s3_user": "fixture", "s3_password": "rotated"}
proxy.get_paginator(operation_name="list_objects_v2")
self.assertEqual(factory.call_count, 2)
stub.assert_no_pending_responses()
class CredentialTest(unittest.TestCase):
def setUp(self):
self.source = bao.CredentialSource()
self.source.opener = Mock()
self.source.address = "https://bao.invalid"
self.source.scope = self.source.role = "recovery"
self.source.max_age = 10
self.clock = self.enterContext(patch.object(bao, "monotonic", return_value=100))
self.log = self.enterContext(patch.object(bao, "log"))
def token(self, value="initial"):
return response({"auth": {"client_token": value, "lease_duration": 10}})
def kv(self, version=1):
return response({"data": {"data": {"database_url": "fixture-dsn", "s3_user": "lab-recovery",
"s3_password": "fixture-password"}, "metadata": {"version": version}}})
def test_start_loads_only_recovery_scope_before_background_refresh(self):
env = {"BAO_ROLE": "recovery", "BAO_ADDR": "https://bao.invalid", "TLS_CA_FILE": "/test/ca"}
self.source.opener.open.side_effect = [self.token(), self.kv()]
with patch.dict(os.environ, env, clear=True), patch.object(bao, "Thread") as thread, \
patch.object(bao.ssl, "create_default_context") as tls, \
patch.object(bao, "build_opener", return_value=self.source.opener):
self.source.start()
self.assertEqual(self.source.get()["s3_user"], "lab-recovery")
requests = [item.args[0] for item in self.source.opener.open.call_args_list]
self.assertEqual(requests[0].full_url, "https://bao.invalid/v1/auth/cert/login")
self.assertEqual(json.loads(requests[0].data), {"name": "recovery"})
self.assertEqual(requests[1].full_url, "https://bao.invalid/v1/kv/data/messenger/recovery")
tls.return_value.load_cert_chain.assert_called_once_with("/run/identity/bao.crt", "/run/identity/bao.key")
thread.return_value.start.assert_called_once()
def test_token_renewal_refreshes_snapshot_and_login_fallback(self):
self.source.opener.open.side_effect = [self.token(), self.kv(), self.token("renewed"), self.kv(2),
http_error(403), self.token("new-login"), self.kv(3)]
self.source.refresh_once()
self.clock.return_value = 106
self.source.refresh_once()
self.assertEqual(self.source.token, "renewed")
self.assertEqual(self.source.get()["version"], 2)
self.clock.return_value = 112
self.source.refresh_once()
self.assertEqual(self.source.token, "new-login")
self.assertEqual(self.source.get()["version"], 3)
requests = [item.args[0] for item in self.source.opener.open.call_args_list]
self.assertTrue(requests[2].full_url.endswith("/auth/token/renew-self"))
self.assertIsNone(requests[5].get_header("X-vault-token"))
def test_unavailable_keeps_snapshot_only_until_deadline(self):
self.source.opener.open.side_effect = [self.token(), self.kv(), http_error(503),
URLError("private network error")]
self.source.refresh_once()
self.clock.return_value = 105
self.source.refresh_once()
self.assertEqual(self.source.get()["version"], 1)
self.clock.return_value = 110
self.source.refresh_once()
with self.assertRaises(bao.CredentialsUnavailable):
self.source.get()
self.assertEqual([call.kwargs["reason"] for call in self.log.call_args_list],
["unavailable", "unavailable"])
def test_bad_certificate_is_diagnosed_without_certificate_details(self):
self.source.opener.open.side_effect = URLError(ssl.SSLCertVerificationError("private cert details"))
self.source.refresh_once()
with self.assertRaises(bao.CredentialsUnavailable):
self.source.get()
self.assertEqual(self.log.call_args.kwargs["reason"], "tls_error")
self.assertNotIn("private", str(self.log.call_args))
def test_server_rejects_certificate_login(self):
self.source.opener.open.side_effect = http_error(400)
self.source.refresh_once()
with self.assertRaises(bao.CredentialsUnavailable):
self.source.get()
self.assertEqual(self.log.call_args.kwargs["operation"], "login")
self.assertEqual(self.log.call_args.kwargs["reason"], "certificate_auth_rejected")
def test_forbidden_or_missing_kv_invalidates_previous_snapshot(self):
for status, reason in ((403, "forbidden"), (404, "kv_missing")):
with self.subTest(status=status):
self.source.token = None
self.source.opener.open.side_effect = [self.token(), self.kv(), http_error(status)]
self.source.refresh_once()
self.source.refresh_once()
with self.assertRaises(bao.CredentialsUnavailable):
self.source.get()
self.assertEqual(self.log.call_args.kwargs["reason"], reason)
self.assertNotIn("private", str(self.log.call_args))
def test_recovery_cannot_configure_another_services_scope(self):
with patch.dict(os.environ, {"BAO_ROLE": "recovery", "BAO_SCOPE": "api"}, clear=True):
with self.assertRaisesRegex(ValueError, "role/scope"):
self.source.start()
if __name__ == "__main__":
unittest.main()
+271
View File
@@ -0,0 +1,271 @@
"""Black-box TLS and AMQP qualification in the disposable operator probe profile."""
import argparse
import base64
import http.client
import json
import socket
import ssl
from time import time_ns
from pathlib import Path
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
import pika
import psycopg
from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
PKI = Path("/probe")
CA = "/run/trust/ca.crt"
def context(identity=None):
result = ssl.create_default_context(cafile=CA)
if identity and identity.endswith(".pem"):
result.load_cert_chain(str(PKI / identity))
elif identity:
result.load_cert_chain(str(PKI / (identity + ".crt")), str(PKI / (identity + ".key")))
return result
def probe(host, port, identity, path="/health/live", method="GET", body=None, headers=None):
client = http.client.HTTPSConnection(host, port, context=context(identity), timeout=3)
try:
client.request(method, path, body, headers or {"Content-Type": "application/x-protobuf"})
response = client.getresponse()
response.read()
return response.status
finally:
client.close()
def deny_tls(operation):
try:
operation()
except ssl.SSLError as exc:
assert any(part in str(exc).lower() for part in
("alert", "certificate", "eof")), type(exc).__name__
except pika.exceptions.ProbableAuthenticationError:
pass
except pika.exceptions.IncompatibleProtocolError as exc:
assert "certificate" in str(exc).lower(), type(exc).__name__
else:
raise AssertionError("Peer accepted unwanted certificate")
def amqp(identity):
peer = pika.ConnectionParameters(host="broker", port=5671, virtual_host="messenger",
credentials=pika.credentials.ExternalCredentials(),
ssl_options=pika.SSLOptions(context(identity), "broker"), socket_timeout=3,
stack_timeout=4, connection_attempts=1)
return pika.BlockingConnection(peer)
def leafs(mode):
assert probe("lb", 8443, None, "/health/ready") == 200
for host in ("api-a-tls", "api-b-tls"):
assert probe(host, 8444, "lb/client.pem") == 200
if mode == "leaf-revoked":
deny_tls(lambda: probe(host, 8444, "rotation/old.pem"))
if mode == "matrix":
deny_tls(lambda: probe(host, 8444, None))
deny_tls(lambda: probe(host, 8444, "probe/foreign"))
assert probe(host, 8444, "probe/client") == 403
for direct in ("api-a", "api-b"):
try:
with socket.create_connection((direct, 8080), timeout=2):
raise AssertionError("Direct HTTP connection to Uvicorn")
except (socket.gaierror, ConnectionRefusedError):
pass
def matrix():
leafs("matrix")
for identity in (None, "probe/foreign", "probe/client"):
deny_tls(lambda: amqp(identity))
for identity in ("publisher/amqp", "worker/amqp", "ops/amqp"):
with amqp(identity):
pass
with amqp("worker/amqp") as connection:
channel = connection.channel()
channel.confirm_delivery()
try:
channel.basic_publish("attachments", "attachment.process.v1", b"{}", mandatory=True)
except pika.exceptions.ChannelClosedByBroker as exc:
assert exc.reply_code == 403
else:
raise AssertionError("Worker was allowed to publish")
with amqp("publisher/amqp") as connection:
try:
connection.channel().basic_get("attachment.process.v1")
except pika.exceptions.ChannelClosedByBroker as exc:
assert exc.reply_code == 403
else:
raise AssertionError("Publisher was allowed to consume")
def otlp(identity):
return probe("otel-collector", 4318, identity, "/v1/traces", "POST", b"")
for identity in ("api-a/otel", "api-b/otel", "worker/otel"):
assert otlp(identity) == 200
assert otlp("probe/client") == 403
deny_tls(lambda: otlp(None))
deny_tls(lambda: otlp("probe/foreign"))
def bao_call(identity, path, *, token=None, data=None):
client = http.client.HTTPSConnection("openbao", 8200, context=context(identity), timeout=3)
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
try:
client.request("GET" if data is None else "POST", "/v1/" + path,
None if data is None else json.dumps(data), headers)
reply = client.getresponse()
payload = reply.read()
return reply.status, json.loads(payload) if reply.status == 200 else {}
finally:
client.close()
def scoped_kv(role, scope):
identity = f"{role}/bao"
code, login = bao_call(identity, "auth/cert/login", data={"name": role})
assert code == 200
token = login["auth"]["client_token"]
assert 0 < login["auth"]["lease_duration"] <= 60
assert bao_call(identity, "auth/token/renew-self", token=token, data={})[0] == 200
foreign = "recovery" if scope == "api" else "api"
assert bao_call(identity, "kv/data/messenger/" + foreign, token=token)[0] == 403
assert bao_call(identity, "sys/policies/acl/probe-denied", token=token,
data={"policy": ""})[0] == 403
code, own = bao_call(identity, "kv/data/messenger/" + scope, token=token)
assert code == 200
return own["data"]["data"]
def storage_and_secrets():
api = scoped_kv("api-a", "api")
assert scoped_kv("api-b", "api") == api
worker = scoped_kv("worker", "worker")
assert scoped_kv("recovery", "recovery")["s3_user"] == "lab-recovery"
for identity in (None, "probe/foreign", "probe/client", "worker/bao"):
assert bao_call(identity, "auth/cert/login", data={"name": "api-a"})[0] in (400, 403)
for info, user in ((api, ("api_blue", "api_green")), (worker, ("worker",))):
with psycopg.connect(info["database_url"], connect_timeout=3) as db:
actual, tls = db.execute(
"SELECT current_user, ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()"
).fetchone()
assert actual in user and tls
try:
db.execute("SELECT 1 FROM pg_authid")
except psycopg.errors.InsufficientPrivilege:
db.rollback()
else:
raise AssertionError("Application role can read PostgreSQL password verifiers")
try:
psycopg.connect(info["database_url"], sslmode="disable", connect_timeout=3)
except psycopg.OperationalError as exc:
assert "rejects connection" in str(exc)
else:
raise AssertionError("PostgreSQL accepted plaintext")
client = boto3.client("s3", endpoint_url="https://s3:9000", region_name="us-east-1",
verify=CA, aws_access_key_id=info["s3_user"],
aws_secret_access_key=info["s3_password"],
config=Config(s3={"addressing_style": "path"}, connect_timeout=2,
retries={"total_max_attempts": 1}))
try:
client.list_buckets()
except ClientError as exc:
assert exc.response["ResponseMetadata"]["HTTPStatusCode"] == 403
else:
raise AssertionError("Application identity could enumerate buckets")
try:
client.get_object(Bucket="messenger-attachments", Key="operators/authorization-probe")
except ClientError as exc:
assert exc.response["ResponseMetadata"]["HTTPStatusCode"] == 403
else:
raise AssertionError("Application identity could read an operator prefix")
assert probe("s3", 9000, None, "/minio/health/ready") == 200
def telemetry():
logs = ExportLogsServiceRequest()
resource = logs.resource_logs.add()
service = resource.resource.attributes.add()
service.key = "service.name"
service.value.string_value = "lab7-matrix-probe"
record = resource.scope_logs.add().log_records.add()
record.time_unix_nano = time_ns()
record.body.string_value = "synthetic TLS matrix probe"
cases = (
("prometheus", 9090, "grafana/client", "/api/v1/status/buildinfo", "GET", None),
("loki", 3100, "grafana/client", "/loki/api/v1/labels", "GET", None),
("tempo", 3200, "grafana/client", "/api/search", "GET", None),
("loki", 3100, "otel/client", "/otlp/v1/logs", "POST", logs.SerializeToString()),
("tempo", 4318, "otel/client", "/v1/traces", "POST", b""),
)
for host, port, identity, path, method, body in cases:
status = probe(host, port, identity, path, method, body)
assert status in (200, 204), (host, port, path, status)
assert probe(host, port, "probe/client", path, method, body) == 403
deny_tls(lambda: probe(host, port, None, path, method, body))
assert probe("grafana", 3000, None, "/api/health") == 200
assert probe("grafana", 3000, None, "/api/datasources") == 401
admin = (PKI / "grafana/admin").read_bytes().strip()
headers = {"Authorization": "Basic " + base64.b64encode(b"admin:" + admin).decode()}
for backend, path in (("prometheus", "/api/v1/status/buildinfo"),
("loki", "/loki/api/v1/labels"), ("tempo", "/api/search")):
assert probe("grafana", 3000, None, f"/api/datasources/proxy/uid/{backend}{path}",
headers=headers) == 200, backend
for host, port in (("lb", 8404), ("otel-collector", 9464), ("otel-collector", 8888)):
assert probe(host, port, "prometheus/client", "/metrics") == 200, (host, port)
assert probe(host, port, "probe/client", "/metrics") == 403, (host, port)
deny_tls(lambda: probe(host, port, None, "/metrics"))
for host, port in (("otel-collector", 14318), ("prometheus", 19090), ("loki", 13100), ("tempo", 13200)):
try:
with socket.create_connection((host, port), timeout=2):
raise AssertionError(f"Reachable local cleartext hop: {host}:{port}")
except ConnectionRefusedError:
pass
def ingress():
with socket.create_connection(("lb", 8443), timeout=3) as peer:
try:
context().wrap_socket(peer, server_hostname="wrong.invalid")
except ssl.SSLCertVerificationError:
pass
else:
raise AssertionError("Wrong hostname was accepted")
for host, port in (("lb", 8443), ("api-a-tls", 8444), ("api-b-tls", 8444),
("broker", 5671), ("otel-collector", 4318), ("openbao", 8200), ("s3", 9000),
("loki", 3100), ("tempo", 3200), ("prometheus", 9090), ("grafana", 3000)):
conn = http.client.HTTPConnection(host, port, timeout=3)
try:
conn.request("GET", "/health/live")
answer = conn.getresponse()
except (ConnectionResetError, http.client.RemoteDisconnected):
pass
except http.client.BadStatusLine as exc:
assert exc.line.startswith("\x15\x03"), (host, port)
else:
assert answer.status == 400, (host, port, answer.status)
finally:
conn.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("mode", choices=("matrix", "leaf-current", "leaf-revoked", "login-unavailable"))
mode = parser.parse_args().mode
if mode == "matrix":
matrix()
ingress()
storage_and_secrets()
telemetry()
elif mode == "login-unavailable":
for host in ("api-a-tls", "api-b-tls"):
assert probe(host, 8444, "lb/client.pem", "/api/v1/auth/sessions", "POST") == 503
else:
leafs(mode)
print(f"PASS: {mode}")