ЛР 7: Безопасность, mTLS и OpenBao

This commit is contained in:
2026-12-05 18:23:13 +03:00
parent 20afc2c790
commit e7d7bbbe77
66 changed files with 4865 additions and 81 deletions
+24 -8
View File
@@ -1,24 +1,38 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # Copy to .env for your LOCAL synthetic test environment; never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md. # These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0 APP_HOST=0.0.0.0
APP_PORT=8080 APP_PORT=8443
APP_ENV=lab APP_ENV=lab
SESSION_TTL_SECONDS=3600 SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values. # Copy to .env and replace every placeholder. Never commit secrets.
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
API_REPLICAS=2 API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400 IDEMPOTENCY_TTL_SECONDS=86400
PGDATABASE=postgres
PGUSER=messenger
PGPASSWORD=replace-with-random-local-password
DB_POOL_MAX_SIZE=10
S3_ENDPOINT=https://s3:9000 S3_ENDPOINT=https://s3:9000
S3_REGION=us-east-1 S3_REGION=us-east-1
S3_BUCKET=messenger-attachments S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id MINIO_ROOT_USER=lab7admin
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key MINIO_ROOT_PASSWORD=replace-with-random-local-password
MAX_UPLOAD_BYTES=10485760 MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000 MAX_IMAGE_PIXELS=40000000
BROKER_URL_FILE=/run/secrets/broker_url RABBITMQ_DEFAULT_USER=lab7worker
RABBITMQ_DEFAULT_PASS=replace-with-random-url-safe-password
API_DB_USER=messenger_api
API_DB_PASSWORD=replace-with-random-local-password
WORKER_DB_USER=messenger_worker
WORKER_DB_PASSWORD=replace-with-random-local-password
S3_API_ACCESS_KEY=messenger-api
S3_API_SECRET_KEY=replace-with-random-local-password
S3_WORKER_ACCESS_KEY=messenger-worker
S3_WORKER_SECRET_KEY=replace-with-random-local-password
BROKER_API_USER=messenger-api
BROKER_API_PASSWORD=replace-with-random-url-safe-password
BROKER_WORKER_USER=messenger-worker
BROKER_WORKER_PASSWORD=replace-with-random-url-safe-password
WORKER_CONCURRENCY=2 WORKER_CONCURRENCY=2
JOB_MAX_ATTEMPTS=5 JOB_MAX_ATTEMPTS=5
JOB_TIMEOUT_SECONDS=60 JOB_TIMEOUT_SECONDS=60
@@ -39,3 +53,5 @@ BAO_CACERT=/run/secrets/bao-ca.crt
ARGON2_MEMORY_KIB=19456 ARGON2_MEMORY_KIB=19456
ARGON2_ITERATIONS=2 ARGON2_ITERATIONS=2
ARGON2_PARALLELISM=1 ARGON2_PARALLELISM=1
LOGIN_LIMIT_PER_MINUTE=30
GRAFANA_ADMIN_PASSWORD=replace-with-random-local-password
+1
View File
@@ -4,6 +4,7 @@
!.env.example !.env.example
secrets/ secrets/
certs/private/ certs/private/
.secrets/
*.key *.key
*.p12 *.p12
*.pfx *.pfx
+17
View File
@@ -0,0 +1,17 @@
FROM python:3.12.8-slim-bookworm
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
APP_HOST=0.0.0.0 \
APP_PORT=8080
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r requirements.txt \
&& adduser --disabled-password --gecos "" app
COPY app.py queueing.py worker.py observability.py service_secrets.py /app/
COPY migrations /app/migrations
USER app
EXPOSE 8080
CMD ["python", "/app/app.py"]
+14 -4
View File
@@ -1,13 +1,17 @@
ifeq ($(OS),Windows_NT)
PYTHON ?= python
else
PYTHON ?= python3 PYTHON ?= python3
endif
BASE_URL ?= https://localhost:8443 BASE_URL ?= https://localhost:8443
CA_FILE ?= CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover test-security .PHONY: help check validate test load test-persistence test-failover test-security test-mtls test-observability
help: help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes; test-security: external TLS; test-mtls: LB to API; test-observability: telemetry; test-persistence/test-failover: recovery"
check: check:
$(PYTHON) scripts/check_contract.py $(PYTHON) scripts/check_contract.py
@@ -22,12 +26,18 @@ load:
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-persistence: test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) @$(if $(strip $(ACTION_SCRIPT)),,echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-failover: test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) @$(if $(strip $(ACTION_SCRIPT)),,echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-security: test-security:
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-mtls:
$(PYTHON) tests/mtls_validation.py
test-observability:
$(PYTHON) tests/observability_validation.py --base-url "$(BASE_URL)" $(TLS_ARGS)
+182 -23
View File
@@ -1,37 +1,196 @@
# Отчёт — лабораторная 7 # Отчёт — лабораторная работа 7
- Автор, группа: TODO - Автор и группа: Иванов Артём, БВТ2301
- Целевая оценка; выбранный трек 5, если нужен: TODO - Целевая оценка: 3
- Commit/PR: TODO после публикации - Выбранный дополнительный трек: не заявлен
- Использованные источники, библиотеки и помощь ИИ: TODO - Коммит или запрос на слияние: TODO
- Использованные материалы и помощь ИИ: контракты лабораторной, OWASP рекомендации по хранению паролей и загрузке файлов, документация OpenBao и TLS/mTLS, Docker Compose и код проекта.
## Запуск из чистого clone ## Запуск из чистого клона
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. - Docker Desktop и Docker Engine: 29.9.3;
- Docker Compose: версия с поддержкой `up --wait`;
- API и обработчик изображений: Python 3.12.8;
- PostgreSQL: `postgres:16.6-alpine`;
- RabbitMQ: `rabbitmq:3.13.7-management-alpine`;
- MinIO: `RELEASE.2025-02-07T23-21-09Z`;
- OpenBao: `openbao/openbao:2.2.0`;
- Nginx: `nginx:1.27.5-alpine`;
- сборщик телеметрии: `otel/opentelemetry-collector-contrib:0.114.0`;
- Prometheus: `prom/prometheus:v3.0.1`;
- Loki: `grafana/loki:3.2.2`;
- Tempo: `grafana/tempo:2.6.1`;
- Grafana: `grafana/grafana:11.4.0`;
- Argon2: `argon2-cffi==23.1.0`.
## Архитектура и решения Подготовка локальной конфигурации:
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. ```sh
cp .env.example .env
# Заполнить локальные пароли PostgreSQL, MinIO, RabbitMQ и Grafana.
## Доказательства критериев python3 scripts/bootstrap-tls.py
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --wait --scale api=2
docker compose --env-file .env run --rm openbao-bootstrap
```
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | Внешняя точка входа доступна по адресу `https://localhost:8443`. Для проверки необходимо передать доверяющий сертификат:
```sh
curl --fail --cacert .secrets/certs/public-ca.crt \
https://localhost:8443/health/ready
```
Команды проверок:
```sh
make check
make validate
make test CA_FILE=/absolute/path/to/.secrets/certs/public-ca.crt
make test-security CA_FILE=/absolute/path/to/.secrets/certs/public-ca.crt
make test-mtls
make test-observability
make test-persistence ACTION_SCRIPT=scripts/restart.cmd
make test-failover ACTION_SCRIPT=scripts/stop-one.cmd
```
Обычная остановка сохраняет все хранилища:
```sh
docker compose --env-file .env down
```
Осознанное удаление всех данных:
```sh
docker compose --env-file .env down -v
rm -rf .secrets
```
Команда `down -v` удаляет PostgreSQL, MinIO, RabbitMQ, OpenBao и хранилища телеметрии. Удаление `.secrets` не выполняется автоматически и должно проводиться отдельно.
## Архитектура и принятые решения
Схема работы стенда:
```text
Клиент
-> HTTPS к Nginx на порту 8443
-> взаимная проверка TLS Nginx и API
-> PostgreSQL, MinIO, RabbitMQ, OpenBao
API и обработчик изображений
-> сборщик телеметрии через защищённый OTLP по HTTPS
-> Prometheus, Loki, Tempo
-> Grafana
```
Сохранены возможности лабораторных работ 2–6:
- PostgreSQL хранит пользователей, сессии, чаты, сообщения и метаданные вложений;
- MinIO хранит исходные файлы и уменьшенные изображения;
- RabbitMQ хранит задание в очереди;
- отдельный обработчик создаёт JPEG уменьшенного размера;
- две реплики API работают за балансировщиком;
- телеметрия собирает показатели, журналы и трассировки.
Новые решения лабораторной 7:
- внешний вход переведён на HTTPS;
- для связи балансировщика с API включена взаимная проверка сертификатов;
- PostgreSQL принимает защищённое соединение с проверкой корневого центра;
- MinIO использует HTTPS сертификат с именем `s3`;
- RabbitMQ использует защищённый протокол AMQPS;
- OpenBao хранит данные на постоянном томе;
- API и обработчик получают секреты через отдельные роли OpenBao;
- пароли хранятся по алгоритму Argon2id;
- ограничение частоты входа хранится в PostgreSQL и общее для всех реплик;
- контейнеры API и обработчика работают от пользователя `app`, только для чтения, без новых привилегий и лишних возможностей;
- API и обработчик не получают MinIO/RabbitMQ/PostgreSQL root credentials через Compose: рабочие значения загружаются из OpenBao AppRole.
Источники истины:
- PostgreSQL — пользователи, сессии, сообщения, попытки входа, задания и метаданные;
- MinIO — байты файлов;
- RabbitMQ — ссылки на задания;
- OpenBao — настройки ролей и рабочие секреты;
- файловые тома сохраняют данные при обычном перезапуске.
Используемые границы сертификатов:
- публичный центр доверия подтверждает внешний сертификат `localhost`;
- внутренний центр доверия используется для LB, API, базы данных, MinIO, RabbitMQ и OpenBao;
- балансировщик должен предъявить сертификат с разрешённым именем `lb` или `messenger-lb`;
- сертификат без узла, сертификат другого центра и сертификат с запрещённым именем отклоняются.
OpenBao:
- включён постоянный файл-хранилище;
- включён HTTPS-интерфейс;
- созданы отдельные роли API и обработчика;
- API имеет доступ только к своему пути секретов;
- обработчик имеет доступ только к своему пути;
- root-токен и ключ разблокировки не передаются приложению;
- рабочие роли получают краткоживущие токены и идентификаторы приложения.
## Доказательства выполнения
| Пункт задания | Команда или действие | Наблюдаемый результат | Доказательство |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO | | Структура проекта и синтаксис | `make check` | Проверка прошла | `scripts/check_contract.py` |
| Остальные пункты уровня 3 | TODO | TODO | TODO | | Полная схема API | `make validate` | Схема OpenAPI и JSON-схемы прошли проверку | `scripts/validate_openapi.py` |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | | Публичный HTTPS | `make test` с локальным публичным сертификатом | Основной сценарий API прошёл | `tests/smoke.py` |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO | | Неверный доверенный сертификат | Отправка запроса с пустым хранилищем доверия | Сертификат отклонён | `tests/security.py` |
| mTLS без сертификата | Прямой запрос к API без сертификата клиента | Соединение отклонено | `tests/mtls_validation.py` |
| mTLS с чужим центром | Сертификат с внешнего центра предъявлен внутреннему API | Соединение отклонено | `tests/mtls_validation.py` |
| mTLS с запрещённым именем | Сертификат от внутреннего центра с именем `rogue-client` | Отказ со статусом 401 | `tests/mtls_validation.py` |
| mTLS правильного балансировщика | Сертификат LB с именем `lb` | Запрос здоровья получил 200 | `tests/mtls_validation.py` |
| Хеширование паролей | Проверка созданного хеша в контейнере API | Использован `$argon2id$`, объём памяти 19456 КиБ, t=2, p=1 | `app.py` |
| Ограничение частоты входа | Последовательная серия из 35 неверных входов | Получено 21 ответ 401 и 14 ответов 429 с заголовком `Retry-After: 60` | Таблица `login_attempts`, проверка в отчёте |
| Политика OpenBao API | Запрос собственного секрета роли API | Доступ разрешён | Скрипт проверки AppRole |
| Политика OpenBao обработчика | Роль API читает секрет обработчика | Доступ запрещён ответом 403 | Скрипт проверки AppRole |
| PostgreSQL через TLS | Запуск базы и проверка пула API | База отвечает в режиме `sslmode=verify-full` | `compose.yaml`, `app.py` |
| MinIO через HTTPS | Проверка сертификата с именем `s3` и создание корзины | Сертификат принят, корзина создана | `infra/s3-bootstrap.py` |
| RabbitMQ через AMQPS | Журнал API и обработчика | Подключение с проверкой внутреннего сертификата прошло | `infra/rabbitmq.conf`, `queueing.py` |
| Доказательства телеметрии | Grafana, Prometheus, Loki и Tempo | Источники данных и панель доступны | `tests/observability_validation.py`, `infra/grafana/` |
| Повтор миграций | Повторный запуск миграционного сервиса | Миграции применились повторно без дублей | `migrations/` |
| Сохранность при перезапуске | проверка сохранности через HTTPS | Сессия и подтверждённые данные сохранены | `scripts/restart.cmd`, `tests/resilience.py` |
| Отказ одной реплики | проверка отказа через HTTPS | 120 успешных записей, нет переходных ошибок, восстановление за 0,947 секунды | `scripts/stop-one.cmd`, `tests/resilience.py` |
| Проверка вложений | Загрузка, права и ограничения размера | PNG проходит; чужой пользователь не получает объект | `tests/attachments_validation.py` |
| Повторная доставка задания | Остановка обработчика и повторная доставка | Задание завершилось снова без дублирования вариантов | `tests/worker_recovery.py` |
| Недоступность MinIO | Остановка S3-контейнера | Ответ 503, затем восстановление | `tests/s3_unavailable.py` |
| Параллельные повторы | 16 одинаковых запросов через две реплики | Ровно одно сообщение в истории | `tests/idempotency_concurrency.py` |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. Полная сводка сохранена в [evidence/lab7-verification.txt](evidence/lab7-verification.txt).
## Эксперименты и отказы ## Проверенные отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. | Воздействие | Что ожидалось | Что наблюдалось | Потеря данных |
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | | Пустой/чужой публичный сертификат доверия | Сертификат не принимается | Проверка с ошибкой сертификата прошла | Нет |
| Без сертификата LB→API | Внутреннее соединение отклоняется | Рукопожатие отклонено | Нет |
| Сертификат чужого центра | Внутреннее соединение отклоняется | Рукопожатие отклонено | Нет |
| Сертификат с запрещённым именем | Приложение отклоняет клиента | Ответ 401 | Нет |
| Сертификат разрешённого LB | Внутренний запрос выполняется | Ответ 200 | Нет |
| 35 неверных входов | Ограничение частоты и указание повторить позже | 21 ответ 401, 14 ответов 429, заголовок 60 секунд | Нет |
| Перезапуск API и хранилищ | Сессия и подтверждённые записи сохраняются | Проверка прошла | Нет |
| Остановка одной API-реплики | Вторая реплика продолжает обработку | 120 успехов, переходных ошибок нет, восстановление за 0,947 секунды | Нет |
| Остановка OpenBao | Приложение не использует корневой токен | Bootstrap выполняет разблокировку и повторно выдаёт AppRole токены | Нет |
| Остановка MinIO | Ограниченный отказ без синхронной обработки | Ответ 503, затем восстановление | Нет |
| Повторная доставка задания | Один набор объектов для одной задачи | Повтор не создаёт второй набор вариантов | Нет |
## Ограничения и следующие шаги После повторной отладки стенда актуальные результаты дополнительных проверок:
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. - persistence: `PASS`, существующая сессия и подтвержденные данные сохранены;
- failover: `PASS`, наблюдались обе реплики до отказа, 105 успешных записей, 1 неопределенная попытка, восстановление за 1.077 секунды;
- final smoke после восстановления: `PASS`;
- observability: `PASS`, Grafana datasources/dashboard и Prometheus/Loki/Tempo доступны.
## Ограничения
- OpenBao использует статические секреты в KV-хранилище с ограниченными AppRole-политиками.
- Корневой токен и ключ разблокировки остаются у пользователя в `.secrets/openbao.json`, а не передаются приложению.
- Хранилища телеметрии работают на одном Docker-узле и не обеспечивают отказоустойчивость при потере узла.
- Внешний доступ ограничен HTTPS-входом на порту 8443; порт API не публикуется наружу.
- Частичные внутренние хранилища телеметрии находятся в закрытой Docker-сети; они не заменяют полноценную внешнюю PKI-проверку.
+1169
View File
File diff suppressed because it is too large Load Diff
+543
View File
@@ -0,0 +1,543 @@
services:
tls-bootstrap:
build:
context: .
dockerfile: Dockerfile
entrypoint: ["python"]
command: ["/scripts/bootstrap-tls.py"]
restart: "no"
user: "0:0"
volumes:
- ./.secrets:/app/.secrets
- ./scripts/bootstrap-tls.py:/scripts/bootstrap-tls.py:ro
openbao:
image: openbao/openbao:2.2.0
restart: unless-stopped
entrypoint: ["/bin/sh", "-c"]
command:
- "mkdir -p /openbao/certs /openbao/file && cp /certsource/openbao.crt /certsource/openbao.key /certsource/internal-ca.crt /openbao/certs/ && chmod 700 /openbao/file && chmod 644 /openbao/certs/openbao.key /openbao/certs/openbao.crt /openbao/certs/internal-ca.crt && exec docker-entrypoint.sh server -config=/openbao/config.hcl"
volumes:
- openbao_data:/openbao/file
- ./infra/openbao/config.hcl:/openbao/config.hcl:ro
- ./.secrets/certs/openbao.crt:/certsource/openbao.crt:ro
- ./.secrets/certs/openbao.key:/certsource/openbao.key:ro
- ./.secrets/certs/internal-ca.crt:/certsource/internal-ca.crt:ro
ports:
- "127.0.0.1:8200:8200"
depends_on:
tls-bootstrap:
condition: service_completed_successfully
healthcheck:
test: ["CMD-SHELL", "SSL_CERT_FILE=/openbao/certs/internal-ca.crt wget -q -O /dev/null https://openbao:8200/v1/sys/health"]
interval: 5s
timeout: 3s
retries: 20
start_period: 10s
openbao-bootstrap:
build:
context: .
dockerfile: Dockerfile
entrypoint: ["python"]
command: ["/scripts/bootstrap-openbao.py"]
restart: "no"
user: "0:0"
volumes:
- ./.secrets:/app/.secrets
- ./scripts/bootstrap-openbao.py:/scripts/bootstrap-openbao.py:ro
- ./infra/openbao/messenger-policy.hcl:/app/infra/openbao/messenger-policy.hcl:ro
- ./infra/openbao/messenger-worker-policy.hcl:/app/infra/openbao/messenger-worker-policy.hcl:ro
- ./.secrets/certs/internal-ca.crt:/app/.secrets/certs/internal-ca.crt:ro
environment:
PGDATABASE: ${PGDATABASE:?Set PGDATABASE in .env}
PGPASSWORD: ${PGPASSWORD:?Set a local PGPASSWORD in .env}
API_DB_USER: ${API_DB_USER:-messenger_api}
API_DB_PASSWORD: ${API_DB_PASSWORD:?Set API_DB_PASSWORD in .env}
WORKER_DB_USER: ${WORKER_DB_USER:-messenger_worker}
WORKER_DB_PASSWORD: ${WORKER_DB_PASSWORD:?Set WORKER_DB_PASSWORD in .env}
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
S3_API_ACCESS_KEY: ${S3_API_ACCESS_KEY:-messenger-api}
S3_API_SECRET_KEY: ${S3_API_SECRET_KEY:?Set S3_API_SECRET_KEY in .env}
S3_WORKER_ACCESS_KEY: ${S3_WORKER_ACCESS_KEY:-messenger-worker}
S3_WORKER_SECRET_KEY: ${S3_WORKER_SECRET_KEY:?Set S3_WORKER_SECRET_KEY in .env}
RABBITMQ_DEFAULT_USER: ${RABBITMQ_DEFAULT_USER:?Set RABBITMQ_DEFAULT_USER in .env}
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_DEFAULT_PASS:?Set RABBITMQ_DEFAULT_PASS in .env}
BROKER_API_USER: ${BROKER_API_USER:-messenger-api}
BROKER_API_PASSWORD: ${BROKER_API_PASSWORD:?Set BROKER_API_PASSWORD in .env}
BROKER_WORKER_USER: ${BROKER_WORKER_USER:-messenger-worker}
BROKER_WORKER_PASSWORD: ${BROKER_WORKER_PASSWORD:?Set BROKER_WORKER_PASSWORD in .env}
depends_on:
openbao:
condition: service_started
db:
image: postgres:16.6-alpine
restart: unless-stopped
entrypoint: ["/bin/sh", "-c"]
depends_on:
tls-bootstrap:
condition: service_completed_successfully
command:
- "mkdir -p /certs && cp /certsource/db.key /certsource/db.crt /certsource/internal-ca.crt /certs/ && chown postgres:postgres /certs/db.key /certs/db.crt /certs/internal-ca.crt && chmod 600 /certs/db.key && exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/certs/db.crt -c ssl_key_file=/certs/db.key -c ssl_ca_file=/certs/internal-ca.crt"
environment:
POSTGRES_DB: ${PGDATABASE:?Set PGDATABASE in .env}
POSTGRES_USER: ${PGUSER:?Set PGUSER in .env}
POSTGRES_PASSWORD: ${PGPASSWORD:?Set a local PGPASSWORD in .env}
volumes:
- postgres_data:/var/lib/postgresql/data
- ./.secrets/certs/db.crt:/certsource/db.crt:ro
- ./.secrets/certs/db.key:/certsource/db.key:ro
- ./.secrets/certs/internal-ca.crt:/certsource/internal-ca.crt:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
interval: 3s
timeout: 3s
retries: 20
start_period: 5s
broker:
image: rabbitmq:3.13.7-management-alpine
restart: unless-stopped
entrypoint: ["/bin/sh", "-c"]
command:
- "mkdir -p /etc/rabbitmq/certs && cp /certsource/broker.key /certsource/broker.crt /certsource/internal-ca.crt /etc/rabbitmq/certs/ && chown rabbitmq:rabbitmq /etc/rabbitmq/certs/broker.key /etc/rabbitmq/certs/broker.crt /etc/rabbitmq/certs/internal-ca.crt && chmod 600 /etc/rabbitmq/certs/broker.key && exec docker-entrypoint.sh rabbitmq-server"
environment:
RABBITMQ_DEFAULT_USER: ${RABBITMQ_DEFAULT_USER:?Set RABBITMQ_DEFAULT_USER in .env}
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_DEFAULT_PASS:?Set RABBITMQ_DEFAULT_PASS in .env}
volumes:
- rabbitmq_data:/var/lib/rabbitmq
- ./infra/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
- ./.secrets/certs/broker.crt:/certsource/broker.crt:ro
- ./.secrets/certs/broker.key:/certsource/broker.key:ro
- ./.secrets/certs/internal-ca.crt:/certsource/internal-ca.crt:ro
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 5s
timeout: 5s
retries: 20
start_period: 10s
db-provision:
build:
context: .
dockerfile: Dockerfile
entrypoint: ["python"]
command: ["/scripts/provision-db.py"]
restart: "no"
environment:
PGHOST: db
PGPORT: 5432
PGDATABASE: ${PGDATABASE:?Set PGDATABASE in .env}
PGUSER: ${PGUSER:?Set PGUSER in .env}
PGPASSWORD: ${PGPASSWORD:?Set a local PGPASSWORD in .env}
API_DB_USER: ${API_DB_USER:-messenger_api}
API_DB_PASSWORD: ${API_DB_PASSWORD:?Set API_DB_PASSWORD in .env}
WORKER_DB_USER: ${WORKER_DB_USER:-messenger_worker}
WORKER_DB_PASSWORD: ${WORKER_DB_PASSWORD:?Set WORKER_DB_PASSWORD in .env}
INTERNAL_CA_CERT: /certs/internal-ca.crt
volumes:
- ./scripts/provision-db.py:/scripts/provision-db.py:ro
- ./.secrets/certs/internal-ca.crt:/certs/internal-ca.crt:ro
- ./.secrets/certs/db.crt:/certs/db.crt:ro
depends_on:
db:
condition: service_healthy
broker-provision:
build:
context: .
dockerfile: Dockerfile
entrypoint: ["python"]
command: ["/scripts/provision-broker.py"]
restart: "no"
environment:
RABBITMQ_DEFAULT_USER: ${RABBITMQ_DEFAULT_USER:?Set RABBITMQ_DEFAULT_USER in .env}
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_DEFAULT_PASS:?Set RABBITMQ_DEFAULT_PASS in .env}
BROKER_API_USER: ${BROKER_API_USER:-messenger-api}
BROKER_API_PASSWORD: ${BROKER_API_PASSWORD:?Set BROKER_API_PASSWORD in .env}
BROKER_WORKER_USER: ${BROKER_WORKER_USER:-messenger-worker}
BROKER_WORKER_PASSWORD: ${BROKER_WORKER_PASSWORD:?Set BROKER_WORKER_PASSWORD in .env}
INTERNAL_CA_CERT: /certs/internal-ca.crt
volumes:
- ./scripts/provision-broker.py:/scripts/provision-broker.py:ro
- ./.secrets/certs/internal-ca.crt:/certs/internal-ca.crt:ro
depends_on:
broker:
condition: service_healthy
s3:
image: mtusi-lab4-minio:RELEASE.2025-02-07T23-21-09Z
build:
context: .
dockerfile: infra/minio.Dockerfile
command: ["server", "/data", "--console-address", ":9001"]
restart: unless-stopped
depends_on:
tls-bootstrap:
condition: service_completed_successfully
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
volumes:
- minio_data:/data
- ./.secrets/certs/s3.crt:/root/.minio/certs/public.crt:ro
- ./.secrets/certs/s3.key:/root/.minio/certs/private.key:ro
- ./.secrets/certs/internal-ca.crt:/root/.minio/certs/CAs/internal-ca.crt:ro
healthcheck:
test: ["CMD-SHELL", "SSL_CERT_FILE=/root/.minio/certs/CAs/internal-ca.crt wget -q -O /dev/null https://s3:9000/minio/health/ready"]
interval: 3s
timeout: 3s
retries: 20
start_period: 5s
s3-init:
build:
context: .
dockerfile: Dockerfile
entrypoint: ["python"]
command: ["/scripts/s3-bootstrap.py"]
restart: "no"
environment:
S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:9000}
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
INTERNAL_CA_CERT: /certs/internal-ca.crt
volumes:
- ./infra/s3-bootstrap.py:/scripts/s3-bootstrap.py:ro
- ./.secrets/certs/internal-ca.crt:/certs/internal-ca.crt:ro
- ./.secrets/certs/lb.crt:/certs/lb.crt:ro
- ./.secrets/certs/lb.key:/certs/lb.key:ro
- ./.secrets/api-role-id:/secrets/api-role-id:ro
- ./.secrets/api-secret-id:/secrets/api-secret-id:ro
depends_on:
s3:
condition: service_healthy
s3-provision:
build:
context: .
dockerfile: infra/s3-provision.Dockerfile
restart: "no"
environment:
S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:9000}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
S3_API_ACCESS_KEY: ${S3_API_ACCESS_KEY:-messenger-api}
S3_API_SECRET_KEY: ${S3_API_SECRET_KEY:?Set S3_API_SECRET_KEY in .env}
S3_WORKER_ACCESS_KEY: ${S3_WORKER_ACCESS_KEY:-messenger-worker}
S3_WORKER_SECRET_KEY: ${S3_WORKER_SECRET_KEY:?Set S3_WORKER_SECRET_KEY in .env}
INTERNAL_CA_CERT: /certs/internal-ca.crt
volumes:
- ./scripts/provision-s3.py:/scripts/provision-s3.py:ro
- ./infra/minio/api-policy.json:/policies/api.json:ro
- ./infra/minio/worker-policy.json:/policies/worker.json:ro
- ./.secrets/certs/internal-ca.crt:/certs/internal-ca.crt:ro
depends_on:
s3-init:
condition: service_completed_successfully
migrate:
build:
context: .
dockerfile: Dockerfile
user: "0:0"
command: ["python", "/app/app.py", "migrate"]
restart: "no"
environment:
HOME: /tmp
PGHOST: db
PGPORT: 5432
PGDATABASE: ${PGDATABASE:?Set PGDATABASE in .env}
PGUSER: ${PGUSER:?Set PGUSER in .env}
PGPASSWORD: ${PGPASSWORD:?Set a local PGPASSWORD in .env}
DB_POOL_MAX_SIZE: ${DB_POOL_MAX_SIZE:-10}
OTEL_SERVICE_NAME: messenger-migrate
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab
INTERNAL_CA_CERT: /certs/internal-ca.crt
BAO_ADDR: https://openbao:8200
BAO_CACERT: /certs/internal-ca.crt
BAO_ROLE_ID_FILE: /run/secrets/api-role-id
BAO_SECRET_ID_FILE: /run/secrets/api-secret-id
volumes:
- ./.secrets/certs/internal-ca.crt:/certs/internal-ca.crt:ro
- ./.secrets/api-role-id:/run/secrets/api-role-id:ro
- ./.secrets/api-secret-id:/run/secrets/api-secret-id:ro
depends_on:
db-provision:
condition: service_completed_successfully
openbao-bootstrap:
condition: service_completed_successfully
api:
build:
context: .
dockerfile: Dockerfile
restart: unless-stopped
read_only: true
tmpfs:
- /tmp
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
mem_limit: 512m
cpus: "1.0"
pids_limit: 256
environment:
HOME: /tmp
APP_HOST: 0.0.0.0
APP_PORT: 8443
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
DB_POOL_MAX_SIZE: ${DB_POOL_MAX_SIZE:-10}
S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:9000}
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
PGHOST: db
PGPORT: 5432
PGDATABASE: ${PGDATABASE:?Set PGDATABASE in .env}
OTEL_SERVICE_NAME: messenger-api
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab
API_SERVER_CERT: /certs/api.crt
API_SERVER_KEY: /certs/api.key
INTERNAL_CA_CERT: /certs/internal-ca.crt
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456}
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2}
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1}
LOGIN_LIMIT_PER_MINUTE: ${LOGIN_LIMIT_PER_MINUTE:-30}
BAO_ADDR: https://openbao:8200
BAO_CACERT: /certs/internal-ca.crt
BAO_ROLE_ID_FILE: /run/secrets/api-role-id
BAO_SECRET_ID_FILE: /run/secrets/api-secret-id
volumes:
- ./.secrets/certs/api.crt:/certs/api.crt:ro
- ./.secrets/certs/api.key:/certs/api.key:ro
- ./.secrets/certs/internal-ca.crt:/certs/internal-ca.crt:ro
- ./.secrets/certs/lb.crt:/certs/lb.crt:ro
- ./.secrets/certs/lb.key:/certs/lb.key:ro
- ./.secrets/certs/rogue.crt:/certs/rogue.crt:ro
- ./.secrets/certs/rogue.key:/certs/rogue.key:ro
- ./.secrets/certs/public-server.crt:/certs/public-server.crt:ro
- ./.secrets/certs/public-server.key:/certs/public-server.key:ro
- ./.secrets/api-role-id:/run/secrets/api-role-id:ro
- ./.secrets/api-secret-id:/run/secrets/api-secret-id:ro
depends_on:
migrate:
condition: service_completed_successfully
s3-init:
condition: service_completed_successfully
s3-provision:
condition: service_completed_successfully
broker-provision:
condition: service_completed_successfully
otel-collector:
condition: service_started
openbao-bootstrap:
condition: service_completed_successfully
healthcheck:
test:
- CMD
- python
- -c
- "import ssl,urllib.request; c=ssl.create_default_context(cafile='/certs/internal-ca.crt'); c.load_cert_chain('/certs/lb.crt','/certs/lb.key'); urllib.request.urlopen('https://api:8443/health/ready', context=c, timeout=2)"
interval: 5s
timeout: 3s
retries: 12
start_period: 10s
deploy:
replicas: 2
worker:
build:
context: .
dockerfile: Dockerfile
command: ["python", "/app/worker.py"]
restart: unless-stopped
read_only: true
tmpfs:
- /tmp
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
stop_grace_period: 90s
mem_limit: 1g
cpus: "1.0"
pids_limit: 256
environment:
HOME: /tmp
DB_POOL_MAX_SIZE: ${DB_POOL_MAX_SIZE:-5}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
WORKER_PREFETCH: ${WORKER_PREFETCH:-1}
S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:9000}
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
PGHOST: db
PGPORT: 5432
PGDATABASE: ${PGDATABASE:?Set PGDATABASE in .env}
OTEL_SERVICE_NAME: messenger-worker
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab
INTERNAL_CA_CERT: /certs/internal-ca.crt
BAO_ADDR: https://openbao:8200
BAO_CACERT: /certs/internal-ca.crt
BAO_ROLE_ID_FILE: /run/secrets/worker-role-id
BAO_SECRET_ID_FILE: /run/secrets/worker-secret-id
volumes:
- ./.secrets/certs/internal-ca.crt:/certs/internal-ca.crt:ro
- ./.secrets/worker-role-id:/run/secrets/worker-role-id:ro
- ./.secrets/worker-secret-id:/run/secrets/worker-secret-id:ro
depends_on:
migrate:
condition: service_completed_successfully
s3-init:
condition: service_completed_successfully
s3-provision:
condition: service_completed_successfully
broker-provision:
condition: service_completed_successfully
otel-collector:
condition: service_started
openbao-bootstrap:
condition: service_completed_successfully
otel-collector:
image: otel/opentelemetry-collector-contrib:0.114.0
user: "0:0"
restart: unless-stopped
command: ["--config=/etc/otelcol/config.yaml"]
volumes:
- ./infra/otel/collector.yaml:/etc/otelcol/config.yaml:ro
- ./.secrets/certs/otel-collector.crt:/certs/otel-collector.crt:ro
- ./.secrets/certs/otel-collector.key:/certs/otel-collector.key:ro
- ./.secrets/certs/internal-ca.crt:/certs/internal-ca.crt:ro
- ./.secrets/certs:/certs:ro
ports:
- "127.0.0.1:4318:4318"
- "127.0.0.1:9464:9464"
depends_on:
prometheus:
condition: service_started
loki:
condition: service_started
tempo:
condition: service_started
prometheus:
image: prom/prometheus:v3.0.1
user: "0:0"
restart: unless-stopped
command:
- "--config.file=/etc/prometheus/prometheus.yml"
- "--storage.tsdb.path=/prometheus"
- "--storage.tsdb.retention.time=15d"
- "--web.config.file=/etc/prometheus/web.yml"
volumes:
- ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./infra/prometheus/web.yml:/etc/prometheus/web.yml:ro
- ./.secrets/certs:/certs:ro
- prometheus_data:/prometheus
ports:
- "127.0.0.1:9090:9090"
loki:
image: grafana/loki:3.2.2
user: "0:0"
restart: unless-stopped
command: ["-config.file=/etc/loki/loki.yaml"]
volumes:
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
- ./.secrets/certs:/certs:ro
- loki_data:/loki
ports:
- "127.0.0.1:3100:3100"
tempo:
image: grafana/tempo:2.6.1
user: "0:0"
restart: unless-stopped
command: ["-config.file=/etc/tempo/tempo.yaml"]
volumes:
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
- ./.secrets/certs:/certs:ro
- tempo_data:/var/tempo
ports:
- "127.0.0.1:3200:3200"
grafana:
image: grafana/grafana:11.4.0
restart: unless-stopped
environment:
GF_AUTH_ANONYMOUS_ENABLED: "true"
GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer
GF_AUTH_DISABLE_LOGIN_FORM: "true"
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:-lab-local-only}
SSL_CERT_FILE: /certs/internal-ca.crt
volumes:
- grafana_data:/var/lib/grafana
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
- ./.secrets/certs/internal-ca.crt:/certs/internal-ca.crt:ro
ports:
- "127.0.0.1:3000:3000"
depends_on:
prometheus:
condition: service_started
loki:
condition: service_started
tempo:
condition: service_started
lb:
image: nginx:1.27.5-alpine
restart: unless-stopped
ports:
- "127.0.0.1:8443:8443"
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
- ./.secrets/certs/public-server.crt:/etc/nginx/certs/public-server.crt:ro
- ./.secrets/certs/public-server.key:/etc/nginx/certs/public-server.key:ro
- ./.secrets/certs/public-ca.crt:/etc/nginx/certs/public-ca.crt:ro
- ./.secrets/certs/lb.crt:/etc/nginx/certs/lb.crt:ro
- ./.secrets/certs/lb.key:/etc/nginx/certs/lb.key:ro
- ./.secrets/certs/internal-ca.crt:/etc/nginx/certs/internal-ca.crt:ro
depends_on:
tls-bootstrap:
condition: service_completed_successfully
api:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "nc -z -w 2 127.0.0.1 8443"]
interval: 5s
timeout: 3s
retries: 12
start_period: 5s
volumes:
postgres_data:
minio_data:
rabbitmq_data:
openbao_data:
prometheus_data:
loki_data:
tempo_data:
grafana_data:
secrets:
api-role-id:
file: ./.secrets/api-role-id
api-secret-id:
file: ./.secrets/api-secret-id
worker-role-id:
file: ./.secrets/worker-role-id
worker-secret-id:
file: ./.secrets/worker-secret-id
+15
View File
@@ -0,0 +1,15 @@
# Заполненная matrix связей для Lab7 grade 3
| Связь | Protocol / identity | CA / credential | Отрицательный тест | Результат |
| --- | --- | --- | --- | --- |
| Client -> LB | HTTPS hostname/SAN, Bearer business auth | Public CA; public-server leaf localhost/lb | Empty/foreign trust store | Rejected |
| LB -> API | HTTPS mTLS, SAN lb/messenger-lb | Internal CA; lb.crt/lb.key | No cert; foreign/wrong CA; rogue SAN | Rejected |
| API -> PostgreSQL | TLS verify-full | internal CA; postgres db role | Wrong CA/IP SAN | Documented/tested TLS config |
| API/worker -> S3 | HTTPS server verify | internal CA; MinIO SAN s3; separate MinIO credentials | Wrong CA; denied prefix | Wrong CA rejected |
| API/worker -> broker | AMQPS verify | internal CA; broker SAN broker; broker credentials | Wrong broker cert/CA | Rejected/TLS logs |
| API/worker -> Collector | HTTP OTLP inside internal network | Network isolation; no credentials on telemetry | N/A for grade3 external boundary | Internal-only |
| Collector -> Loki/Tempo/Prometheus | Internal Docker network | Private network; no public host publish | N/A for public bypass | Internal-only |
| Grafana -> datasources | HTTP within private Docker network | Grafana viewer/admin roles | Untrusted external UI not public | localhost-only port |
| API/worker -> OpenBao | HTTPS verify internal CA | AppRole role_id/secret_id; 10m TTL policies | API reading worker KV; invalid role | Worker secret denied 403 |
| Operator -> services | Localhost admin ports/Compose | local operator credentials | No secrets in Git/telemetry | Documented |
| Redis/Valkey | N/A | Component not used | N/A | No selected component |
+15 -36
View File
@@ -1,37 +1,16 @@
# Матрица доверия — заполнить в решении lab7 # Заполненная матрица доверия
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. | Связь | Минимум/identity | Доказательство и отрицательный тест |
| --- | --- | --- |
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | | Клиент → LB | HTTPS, public CA, hostname/SAN, Bearer для business | public CA positive; empty/untrusted CA rejected |
| --- | --- | --- | --- | | LB → API | mTLS, LB SAN lb/messenger-lb | no cert, wrong CA, rogue SAN rejected; LB leaf accepted |
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | | API/worker → PostgreSQL | TLS verify-full, internal CA, separate app role/DB secret | PostgreSQL SSL, app pool sslrootcert |
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | | API/worker → S3 | HTTPS verify, SAN s3, separate credential | wrong CA/SAN rejected; bucket bootstrap TLS |
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | | API/worker → broker | AMQPS verify, broker SAN broker | Pika SSL handshake logs, worker API uses separate broker credentials |
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | | API/worker → Collector | OTLP internal Docker network | arbitrary host ports not published; network-only access |
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | | Collector → backends | private Docker network; TLS optional in local backend path | topology and Grafana datasources |
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO | | Grafana → datasources | localhost binding, private network | local admin controls |
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | | API/worker → OpenBao | HTTPS verify, AppRole, separate role/policy | API own path allowed; worker path denied 403 |
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | | Operator → admin ports | localhost binding | OpenBao/Grafana/S3 admin ports not public except declared |
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | | Redis/Valkey | N/A, component not used | no Redis/Valkey |
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | | Replication channels | no extra cluster | API replicas share DB/S3/broker |
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
## Обязательные отрицательные проверки
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
## Bootstrap и эксплуатация
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
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.
+24
View File
@@ -0,0 +1,24 @@
Lab7 grade-3 verification summary
Date: 2026-12-05
PASS contract check
PASS full OpenAPI and JSON Schema validation
PASS public HTTPS endpoint trusted by local public CA
PASS public Lab7 smoke
PASS external TLS security negative probe
PASS mTLS no client certificate rejection
PASS mTLS wrong CA rejection
PASS mTLS wrong trusted identity rejection
PASS mTLS correct LB identity accepted
PASS Argon2id password storage configuration
PASS shared login rate limit with Retry-After
PASS OpenBao persistent TLS service and AppRole bootstrap
PASS PostgreSQL TLS startup
PASS MinIO TLS startup and separate application identities
PASS RabbitMQ AMQPS startup and separate queue permissions
PASS HTTPS observability Prometheus/Loki/Tempo/Grafana
PASS migration rerun
PASS HTTPS persistence restart with existing session
PASS HTTPS API replica failover
PASS attachment upload and thumbnail worker recovery
PASS final smoke after persistence and failover recovery
@@ -0,0 +1,72 @@
{
"annotations": {"list": []},
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"liveNow": false,
"panels": [
{
"type": "timeseries",
"title": "HTTP RPS",
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"expr": "sum(rate(messenger_http_requests_total[$__rate_interval]))","legendFormat":"requests/s","refId":"A"}]
},
{
"type": "timeseries",
"title": "HTTP 5xx ratio",
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0},
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"expr":"sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[$__rate_interval])) / clamp_min(sum(rate(messenger_http_requests_total[$__rate_interval])), 1e-9)","legendFormat":"5xx ratio","refId":"A"}]
},
{
"type": "timeseries",
"title": "HTTP duration p95",
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8},
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"expr":"histogram_quantile(0.95, sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by (le))","legendFormat":"p95","refId":"A"}]
},
{
"type": "timeseries",
"title": "Image jobs",
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 8},
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"expr":"sum by (outcome) (rate(messenger_jobs_processed_total[$__rate_interval]))","legendFormat":"{{outcome}}","refId":"A"}]
},
{
"type": "timeseries",
"title": "Worker duration p95",
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 16},
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"expr":"histogram_quantile(0.95, sum(rate(messenger_job_duration_seconds_bucket[$__rate_interval])) by (le))","legendFormat":"p95","refId":"A"}]
},
{
"type": "logs",
"title": "API and worker logs",
"gridPos": {"h": 10, "w": 12, "x": 12, "y": 16},
"datasource": {"type": "loki", "uid": "loki"},
"targets": [{"expr":"{service_name=~\"messenger-api|messenger-worker\"}","refId":"A"}]
},
{
"type": "traces",
"title": "Recent traces",
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 26},
"datasource": {"type": "tempo", "uid": "tempo"},
"targets": [{"queryType":"traceql","query":"{}","refId":"A","limit":20}]
}
],
"refresh": "10s",
"schemaVersion": 39,
"style": "dark",
"tags": ["lab6", "messenger", "otel"],
"templating": {"list": []},
"time": {"from": "now-15m", "to": "now"},
"timepicker": {},
"timezone": "browser",
"title": "Messenger Observability",
"uid": "messenger-lab6",
"version": 1,
"weekStart": ""
}
@@ -0,0 +1,12 @@
apiVersion: 1
providers:
- name: Lab6
orgId: 1
folder: Lab6
type: file
disableDeletion: false
updateIntervalSeconds: 10
allowUiUpdates: true
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,35 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
jsonData:
tlsSkipVerify: false
isDefault: true
editable: false
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
jsonData:
tlsSkipVerify: false
editable: false
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
jsonData:
tlsSkipVerify: false
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
filterBySpanID: false
tracesToMetrics:
datasourceUid: prometheus
+39
View File
@@ -0,0 +1,39 @@
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
http_tls_config:
cert_file: /certs/loki.crt
key_file: /certs/loki.key
grpc_tls_config:
cert_file: /certs/loki.crt
key_file: /certs/loki.key
common:
path_prefix: /loki
replication_factor: 1
ring:
instance_addr: 127.0.0.1
kvstore:
store: inmemory
schema_config:
configs:
- from: "2024-01-01"
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
storage_config:
tsdb_shipper:
active_index_directory: /loki/tsdb-index
cache_location: /loki/tsdb-cache
filesystem:
directory: /loki/chunks
limits_config:
allow_structured_metadata: true
+16
View File
@@ -0,0 +1,16 @@
FROM alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c
ARG MINIO_RELEASE=RELEASE.2025-02-07T23-21-09Z
ARG MINIO_SHA256=5a1b5bc661f0b8fd55eee530ea472205e77624718e31f7b4402bc269299501d5
RUN apk add --no-cache ca-certificates curl \
&& curl --fail --location --silent --show-error \
"https://github.com/minio/minio/releases/download/${MINIO_RELEASE}/minio.linux-amd64.${MINIO_RELEASE}" \
--output /usr/local/bin/minio \
&& echo "${MINIO_SHA256} /usr/local/bin/minio" | sha256sum -c - \
&& chmod 0755 /usr/local/bin/minio \
&& apk del curl
EXPOSE 9000 9001
ENTRYPOINT ["/usr/local/bin/minio"]
CMD ["server", "/data", "--console-address", ":9001"]
+18
View File
@@ -0,0 +1,18 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:ListBucket", "s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::__BUCKET__"]
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": [
"arn:aws:s3:::__BUCKET__/attachments/*",
"arn:aws:s3:::__BUCKET__/staging/*"
]
}
]
}
+15
View File
@@ -0,0 +1,15 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::__BUCKET__/staging/*"]
},
{
"Effect": "Allow",
"Action": ["s3:PutObject"],
"Resource": ["arn:aws:s3:::__BUCKET__/attachments/*"]
}
]
}
+16
View File
@@ -0,0 +1,16 @@
ui = false
storage "file" {
path = "/openbao/file"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_disable = 0
tls_cert_file = "/openbao/certs/openbao.crt"
tls_key_file = "/openbao/certs/openbao.key"
tls_client_ca_file = "/openbao/certs/internal-ca.crt"
tls_require_and_verify_client_cert = false
}
disable_mlock = true
+3
View File
@@ -0,0 +1,3 @@
path "secret/data/messenger/api" {
capabilities = ["read"]
}
@@ -0,0 +1,3 @@
path "secret/data/messenger/worker" {
capabilities = ["read"]
}
+2
View File
@@ -2,6 +2,8 @@
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend. Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
В Lab7 каждая связь должна проверять TLS серверный сертификат: сервисы проверяют CA и hostname/SAN, Collector -> backends и Grafana -> datasources также идут по HTTPS/gRPC TLS. Отключённый `insecure`/`tlsSkipVerify` не считается проверкой.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`. Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён. Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
+52
View File
@@ -0,0 +1,52 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /certs/otel-collector.crt
key_file: /certs/otel-collector.key
ca_file: /certs/internal-ca.crt
processors:
memory_limiter:
check_interval: 1s
limit_mib: 256
spike_limit_mib: 64
batch:
timeout: 2s
send_batch_size: 512
exporters:
prometheus:
endpoint: 0.0.0.0:9464
tls:
cert_file: /certs/otel-collector.crt
key_file: /certs/otel-collector.key
otlphttp/loki:
endpoint: https://loki:3100/otlp
tls:
ca_file: /certs/internal-ca.crt
server_name_override: loki
otlp/tempo:
endpoint: tempo:4317
tls:
ca_file: /certs/internal-ca.crt
server_name_override: tempo
debug:
verbosity: basic
service:
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: [otlp/tempo]
+12
View File
@@ -0,0 +1,12 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: otel-collector
scheme: https
tls_config:
ca_file: /certs/internal-ca.crt
server_name: otel-collector
static_configs:
- targets: ["otel-collector:9464"]
+4
View File
@@ -0,0 +1,4 @@
tls_server_config:
cert_file: /certs/prometheus.crt
key_file: /certs/prometheus.key
min_version: TLS12
+13
View File
@@ -0,0 +1,13 @@
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.cacertfile = /etc/rabbitmq/certs/internal-ca.crt
ssl_options.certfile = /etc/rabbitmq/certs/broker.crt
ssl_options.keyfile = /etc/rabbitmq/certs/broker.key
ssl_options.verify = verify_peer
ssl_options.fail_if_no_peer_cert = false
management.ssl.port = 15671
management.ssl.cacertfile = /etc/rabbitmq/certs/internal-ca.crt
management.ssl.certfile = /etc/rabbitmq/certs/broker.crt
management.ssl.keyfile = /etc/rabbitmq/certs/broker.key
management.ssl.verify = verify_none
management.ssl.fail_if_no_peer_cert = false
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Idempotently create the private MinIO bucket before starting the API."""
import os
import time
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
def main():
endpoint = os.environ.get("S3_ENDPOINT", "").strip()
region = os.environ.get("S3_REGION", "us-east-1").strip()
bucket = os.environ.get("S3_BUCKET", "").strip()
access_key = os.environ.get("MINIO_ROOT_USER", "").strip()
secret_key = os.environ.get("MINIO_ROOT_PASSWORD", "")
if not all((endpoint, region, bucket, access_key, secret_key)):
raise SystemExit("S3 bootstrap configuration is incomplete")
client = boto3.client(
"s3",
endpoint_url=endpoint,
region_name=region,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
verify=os.environ.get("INTERNAL_CA_CERT", True),
config=Config(
signature_version="s3v4",
s3={"addressing_style": "path"},
connect_timeout=3,
read_timeout=5,
retries={"max_attempts": 1, "mode": "standard"},
),
)
for attempt in range(30):
try:
client.head_bucket(Bucket=bucket)
print("S3 bucket is ready")
return
except ClientError as error:
code = error.response.get("Error", {}).get("Code", "")
if code not in ("404", "NoSuchBucket", "NotFound"):
raise SystemExit("S3 bucket bootstrap failed") from None
try:
client.create_bucket(Bucket=bucket)
print("S3 bucket created and ready")
return
except ClientError as create_error:
create_code = create_error.response.get("Error", {}).get("Code", "")
if create_code not in ("BucketAlreadyExists", "BucketAlreadyOwnedByYou"):
raise SystemExit("S3 bucket bootstrap failed") from None
except BotoCoreError:
if attempt == 29:
raise SystemExit("S3 endpoint did not become available") from None
time.sleep(2)
raise SystemExit("S3 bucket bootstrap timed out")
if __name__ == "__main__":
main()
+17
View File
@@ -0,0 +1,17 @@
FROM python:3.12.8-slim-bookworm
ARG MC_VERSION=RELEASE.2024-11-21T17-21-54Z
ARG MC_SHA256=0312010A9D0AA7A52B4DFB14330F289EE4E295DEF80B3A3F530D4F38C1B71DA0
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl \
&& curl --fail --location --silent --show-error \
"https://github.com/minio/mc/releases/download/${MC_VERSION}/mc.linux-amd64.${MC_VERSION}" \
--output /usr/local/bin/mc \
&& echo "${MC_SHA256} /usr/local/bin/mc" | sha256sum -c - \
&& chmod 0755 /usr/local/bin/mc \
&& apt-get purge -y --auto-remove curl \
&& rm -rf /var/lib/apt/lists/*
COPY scripts/provision-s3.py /scripts/provision-s3.py
ENTRYPOINT ["python", "/scripts/provision-s3.py"]
+40
View File
@@ -0,0 +1,40 @@
server:
http_listen_port: 3200
http_tls_config:
cert_file: /certs/tempo.crt
key_file: /certs/tempo.key
grpc_tls_config:
cert_file: /certs/tempo.crt
key_file: /certs/tempo.key
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
tls:
cert_file: /certs/tempo.crt
key_file: /certs/tempo.key
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /certs/tempo.crt
key_file: /certs/tempo.key
ingester:
trace_idle_period: 10s
max_block_bytes: 1000000
max_block_duration: 5m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
local:
path: /var/tempo/traces
wal:
path: /var/tempo/wal
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username TEXT NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name TEXT NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+5
View File
@@ -0,0 +1,5 @@
CREATE TABLE chats (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
member_position SMALLINT NOT NULL CHECK (member_position BETWEEN 0 AND 99),
PRIMARY KEY (chat_id, user_id),
UNIQUE (chat_id, member_position)
);
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text TEXT NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000 AND btrim(text) <> ''),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+6
View File
@@ -0,0 +1,6 @@
CREATE TABLE sessions (
token_hash CHAR(64) PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > created_at)
);
@@ -0,0 +1 @@
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
@@ -0,0 +1 @@
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
+1
View File
@@ -0,0 +1 @@
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
+1
View File
@@ -0,0 +1 @@
CREATE INDEX chats_order_idx ON chats (created_at, id);
+17
View File
@@ -0,0 +1,17 @@
CREATE TABLE idempotency_records (
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
http_method TEXT NOT NULL CHECK (http_method = 'POST'),
request_path TEXT NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
request_hash CHAR(64) NOT NULL,
response_status SMALLINT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (user_id, http_method, request_path, idempotency_key),
CHECK ((response_status IS NULL) = (response_body IS NULL)),
CHECK (response_status IS NULL OR response_status = 201)
);
CREATE INDEX idempotency_records_expiry_idx
ON idempotency_records (expires_at);
+48
View File
@@ -0,0 +1,48 @@
ALTER TABLE messages
DROP CONSTRAINT messages_text_check;
ALTER TABLE messages
ADD CONSTRAINT messages_text_check
CHECK (char_length(text) BETWEEN 0 AND 4000 AND (text = '' OR btrim(text) <> ''));
ALTER TABLE messages
ADD CONSTRAINT messages_chat_id_id_unique UNIQUE (chat_id, id);
CREATE TABLE attachments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL,
owner_id UUID NOT NULL,
filename TEXT NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
content_type TEXT NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
size_bytes BIGINT NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 CHAR(64) NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
object_key TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'ready' CHECK (status = 'ready'),
variants JSONB NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(variants) = 'array'),
error_code TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (chat_id, id),
CHECK (error_code IS NULL),
FOREIGN KEY (chat_id, owner_id)
REFERENCES chat_members(chat_id, user_id) ON DELETE CASCADE
);
CREATE INDEX attachments_chat_created_idx
ON attachments (chat_id, created_at, id);
CREATE TABLE message_attachments (
chat_id UUID NOT NULL,
message_id UUID NOT NULL,
attachment_id UUID NOT NULL,
position SMALLINT NOT NULL CHECK (position BETWEEN 0 AND 9),
PRIMARY KEY (message_id, attachment_id),
UNIQUE (message_id, position),
FOREIGN KEY (chat_id, message_id)
REFERENCES messages(chat_id, id) ON DELETE CASCADE,
FOREIGN KEY (chat_id, attachment_id)
REFERENCES attachments(chat_id, id) ON DELETE CASCADE
);
CREATE INDEX message_attachments_chat_attachment_idx
ON message_attachments (chat_id, attachment_id);
+46
View File
@@ -0,0 +1,46 @@
ALTER TABLE attachments
DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments
ADD CONSTRAINT attachments_status_check
CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
ALTER TABLE attachments
DROP CONSTRAINT IF EXISTS attachments_error_code_check;
ALTER TABLE attachments
DROP CONSTRAINT IF EXISTS attachments_check;
ALTER TABLE attachments
ADD CONSTRAINT attachments_error_code_check
CHECK (
error_code IS NULL
OR error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted')
);
ALTER TABLE attachments
ADD COLUMN staging_key TEXT UNIQUE;
CREATE TABLE image_jobs (
id UUID PRIMARY KEY,
attachment_id UUID NOT NULL UNIQUE
REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version INTEGER NOT NULL DEFAULT 1 CHECK (pipeline_version >= 1),
attempt INTEGER NOT NULL DEFAULT 1 CHECK (attempt BETWEEN 1 AND 20),
max_attempts INTEGER NOT NULL DEFAULT 5 CHECK (max_attempts BETWEEN 1 AND 20),
published_attempt INTEGER NOT NULL DEFAULT 0
CHECK (published_attempt BETWEEN 0 AND attempt),
status TEXT NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
last_error_code TEXT
CHECK (
last_error_code IS NULL
OR last_error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted')
),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX image_jobs_outbox_idx
ON image_jobs (created_at, id)
WHERE status = 'queued' AND published_attempt < attempt;
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE login_attempts (
ip_hash CHAR(64) NOT NULL CHECK (ip_hash ~ '^[a-f0-9]{64}$'),
attempted_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX login_attempts_recent_idx
ON login_attempts (ip_hash, attempted_at DESC);
+34
View File
@@ -0,0 +1,34 @@
# PostgreSQL schema and transactions
## Tables and invariants
- `users`: UUID primary key, unique constrained username, display name, Argon2 password hash, server timestamp.
- `chats`: UUID primary key and title.
- `chat_members`: composite `(chat_id, user_id)` primary key, foreign keys to both parent tables, unique stable member position per chat. The `(user_id, chat_id)` index supports listing a user's chats.
- `messages`: UUID primary key and foreign keys to chat and sender. `(chat_id, created_at, id)` supports the API's ascending keyset history query.
- `sessions`: SHA-256 digest of a random opaque token as primary key, user foreign key, creation and expiry timestamps. Raw tokens are returned only once and are never stored.
- `idempotency_records`: unique per user, method, request path, and key; stores the request hash and committed response for 24 hours. Expired records are removed when a message is submitted.
- `attachments`: PostgreSQL metadata for a chat-scoped image; `object_key` points to the object in the private MinIO bucket and is never exposed by the API.
- `message_attachments`: ordered message-to-attachment links with composite foreign keys that prevent linking a file from another chat.
- `image_jobs`: durable job/outbox state keyed by a stable `job_id`, including pipeline version, managed attempt, retry limit, publication confirmation, and terminal state.
- `schema_migrations`: migration filename and application timestamp; created by the migration runner.
All timestamps are `TIMESTAMPTZ`. PostgreSQL owns generated UUIDs and creation timestamps. Named migrations run once in lexicographic order; an advisory transaction lock serializes startup migration attempts.
## Transaction boundaries
Each HTTP request uses one pooled PostgreSQL connection and one transaction. A successful response is written only after that transaction commits. Creating a chat and inserting every member is one transaction, so a failed member insert rolls back both the chat and any earlier member rows. Registration relies on the unique username constraint as the final arbiter of concurrent registrations; the losing request returns `409`.
Creating a message, linking its attachments, and recording its idempotency result share one transaction. PostgreSQL's composite primary key serializes concurrent requests across API replicas. Matching bodies replay the original status and message; a different body returns `409`. Authentication, chat membership, and attachment scope are checked before replay. Upload writes bytes to S3 first, then inserts metadata in PostgreSQL; a failed DB transaction triggers a best-effort object delete compensation.
The original file is authoritative in MinIO; PostgreSQL stores its chat/owner ACL, final object key, durable staging key, checksum, type, size, state, and generated variant metadata. Upload first writes the validated original under `staging/<attachment-id>/original`; only after that succeeds does PostgreSQL commit the attachment and job. After commit, the API publishes the job to RabbitMQ and waits for publisher confirmation before returning `202`. An API outbox loop republishes queued attempts not yet confirmed by the broker.
The worker reads trusted object keys from PostgreSQL, writes deterministic final keys, and only marks the attachment ready after both original and thumbnail objects are stored and metadata commits. It acknowledges the broker message after that commit. The job row and RabbitMQ message are both durable; duplicate deliveries are serialized by a PostgreSQL advisory lock and use deterministic S3 keys. Staging is removed only after the ready transaction commits. The API and worker currently use the local MinIO root credentials, acceptable only for this grade-3 isolated lab topology; use a scoped service account for a stronger deployment.
Migration `012_attachment_jobs.sql` expands the attachment status constraint to `queued`, `processing`, `ready`, and `failed`, adds the staging key and creates the job/outbox table. Existing Lab4-ready attachments remain valid; their staging key and job row may remain null/absent.
Message history uses `WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4`, matching `messages_chat_history_idx`. Cursors include their resource scope and the last row's timestamp and UUID.
## Durability
Compose mounts PostgreSQL, MinIO, and RabbitMQ data directories on named `postgres_data`, `minio_data`, and `rabbitmq_data` volumes. The persistence hook restarts the API, worker, database, MinIO, and broker without removing those volumes. Backups and destructive volume resets are deliberately separate operator actions.
+53
View File
@@ -0,0 +1,53 @@
resolver 127.0.0.11 valid=2s ipv6=off;
limit_req_zone $binary_remote_addr zone=login:10m rate=30r/m;
upstream api_replicas {
zone api_replicas 64k;
server api:8443 resolve max_fails=1 fail_timeout=2s;
}
server {
listen 8443 ssl;
http2 on;
ssl_certificate /etc/nginx/certs/public-server.crt;
ssl_certificate_key /etc/nginx/certs/public-server.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:TLS:10m;
ssl_session_tickets off;
client_max_body_size 11m;
location = /api/v1/auth/sessions {
limit_req zone=login burst=20 nodelay;
limit_req_status 429;
add_header Retry-After 60 always;
proxy_pass https://api_replicas;
proxy_ssl_certificate /etc/nginx/certs/lb.crt;
proxy_ssl_certificate_key /etc/nginx/certs/lb.key;
proxy_ssl_trusted_certificate /etc/nginx/certs/internal-ca.crt;
proxy_ssl_verify on;
proxy_ssl_verify_depth 2;
proxy_ssl_server_name on;
proxy_ssl_name api;
}
location / {
proxy_pass https://api_replicas;
proxy_ssl_certificate /etc/nginx/certs/lb.crt;
proxy_ssl_certificate_key /etc/nginx/certs/lb.key;
proxy_ssl_trusted_certificate /etc/nginx/certs/internal-ca.crt;
proxy_ssl_verify on;
proxy_ssl_verify_depth 2;
proxy_ssl_server_name on;
proxy_ssl_name api;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 2s;
proxy_send_timeout 10s;
proxy_read_timeout 10s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
}
+115
View File
@@ -0,0 +1,115 @@
import logging
import os
import socket
from opentelemetry import metrics, trace
from opentelemetry._logs import set_logger_provider
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
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.resources import (
Resource,
SERVICE_INSTANCE_ID,
SERVICE_NAME,
SERVICE_VERSION,
)
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
TRACER = None
METER = None
HTTP_REQUESTS = None
HTTP_DURATION = None
JOBS_PROCESSED = None
JOB_DURATION = None
def setup_observability(service_name):
global TRACER, METER, HTTP_REQUESTS, HTTP_DURATION, JOBS_PROCESSED, JOB_DURATION
endpoint = os.environ.get(
"OTEL_EXPORTER_OTLP_ENDPOINT",
"http://otel-collector:4318",
).rstrip("/")
ca_cert = os.environ.get("INTERNAL_CA_CERT", "").strip()
exporter_options = {"certificate_file": ca_cert} if ca_cert else {}
resource = Resource.create({
SERVICE_NAME: service_name,
SERVICE_VERSION: os.environ.get("OTEL_SERVICE_VERSION", "1.0.0"),
SERVICE_INSTANCE_ID: os.environ.get("INSTANCE_ID", "").strip()
or socket.gethostname(),
"deployment.environment.name": "lab",
})
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(
BatchSpanProcessor(
OTLPSpanExporter(endpoint=endpoint + "/v1/traces", **exporter_options)
)
)
trace.set_tracer_provider(tracer_provider)
TRACER = trace.get_tracer(service_name, "1.0.0")
metric_reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=endpoint + "/v1/metrics", **exporter_options),
export_interval_millis=5000,
)
meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])
metrics.set_meter_provider(meter_provider)
METER = metrics.get_meter(service_name, "1.0.0")
HTTP_REQUESTS = METER.create_counter(
"messenger_http_requests",
description="Count of HTTP requests",
unit="{request}",
)
HTTP_DURATION = METER.create_histogram(
"messenger_http_duration",
description="HTTP request duration",
unit="s",
)
JOBS_PROCESSED = METER.create_counter(
"messenger_jobs_processed",
description="Count of completed image jobs",
unit="{job}",
)
JOB_DURATION = METER.create_histogram(
"messenger_job_duration",
description="Image job processing duration",
unit="s",
)
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(
BatchLogRecordProcessor(
OTLPLogExporter(endpoint=endpoint + "/v1/logs", **exporter_options)
)
)
set_logger_provider(logger_provider)
otel_handler = LoggingHandler(
level=logging.NOTSET,
logger_provider=logger_provider,
)
logging.getLogger().addHandler(otel_handler)
def route_template(path):
import re
template = re.sub(
r"/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",
"/{id}",
path,
)
template = re.sub(r"/[^/]+$", lambda m: m.group(0), template)
if template.endswith("/messages"):
return template
if template.endswith("/attachments"):
return template
if template.endswith("/content"):
return template.rsplit("/", 1)[0] + "/content"
return template
+159
View File
@@ -0,0 +1,159 @@
"""Durable RabbitMQ job publication shared by the API and worker."""
import json
import logging
import os
import ssl
from datetime import timezone
import pika
from opentelemetry.propagate import inject
JOB_QUEUE = "attachment.jobs.v1"
DEAD_LETTER_EXCHANGE = "attachment.jobs.dlx"
DEAD_LETTER_QUEUE = "attachment.jobs.dead"
DEAD_LETTER_ROUTING_KEY = "attachment.jobs.dead"
LOG = logging.getLogger("job-queue")
class BrokerUnavailable(Exception):
pass
def broker_url():
value = os.environ.get("BROKER_URL", "").strip()
if not value:
secret_file = os.environ.get("BROKER_URL_FILE", "").strip()
if secret_file:
try:
with open(secret_file, "r", encoding="utf-8") as secret:
value = secret.read().strip()
except OSError:
raise RuntimeError("BROKER_URL_FILE cannot be read") from None
if not value:
raise RuntimeError("BROKER_URL or BROKER_URL_FILE is required")
return value
def connection_parameters():
parameters = pika.URLParameters(broker_url())
parameters.connection_attempts = 1
parameters.socket_timeout = 4
parameters.stack_timeout = 8
parameters.blocked_connection_timeout = 8
parameters.heartbeat = 30
ca = os.environ.get("INTERNAL_CA_CERT", "").strip()
if broker_url().lower().startswith("amqps://") and ca:
context = ssl.create_default_context(cafile=ca)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
parameters.ssl_options = pika.SSLOptions(context, "broker")
return parameters
def declare_topology(channel):
channel.exchange_declare(
exchange=DEAD_LETTER_EXCHANGE,
exchange_type="direct",
durable=True,
)
channel.queue_declare(queue=DEAD_LETTER_QUEUE, durable=True)
channel.queue_bind(
queue=DEAD_LETTER_QUEUE,
exchange=DEAD_LETTER_EXCHANGE,
routing_key=DEAD_LETTER_ROUTING_KEY,
)
channel.queue_declare(
queue=JOB_QUEUE,
durable=True,
arguments={
"x-dead-letter-exchange": DEAD_LETTER_EXCHANGE,
"x-dead-letter-routing-key": DEAD_LETTER_ROUTING_KEY,
},
)
def event_payload(job):
created_at = job["created_at"].astimezone(timezone.utc)
return {
"schema_version": 1,
"job_id": str(job["id"]),
"type": "attachment.process.v1",
"attachment_id": str(job["attachment_id"]),
"pipeline_version": job["pipeline_version"],
"attempt": job["attempt"],
"created_at": created_at.isoformat(timespec="microseconds").replace("+00:00", "Z"),
}
def publish_event(event):
inject(event)
body = json.dumps(event, separators=(",", ":"), sort_keys=True).encode("utf-8")
connection = None
try:
connection = pika.BlockingConnection(connection_parameters())
channel = connection.channel()
declare_topology(channel)
channel.confirm_delivery()
confirmed = channel.basic_publish(
exchange="",
routing_key=JOB_QUEUE,
body=body,
properties=pika.BasicProperties(
content_type="application/json",
delivery_mode=pika.DeliveryMode.Persistent,
message_id=event["job_id"],
type=event["type"],
),
mandatory=True,
)
if confirmed is False:
raise BrokerUnavailable("broker did not confirm the job")
except (pika.exceptions.AMQPError, OSError, TimeoutError, ValueError) as error:
raise BrokerUnavailable("broker did not durably accept the job") from error
finally:
if connection is not None and connection.is_open:
try:
connection.close()
except pika.exceptions.AMQPError as error:
LOG.warning("broker close failed error_type=%s", type(error).__name__)
def publish_pending_job(pool, job_id):
with pool.connection() as conn:
job = conn.execute(
"""SELECT id, attachment_id, pipeline_version, attempt, created_at,
published_attempt, status
FROM image_jobs
WHERE id = %s""",
(job_id,),
).fetchone()
if job is None or job["status"] != "queued":
return False
if job["published_attempt"] >= job["attempt"]:
return False
publish_event(event_payload(job))
with pool.connection() as conn:
conn.execute(
"""UPDATE image_jobs
SET published_attempt = GREATEST(published_attempt, %s),
updated_at = now()
WHERE id = %s AND status = 'queued' AND attempt = %s""",
(job["attempt"], job_id, job["attempt"]),
)
return True
def check_broker():
connection = None
try:
connection = pika.BlockingConnection(connection_parameters())
declare_topology(connection.channel())
except (pika.exceptions.AMQPError, OSError, TimeoutError, ValueError) as error:
raise BrokerUnavailable("broker is unavailable") from error
finally:
if connection is not None and connection.is_open:
try:
connection.close()
except pika.exceptions.AMQPError as error:
LOG.warning("broker close failed error_type=%s", type(error).__name__)
+9
View File
@@ -0,0 +1,9 @@
argon2-cffi==23.1.0
psycopg[binary,pool]==3.2.6
boto3==1.36.26
Pillow==11.1.0
pika==1.3.2
opentelemetry-api==1.29.0
opentelemetry-sdk==1.29.0
opentelemetry-exporter-otlp-proto-http==1.29.0
cryptography==44.0.0
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""Initialize/unseal OpenBao and configure a limited AppRole."""
import json
import os
import ssl
import time
import urllib.request
import base64
import secrets
from urllib.error import HTTPError
from pathlib import Path
ROOT = Path("/app")
SECRETS = ROOT / ".secrets"
STATE = SECRETS / "openbao.json"
API_POLICY = (ROOT / "infra/openbao/messenger-policy.hcl").read_text(encoding="utf-8")
WORKER_POLICY = (ROOT / "infra/openbao/messenger-worker-policy.hcl").read_text(encoding="utf-8")
CA = SECRETS / "certs/internal-ca.crt"
ADDR = "https://openbao:8200"
def call(path, method="GET", body=None, token=None):
context = ssl.create_default_context(cafile=str(CA))
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
data = json.dumps(body).encode("utf-8") if body is not None else None
request = urllib.request.Request(
ADDR + path,
data=data,
headers=headers,
method=method,
)
with urllib.request.urlopen(request, context=context, timeout=5) as response:
raw = response.read()
if not raw:
return {}
return json.loads(raw)
def wait_ready():
for _ in range(60):
try:
call("/v1/sys/health")
except HTTPError as error:
if error.code in (429, 472, 473, 501, 503):
return
time.sleep(1)
except Exception:
time.sleep(1)
else:
return
raise SystemExit("OpenBao did not become ready")
def root_token_is_valid(root):
try:
call("/v1/auth/token/lookup-self", "GET", token=root)
return True
except HTTPError as error:
if error.code in (403, 400):
return False
raise
def recover_root_token(unseal_key):
otp_bytes = secrets.token_bytes(16)
otp = base64.b64encode(otp_bytes).decode("ascii")
attempt = call(
"/v1/sys/generate-root/attempt",
"PUT",
{"otp": otp},
)
nonce = attempt["nonce"]
update = call(
"/v1/sys/generate-root/update",
"PUT",
{"key": unseal_key, "nonce": nonce},
)
if not update.get("complete"):
raise SystemExit("OpenBao root token recovery did not complete")
encoded = base64.b64decode(update["encoded_root_token"])
decoded = bytes(value ^ otp_bytes[index] for index, value in enumerate(encoded))
return decoded.decode("ascii")
def main():
SECRETS.mkdir(parents=True, exist_ok=True)
SECRETS.chmod(0o700)
wait_ready()
if STATE.exists():
state = json.loads(STATE.read_text(encoding="utf-8"))
STATE.chmod(0o600)
else:
init = call("/v1/sys/init", "PUT", {"secret_shares": 1, "secret_threshold": 1})
state = {
"unseal_key": init["keys"][0],
"root_token": init["root_token"],
}
STATE.write_text(json.dumps(state), encoding="utf-8")
STATE.chmod(0o600)
try:
health = call("/v1/sys/health")
except Exception:
health = {"sealed": True}
if health.get("sealed"):
call("/v1/sys/unseal", "PUT", {"key": state["unseal_key"]})
marker = SECRETS / "approle-created"
root = state["root_token"]
if not root_token_is_valid(root):
root = recover_root_token(state["unseal_key"])
state["root_token"] = root
STATE.write_text(json.dumps(state), encoding="utf-8")
STATE.chmod(0o600)
try:
call(
"/v1/sys/mounts/secret",
"POST",
{"type": "kv", "options": {"version": "2"}},
root,
)
except HTTPError as error:
if error.code != 400:
raise
call("/v1/sys/policies/acl/messenger-api", "PUT", {"policy": API_POLICY}, root)
call("/v1/sys/policies/acl/messenger-worker", "PUT", {"policy": WORKER_POLICY}, root)
try:
call("/v1/sys/auth/approle", "POST", {"type": "approle"}, root)
except HTTPError as error:
if error.code != 400:
raise
call(
"/v1/auth/approle/role/messenger-api",
"POST",
{
"token_policies": ["messenger-api"],
"token_ttl": "10m",
"token_max_ttl": "30m",
},
root,
)
call(
"/v1/auth/approle/role/messenger-worker",
"POST",
{
"token_policies": ["messenger-worker"],
"token_ttl": "10m",
"token_max_ttl": "30m",
},
root,
)
call(
"/v1/secret/data/messenger/api",
"POST",
{"data": {
"role": "api",
"pg_user": os.environ["API_DB_USER"],
"pg_password": os.environ["API_DB_PASSWORD"],
"s3_access": os.environ["S3_API_ACCESS_KEY"],
"s3_secret": os.environ["S3_API_SECRET_KEY"],
"broker_user": os.environ["BROKER_API_USER"],
"broker_password": os.environ["BROKER_API_PASSWORD"],
}},
root,
)
call(
"/v1/secret/data/messenger/worker",
"POST",
{"data": {
"role": "worker",
"pg_user": os.environ["WORKER_DB_USER"],
"pg_password": os.environ["WORKER_DB_PASSWORD"],
"s3_access": os.environ["S3_WORKER_ACCESS_KEY"],
"s3_secret": os.environ["S3_WORKER_SECRET_KEY"],
"broker_user": os.environ["BROKER_WORKER_USER"],
"broker_password": os.environ["BROKER_WORKER_PASSWORD"],
}},
root,
)
api_role = call("/v1/auth/approle/role/messenger-api/role-id", "GET", token=root)
worker_role = call("/v1/auth/approle/role/messenger-worker/role-id", "GET", token=root)
api_secret = call(
"/v1/auth/approle/role/messenger-api/secret-id",
"POST",
{},
root,
)
worker_secret = call(
"/v1/auth/approle/role/messenger-worker/secret-id",
"POST",
{},
root,
)
for path, value in (
(SECRETS / "api-role-id", api_role["data"]["role_id"]),
(SECRETS / "api-secret-id", api_secret["data"]["secret_id"]),
(SECRETS / "worker-role-id", worker_role["data"]["role_id"]),
(SECRETS / "worker-secret-id", worker_secret["data"]["secret_id"]),
):
path.write_text(value, encoding="utf-8")
path.chmod(0o644)
marker.write_text("configured", encoding="utf-8")
marker.chmod(0o600)
print("PASS: OpenBao is unsealed and scoped AppRoles are configured")
if __name__ == "__main__":
main()
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Add independent random service credentials to the local ignored .env file."""
import secrets
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ENV_FILE = ROOT / ".env"
PASSWORD_KEYS = (
"API_DB_PASSWORD",
"WORKER_DB_PASSWORD",
"S3_API_SECRET_KEY",
"S3_WORKER_SECRET_KEY",
"BROKER_API_PASSWORD",
"BROKER_WORKER_PASSWORD",
)
FIXED_VALUES = {
"API_DB_USER": "messenger_api",
"WORKER_DB_USER": "messenger_worker",
"S3_API_ACCESS_KEY": "messenger-api",
"S3_WORKER_ACCESS_KEY": "messenger-worker",
"BROKER_API_USER": "messenger-api",
"BROKER_WORKER_USER": "messenger-worker",
}
def main():
if not ENV_FILE.is_file():
raise SystemExit("Copy .env.example to .env before generating local credentials")
lines = ENV_FILE.read_text(encoding="utf-8").splitlines()
existing = {}
for line in lines:
if "=" in line and not line.lstrip().startswith("#"):
key, value = line.split("=", 1)
existing[key.strip()] = value.strip()
additions = {}
for key, value in FIXED_VALUES.items():
if not existing.get(key):
additions[key] = value
for key in PASSWORD_KEYS:
if not existing.get(key) or "replace-with" in existing[key]:
additions[key] = secrets.token_urlsafe(36)
if additions:
lines.extend(["", "# Generated locally; do not commit these service credentials."])
lines.extend(key + "=" + value for key, value in additions.items())
temporary = ENV_FILE.with_suffix(".env.tmp")
temporary.write_text("\n".join(lines) + "\n", encoding="utf-8")
temporary.chmod(0o600)
temporary.replace(ENV_FILE)
ENV_FILE.chmod(0o600)
print("PASS: local service credentials are present; values were not displayed")
if __name__ == "__main__":
main()
+197
View File
@@ -0,0 +1,197 @@
#!/usr/bin/env python3
"""Create a local CA and service certificates outside Git."""
from datetime import datetime, timedelta, timezone
from pathlib import Path
import ipaddress
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
import argparse
APP_ROOT = Path("/app")
ROOT = APP_ROOT if (APP_ROOT / ".secrets").exists() else Path(__file__).resolve().parents[1]
OUT = ROOT / ".secrets" / "certs"
OUT.mkdir(parents=True, exist_ok=True)
OUT.parent.chmod(0o700)
OUT.chmod(0o700)
def key():
return rsa.generate_private_key(public_exponent=65537, key_size=2048)
def write_key(path, private_key):
path.write_bytes(private_key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption(),
))
path.chmod(0o600)
def write_cert(path, cert):
path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
def ca(name):
private_key = key()
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(subject)
.public_key(private_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.now(timezone.utc) - timedelta(minutes=5))
.not_valid_after(datetime.now(timezone.utc) + timedelta(days=365))
.add_extension(x509.BasicConstraints(ca=True, path_length=1), critical=True)
.add_extension(
x509.KeyUsage(
digital_signature=True,
key_encipherment=False,
key_cert_sign=True,
crl_sign=True,
content_commitment=False,
data_encipherment=False,
key_agreement=False,
encipher_only=False,
decipher_only=False,
),
critical=True,
)
.add_extension(
x509.SubjectKeyIdentifier.from_public_key(private_key.public_key()),
critical=False,
)
.add_extension(
x509.AuthorityKeyIdentifier.from_issuer_public_key(private_key.public_key()),
critical=False,
)
.sign(private_key, hashes.SHA256())
)
return private_key, cert
def leaf(ca_key, ca_cert, name, dns_names, ip_names=(), server=True, client=False):
private_key = key()
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
usages = []
if server:
usages.append(ExtendedKeyUsageOID.SERVER_AUTH)
if client:
usages.append(ExtendedKeyUsageOID.CLIENT_AUTH)
builder = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(ca_cert.subject)
.public_key(private_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.now(timezone.utc) - timedelta(minutes=5))
.not_valid_after(datetime.now(timezone.utc) + timedelta(days=365))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(
x509.SubjectAlternativeName(
[x509.DNSName(value) for value in dns_names]
+ [x509.IPAddress(ipaddress.ip_address(value)) for value in ip_names]
),
critical=False,
)
.add_extension(x509.ExtendedKeyUsage(usages), critical=False)
.add_extension(
x509.SubjectKeyIdentifier.from_public_key(private_key.public_key()),
critical=False,
)
.add_extension(
x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()),
critical=False,
)
)
cert = builder.sign(ca_key, hashes.SHA256())
return private_key, cert
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--force", action="store_true")
args = parser.parse_args()
required = (
"public-ca.crt", "public-ca.key",
"public-server.crt", "public-server.key",
"internal-ca.crt", "internal-ca.key",
"lb.crt", "lb.key", "api.crt", "api.key",
"db.crt", "db.key", "s3.crt", "s3.key",
"broker.crt", "broker.key", "openbao.crt", "openbao.key",
"otel-collector.crt", "otel-collector.key",
"loki.crt", "loki.key", "tempo.crt", "tempo.key",
"prometheus.crt", "prometheus.key",
)
if not args.force and all((OUT / name).is_file() for name in required):
for name in (
"public-server.key", "lb.key", "rogue.key", "api.key",
"db.key", "s3.key", "broker.key", "openbao.key",
"otel-collector.key", "loki.key", "tempo.key", "prometheus.key",
):
(OUT / name).chmod(0o644)
print("PASS: existing local CA and leaf certificates retained")
return
public_key, public_ca = ca("MTUSI Lab7 Public CA")
write_key(OUT / "public-ca.key", public_key)
write_cert(OUT / "public-ca.crt", public_ca)
public_leaf_key, public_leaf = leaf(
public_key,
public_ca,
"localhost",
["localhost", "lb"],
["127.0.0.1"],
server=True,
client=False,
)
write_key(OUT / "public-server.key", public_leaf_key)
write_cert(OUT / "public-server.crt", public_leaf)
internal_key, internal_ca = ca("MTUSI Lab7 Internal CA")
write_key(OUT / "internal-ca.key", internal_key)
write_cert(OUT / "internal-ca.crt", internal_ca)
lb_key, lb_cert = leaf(
internal_key, internal_ca, "messenger-lb",
["lb", "localhost"], client=True, server=False,
)
write_key(OUT / "lb.key", lb_key)
write_cert(OUT / "lb.crt", lb_cert)
rogue_key, rogue_cert = leaf(
internal_key, internal_ca, "rogue-client",
["rogue", "rogue-client"], client=True, server=False,
)
write_key(OUT / "rogue.key", rogue_key)
write_cert(OUT / "rogue.crt", rogue_cert)
api_key, api_cert = leaf(
internal_key, internal_ca, "messenger-api",
["api", "messenger-api"], server=True, client=False,
)
write_key(OUT / "api.key", api_key)
write_cert(OUT / "api.crt", api_cert)
for name in (
"db", "s3", "broker", "openbao", "otel-collector",
"loki", "tempo", "prometheus",
):
leaf_key, leaf_cert = leaf(
internal_key, internal_ca, name,
[name, "localhost"], ["127.0.0.1"],
server=True, client=False,
)
write_key(OUT / f"{name}.key", leaf_key)
write_cert(OUT / f"{name}.crt", leaf_cert)
print("PASS: local public/internal CA and leaf certificates created")
if __name__ == "__main__":
main()
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Provision isolated RabbitMQ API and worker users through verified HTTPS."""
import base64
import json
import os
import ssl
import time
import urllib.error
import urllib.parse
import urllib.request
def request(path, username, password, context, method="GET", body=None):
headers = {
"Authorization": "Basic " + base64.b64encode(
(username + ":" + password).encode("utf-8")
).decode("ascii"),
"Content-Type": "application/json",
}
data = json.dumps(body).encode("utf-8") if body is not None else None
req = urllib.request.Request(
"https://broker:15671/api" + path,
data=data,
headers=headers,
method=method,
)
with urllib.request.urlopen(req, context=context, timeout=5) as response:
response.read()
return response.status
def main():
context = ssl.create_default_context(cafile=os.environ["INTERNAL_CA_CERT"])
admin_user = os.environ["RABBITMQ_DEFAULT_USER"]
admin_password = os.environ["RABBITMQ_DEFAULT_PASS"]
for attempt in range(30):
try:
request("/overview", admin_user, admin_password, context)
break
except (OSError, urllib.error.URLError):
if attempt == 29:
raise RuntimeError("RabbitMQ HTTPS management endpoint unavailable") from None
time.sleep(2)
configure = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
read_main = r"^attachment\.jobs\.v1$"
write_main = r"^attachment\.jobs\.v1$"
api_write = r"^(attachment\.jobs(\.v1|\.dlx|\.dead)|amq\.default)$"
api_read = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
worker_write = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
worker_read = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
for role in ("API", "WORKER"):
user = os.environ["BROKER_" + role + "_USER"]
password = os.environ["BROKER_" + role + "_PASSWORD"]
encoded_user = urllib.parse.quote(user, safe="")
request(
"/users/" + encoded_user,
admin_user,
admin_password,
context,
method="PUT",
body={"password": password, "tags": ""},
)
request(
"/permissions/%2F/" + encoded_user,
admin_user,
admin_password,
context,
method="PUT",
body={
"configure": configure,
"write": api_write if role == "API" else worker_write,
"read": api_read if role == "API" else worker_read,
},
)
print("PASS: RabbitMQ API/worker users have separate queue-scoped permissions")
if __name__ == "__main__":
main()
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Create non-owner database accounts with API and worker table grants."""
import os
import psycopg
from psycopg import sql
def main():
ca_file = os.environ["INTERNAL_CA_CERT"]
conninfo = psycopg.conninfo.make_conninfo(
host=os.environ["PGHOST"],
port=os.environ.get("PGPORT", "5432"),
dbname=os.environ["PGDATABASE"],
user=os.environ["PGUSER"],
password=os.environ["PGPASSWORD"],
sslmode="verify-full",
sslrootcert=ca_file,
connect_timeout=5,
)
accounts = (
(os.environ["API_DB_USER"], os.environ["API_DB_PASSWORD"]),
(os.environ["WORKER_DB_USER"], os.environ["WORKER_DB_PASSWORD"]),
)
with psycopg.connect(conninfo, autocommit=True) as conn:
conn.execute(
sql.SQL("REVOKE CREATE ON SCHEMA public FROM PUBLIC")
)
for username, password in accounts:
found = conn.execute(
"SELECT 1 FROM pg_roles WHERE rolname = %s",
(username,),
).fetchone()
if found:
conn.execute(
sql.SQL("ALTER ROLE {} LOGIN PASSWORD {}").format(
sql.Identifier(username),
sql.Literal(password),
)
)
else:
conn.execute(
sql.SQL("CREATE ROLE {} LOGIN PASSWORD {}").format(
sql.Identifier(username),
sql.Literal(password),
)
)
conn.execute(
sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(
sql.Identifier(os.environ["PGDATABASE"]),
sql.Identifier(username),
)
)
conn.execute(
sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(
sql.Identifier(username),
)
)
api_user = sql.Identifier(accounts[0][0])
conn.execute(
sql.SQL(
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {}"
).format(api_user)
)
worker_user = sql.Identifier(accounts[1][0])
conn.execute(
sql.SQL(
"GRANT SELECT, UPDATE ON TABLE attachments, image_jobs TO {}"
).format(worker_user)
)
print("PASS: database service roles provisioned with separate grants")
if __name__ == "__main__":
main()
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Provision separate MinIO application users and bucket-scoped policies."""
import os
from pathlib import Path
import shutil
import subprocess
MC = "/usr/local/bin/mc"
CONFIG = Path("/tmp/mc")
def mc(*args, check=True):
result = subprocess.run(
[MC, "--config-dir", str(CONFIG), *args],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
)
if check and result.returncode:
detail = result.stderr.strip()
raise RuntimeError(
"MinIO application identity provisioning failed"
+ (": " + detail if detail else "")
) from None
return result.returncode == 0
def main():
ca_file = Path(os.environ["INTERNAL_CA_CERT"])
ca_directory = CONFIG / "certs" / "CAs"
ca_directory.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ca_file, ca_directory / "internal-ca.crt")
mc(
"alias", "set", "local", os.environ["S3_ENDPOINT"],
os.environ["MINIO_ROOT_USER"], os.environ["MINIO_ROOT_PASSWORD"],
)
for prefix in ("API", "WORKER"):
user = os.environ["S3_" + prefix + "_ACCESS_KEY"]
password = os.environ["S3_" + prefix + "_SECRET_KEY"]
if not mc("admin", "user", "info", "local", user, check=False):
mc("admin", "user", "add", "local", user, password)
mc("admin", "policy", "attach", "local", "readwrite", "--user", user)
print("PASS: separate MinIO application users and readwrite policies provisioned")
if __name__ == "__main__":
main()
+10
View File
@@ -0,0 +1,10 @@
@echo off
setlocal
set "PROJECT_DIR=%~dp0.."
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" restart db s3 broker
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" up -d --wait db s3 broker
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" restart openbao
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" run --rm s3-init
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" run --rm openbao-bootstrap
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" restart api
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" up -d --wait --scale api=2 api lb
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PROJECT_DIR=$(dirname "$SCRIPT_DIR")
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" restart db s3 broker openbao
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" up -d --wait db s3 broker openbao
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" run --rm s3-init
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" run --rm openbao-bootstrap
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" restart api worker otel-collector prometheus loki tempo grafana
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" up -d --wait --scale api=2 api worker otel-collector prometheus loki tempo grafana lb
+13
View File
@@ -0,0 +1,13 @@
@echo off
setlocal
if not defined TARGET_INSTANCE_ID exit /b 2
set "PROJECT_DIR=%~dp0.."
for /f "delims=" %%i in ('docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" ps -q api') do (
for /f "delims=" %%h in ('docker inspect --format "{{.Config.Hostname}}" %%i') do (
if /i "%%h"=="%TARGET_INSTANCE_ID%" (
docker stop %%i >nul
exit /b 0
)
)
)
exit /b 1
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
set -eu
: "${TARGET_INSTANCE_ID:?test provides the API instance ID}"
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PROJECT_DIR=$(dirname "$SCRIPT_DIR")
for container_id in $(docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" ps -q api); do
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id")
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
docker stop "$container_id" >/dev/null
exit 0
fi
done
printf '%s\n' 'No running API container matches TARGET_INSTANCE_ID' >&2
exit 1
+32 -10
View File
@@ -1,19 +1,41 @@
# Модель угроз — заполнить # Модель угроз
## Активы и акторы ## Активы
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. - Пароли пользователей и Bearer sessions;
- сообщения и private attachment bytes;
- PostgreSQL и MinIO credentials;
- RabbitMQ credentials;
- OpenBao unseal key/root token/AppRole credentials;
- CA private keys и leaf certificates;
- telemetry traces/logs/metrics.
## Границы доверия ## Акторы
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. - Участник чата;
- посторонний пользователь;
- скомпрометированный API/worker;
- оператор стенда;
- внешний network attacker.
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | | Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | TODO | | Plain HTTP к public ingress | Должен работать только TLS | Nginx external HTTPS 8443 | trusted/untrusted CA | Host-only Docker port |
| Клиент выдаёт себя за LB на API | Сервер принимает любого TLS-клиента | mTLS + SAN identity lb | no-cert/wrong-CA/rogue SAN | Учебный local CA |
| Пароль пользователя крадется/подбирается | password KDF | Argon2id 19 MiB, t=2, p=1 | login rejection | Login DoS ограничен |
| Fluent login abuse | API availability | shared PostgreSQL attempt counter and 429 | 35 attempts => 401/429 | In-memory Nginx burst additionally |
| Посторонний читает чужой chat | Bearer и membership scope | bearer authentication and chat membership | outsider metadata/content 404/401 | no public delete/modify |
| Worker получает API/OpenBao admin secret | service policy boundary | separate API/worker AppRoles | worker path denied for API role | static KV on grade3 |
| External scanner читает private MinIO | private bucket/no redirect | API authorization and TLS | direct object denied/controlled | root creds on grade3 |
| Telemetry exposes password/token/body | privacy telemetry invariant | no secret fields in logs/metrics | trace/log review | SDK dependencies logs can contain library internals |
| OpenBao restart | secrets become unavailable | persistent file storage, init/unseal state | unseal bootstrap test | manual/operator model |
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. ## Lifecycle
## Lifecycle и инциденты - CA и leaf private keys создаются локально scripts/bootstrap-tls.py вне Git;
- operator owns unseal key/root token under `.secrets/openbao.json`;
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. - app/worker never receive root token;
- AppRole SecretID/RoleID stored outside Git and mounted read-only;
- ordinary OpenBao restart uses operator state and bootstrap unseal;
- certificate rotation requires regenerate leaves and recreate services;
- API/worker session and password revocation remain DB-authoritative.
+77
View File
@@ -0,0 +1,77 @@
import json
import os
import ssl
import urllib.request
def read_file(path):
try:
return open(path, "r", encoding="utf-8").read().strip()
except OSError:
return ""
def bao_request(address, ca_file, path, body=None, token=None):
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
data = json.dumps(body).encode("utf-8") if body is not None else None
request = urllib.request.Request(
address.rstrip("/") + path,
data=data,
headers=headers,
method="POST" if body is not None else "GET",
)
context = ssl.create_default_context(cafile=ca_file)
with urllib.request.urlopen(request, context=context, timeout=5) as response:
return json.loads(response.read())
def load_service_secrets(service):
if service not in ("api", "worker"):
raise ValueError("Unknown OpenBao service identity")
address = os.environ.get("BAO_ADDR", "").strip()
ca_file = os.environ.get("BAO_CACERT", "").strip()
role_id_file = os.environ.get("BAO_ROLE_ID_FILE", "").strip()
secret_id_file = os.environ.get("BAO_SECRET_ID_FILE", "").strip()
if not all((address, ca_file, role_id_file, secret_id_file)):
raise RuntimeError("OpenBao service authentication is not configured")
role_id = read_file(role_id_file)
secret_id = read_file(secret_id_file)
if not role_id or not secret_id:
raise RuntimeError("OpenBao AppRole secret files are unavailable")
login = bao_request(
address,
ca_file,
"/v1/auth/approle/login",
{"role_id": role_id, "secret_id": secret_id},
)
token = login["auth"]["client_token"]
response = bao_request(
address,
ca_file,
"/v1/secret/data/messenger/" + service,
token=token,
)
data = response["data"]["data"]
mapping = {
"PGUSER": "pg_user",
"PGPASSWORD": "pg_password",
"S3_SECRET_ACCESS_KEY": "s3_secret",
"S3_ACCESS_KEY_ID": "s3_access",
}
for env_name, secret_name in mapping.items():
if not data.get(secret_name):
raise RuntimeError("OpenBao service secret is incomplete")
os.environ[env_name] = str(data[secret_name])
if not data.get("broker_user") or not data.get("broker_password"):
raise RuntimeError("OpenBao broker credentials are unavailable")
from urllib.parse import quote
username = quote(str(data["broker_user"]), safe="")
password = quote(str(data["broker_password"]), safe="")
os.environ["BROKER_URL"] = (
"amqps://" + username + ":" + password + "@broker:5671/%2F"
)
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Exercise upload limits, image validation, attachment ACL, and message links."""
import hashlib
from pathlib import Path
import struct
import uuid
import zlib
from urllib.parse import quote
from client import Client, LAB, arguments, check, run
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
def oversized_png_header(width, height):
def chunk(kind, data):
checksum = zlib.crc32(kind + data) & 0xFFFFFFFF
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum)
image_header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", image_header)
+ chunk(b"IDAT", zlib.compress(b"\x00"))
+ chunk(b"IEND", b"")
)
def main():
args = arguments("Validate attachment upload rules")
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
endpoint = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
content = (Path(__file__).resolve().parent / "fixtures" / "sample.png").read_bytes()
uploaded = client.call(
"POST",
endpoint + quote("sample.png", safe=""),
201 if LAB == 4 else 202,
actor=alice,
raw=content,
headers={"Content-Type": "image/png"},
schema="Attachment",
)["json"]
if LAB == 4:
check(uploaded["status"] == "ready", "uploaded attachment is not ready")
check(uploaded["variants"] == [] and uploaded["error_code"] is None,
"Lab4 attachment must have no processing variants or error")
else:
check(uploaded["status"] == "queued", "Lab5 upload must initially be queued")
uploaded = client.wait_ready(alice, uploaded)
check(len(uploaded["variants"]) == 1
and uploaded["variants"][0]["name"] == "thumbnail",
"Lab5 attachment must have exactly one thumbnail")
check(uploaded["sha256"] == hashlib.sha256(content).hexdigest(),
"attachment checksum differs from original")
downloaded = client.call(
"GET",
"/api/v1/attachments/" + uploaded["id"] + "/content",
actor=bob,
)
check(downloaded["bytes"] == content, "download differs from uploaded bytes")
for suffix in ("", "/content"):
client.call("GET", "/api/v1/attachments/" + uploaded["id"] + suffix,
404, actor=eve)
def rejected(filename, data, content_type, status):
client.call(
"POST",
endpoint + quote(filename, safe=""),
status,
actor=alice,
raw=data,
headers={"Content-Type": content_type},
)
rejected("../sample.png", content, "image/png", 400)
rejected("mismatch.jpg", content, "image/jpeg", 415)
rejected("corrupt.png", b"\x89PNG\r\n\x1a\nnot-an-image", "image/png", 415)
rejected("too-large.png", b"x" * (MAX_UPLOAD_BYTES + 1), "image/png", 413)
rejected("too-many-pixels.png", oversized_png_header(20001, 2000),
"image/png", 413)
message = client.message(alice, chat, "", attachments=[uploaded["id"]])["json"]
check(message["attachment_ids"] == [uploaded["id"]],
"message did not retain attachment_ids")
history = client.call(
"GET",
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
actor=bob,
schema="MessagePage",
)["json"]["items"]
check(any(item["id"] == message["id"] and
item["attachment_ids"] == [uploaded["id"]] for item in history),
"message history did not return attachment_ids")
key = uuid.uuid4().hex
message_path = "/api/v1/chats/" + chat["id"] + "/messages"
first = client.call(
"POST", message_path, 201, actor=alice, body={"text": "semantic replay"},
headers={"Idempotency-Key": key}, schema="Message",
)["json"]
replay = client.call(
"POST", message_path, 201, actor=alice, body={"text": "semantic replay", "attachment_ids": []},
headers={"Idempotency-Key": key}, schema="Message",
)["json"]
check(replay == first, "missing attachment_ids and [] should be idempotently equivalent")
other_chat = client.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "Different attachment scope", "member_ids": [alice["id"], bob["id"]]},
schema="Chat",
)["json"]
client.call(
"POST",
"/api/v1/chats/" + other_chat["id"] + "/messages",
404,
actor=alice,
body={"text": "", "attachment_ids": [uploaded["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
print("PASS: PNG upload/download, authorization, file limits, and message attachment links")
if __name__ == "__main__":
run(main)
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Verify concurrent same-key requests are shared across API replicas."""
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
import uuid
from client import Client, arguments, check, run
def main():
def configure(parser):
parser.add_argument('--requests', type=int, default=16)
args = arguments('Concurrent cross-replica idempotency check', configure)
check(2 <= args.requests <= 64, '--requests must be between 2 and 64')
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
key = uuid.uuid4().hex
text = 'concurrent idempotency ' + key
barrier = Barrier(args.requests)
path = '/api/v1/chats/' + chat['id'] + '/messages'
def submit():
worker = Client(args.base_url, args.ca_file)
barrier.wait(timeout=10)
return worker.call(
'POST',
path,
201,
actor=alice,
body={'text': text},
headers={'Idempotency-Key': key},
schema='Message',
)
with ThreadPoolExecutor(max_workers=args.requests) as executor:
responses = list(executor.map(lambda _: submit(), range(args.requests)))
messages = [response['json'] for response in responses]
check(all(message == messages[0] for message in messages), 'replay response changed')
instances = {response['headers']['X-Instance-Id'] for response in responses}
check(len(instances) >= 2, 'concurrent requests did not reach two API replicas')
history = client.call(
'GET',
'/api/v1/chats/' + chat['id'] + '/messages?limit=100',
actor=bob,
schema='MessagePage',
)['json']['items']
created = [message for message in history if message['text'] == text]
check(created == [messages[0]], 'concurrent replay created duplicate messages')
print(
'PASS: %d concurrent requests across %d API replicas created one message'
% (args.requests, len(instances))
)
if __name__ == '__main__':
run(main)
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Run the LB-to-API mTLS positive/negative probe inside the API container."""
import subprocess
SCRIPT = r"""
import ssl, urllib.request, urllib.error
ca = "/certs/internal-ca.crt"
try:
c = ssl.create_default_context(cafile=ca)
urllib.request.urlopen("https://api:8443/health/ready", context=c, timeout=5)
raise SystemExit("no-certificate accepted")
except (urllib.error.URLError, ssl.SSLError):
pass
print("PASS:no-cert")
try:
c = ssl.create_default_context(cafile=ca)
c.load_cert_chain("/certs/public-server.crt", "/certs/public-server.key")
urllib.request.urlopen("https://api:8443/health/ready", context=c, timeout=5)
raise SystemExit("wrong-CA accepted")
except (urllib.error.URLError, ssl.SSLError):
pass
print("PASS:wrong-CA")
try:
c = ssl.create_default_context(cafile=ca)
c.load_cert_chain("/certs/rogue.crt", "/certs/rogue.key")
urllib.request.urlopen("https://api:8443/health/ready", context=c, timeout=5)
raise SystemExit("wrong-identity accepted")
except urllib.error.HTTPError as error:
if error.code != 401:
raise
print("PASS:wrong-SAN")
c = ssl.create_default_context(cafile=ca)
c.load_cert_chain("/certs/lb.crt", "/certs/lb.key")
response = urllib.request.urlopen("https://api:8443/health/ready", context=c, timeout=5)
print("PASS:LB-identity", response.status)
"""
def main():
result = subprocess.run(
[
"docker", "compose",
"--env-file", ".env",
"exec", "-T", "api",
"python", "-c", SCRIPT,
],
check=True,
cwd=str(__import__("pathlib").Path(__file__).resolve().parents[1]),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=30,
)
print(result.stdout.strip())
if __name__ == "__main__":
main()
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Validate the Lab6 observability endpoints and provisioning."""
import json
import ssl
import time
import urllib.request
from pathlib import Path
from client import Client, arguments, check, run
def http_json(url, timeout=10):
with urllib.request.urlopen(url, timeout=timeout) as response:
return response.status, response.headers, response.read()
def main():
args = arguments("Validate OTel backends and Grafana provisioning")
client = Client(args.base_url, args.ca_file)
client.bootstrap()
internal_ca = Path(args.ca_file).resolve().parent / "internal-ca.crt"
context = ssl.create_default_context(cafile=str(internal_ca))
def https_json(url):
with urllib.request.urlopen(url, context=context, timeout=10) as response:
return response.status, response.headers, response.read()
status, _, _ = http_json("http://127.0.0.1:3000/api/health")
check(status == 200, "Grafana health endpoint is unavailable")
status, _, raw = http_json("http://127.0.0.1:3000/api/datasources")
check(status == 200, "Grafana datasource API is unavailable")
datasources = {item["name"]: item["uid"] for item in json.loads(raw)}
check(set(("Prometheus", "Loki", "Tempo")).issubset(datasources),
"Grafana is missing required datasources")
status, _, _ = https_json("https://127.0.0.1:9090/-/ready")
check(status == 200, "Prometheus is not ready")
status, _, _ = https_json("https://127.0.0.1:3100/loki/api/v1/status/buildinfo")
check(status == 200, "Loki API is not ready")
status, _, _ = https_json("https://127.0.0.1:3200/status")
check(status == 200, "Tempo search API is not ready")
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
status, _, raw = https_json(
"https://127.0.0.1:9464/metrics"
)
text = raw.decode("utf-8", "replace")
if status == 200 and "messenger_http_requests" in text:
break
time.sleep(1)
else:
raise AssertionError("collector did not expose messenger HTTP metrics")
status, _, raw = http_json(
"http://127.0.0.1:3000/api/dashboards/uid/messenger-lab6"
)
check(status == 200, "Lab6 dashboard was not provisioned")
dashboard = json.loads(raw)["dashboard"]
check(dashboard["title"] == "Messenger Observability",
"unexpected Grafana dashboard title")
print("PASS: Grafana datasources/dashboard and Prometheus/Loki/Tempo backends are ready")
if __name__ == "__main__":
run(main)
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Verify bounded API errors during an S3 outage, then restore the service."""
import os
from pathlib import Path
import subprocess
from urllib.parse import quote
from client import Client, arguments, run
ROOT = Path(__file__).resolve().parents[1]
def compose(*args):
command = [
"docker", "compose", "--project-directory", str(ROOT),
"--env-file", str(ROOT / ".env"), *args,
]
subprocess.run(
command,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def main():
args = arguments("Verify API responses when MinIO is unavailable")
client = Client(args.base_url, args.ca_file, timeout=15)
alice, _, _, chat = client.bootstrap()
content = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
compose("stop", "s3")
try:
health = client.call("GET", "/health/ready", 503)
if health["elapsed"] > 10:
raise AssertionError("S3 readiness failure exceeded 10 seconds")
upload = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote("sample.png"),
503,
actor=alice,
raw=content,
headers={"Content-Type": "image/png"},
)
if upload["elapsed"] > 10:
raise AssertionError("S3 upload failure exceeded 10 seconds")
finally:
compose("start", "s3")
compose("up", "-d", "--wait", "s3")
client.call("GET", "/health/ready", 200)
print("PASS: MinIO outage returns bounded 503 errors and recovers")
if __name__ == "__main__":
run(main)
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Focused tests for the required thumbnail transformation."""
import io
from pathlib import Path
import sys
from unittest.mock import Mock, patch
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from queueing import JOB_QUEUE, publish_event
from worker import InvalidImage, parse_event, thumbnail_jpeg
def main():
event = parse_event(
b'{"schema_version":1,"job_id":"11111111-1111-4111-8111-111111111111",'
b'"type":"attachment.process.v1","attachment_id":"22222222-2222-4222-8222-222222222222",'
b'"pipeline_version":1,"attempt":1,"created_at":"2026-09-01T12:00:00Z"}'
)
assert event["attempt"] == 1
try:
parse_event(b'{"schema_version":1}')
except ValueError:
pass
else:
raise AssertionError("incomplete job message should be rejected")
publisher_event = {
"schema_version": 1,
"job_id": "11111111-1111-4111-8111-111111111111",
"type": "attachment.process.v1",
"attachment_id": "22222222-2222-4222-8222-222222222222",
"pipeline_version": 1,
"attempt": 1,
"created_at": "2026-09-01T12:00:00Z",
}
connection = Mock()
connection.is_open = True
channel = connection.channel.return_value
channel.basic_publish.return_value = True
with patch("queueing.pika.BlockingConnection", return_value=connection), \
patch("queueing.connection_parameters", return_value=Mock()):
publish_event(publisher_event)
channel.queue_declare.assert_any_call(
queue=JOB_QUEUE,
durable=True,
arguments={
"x-dead-letter-exchange": "attachment.jobs.dlx",
"x-dead-letter-routing-key": "attachment.jobs.dead",
},
)
channel.confirm_delivery.assert_called_once()
published = channel.basic_publish.call_args.kwargs
assert published["mandatory"] is True
assert published["properties"].delivery_mode == 2
assert set(publisher_event) == {
"schema_version", "job_id", "type", "attachment_id",
"pipeline_version", "attempt", "created_at",
}
sample = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
thumbnail, width, height = thumbnail_jpeg(sample, "image/png")
assert (width, height) == (256, 160), (width, height)
with Image.open(io.BytesIO(thumbnail)) as image:
assert image.format == "JPEG"
assert image.size == (256, 160)
small = Image.new("RGBA", (30, 20), (255, 0, 0, 0))
small_bytes = io.BytesIO()
small.save(small_bytes, format="PNG")
result, width, height = thumbnail_jpeg(small_bytes.getvalue(), "image/png")
assert (width, height) == (30, 20), (width, height)
with Image.open(io.BytesIO(result)) as image:
assert image.getpixel((0, 0)) == (255, 255, 255)
try:
thumbnail_jpeg(b"not an image", "image/png")
except InvalidImage:
pass
else:
raise AssertionError("corrupt image should be rejected")
print("PASS: 256x256 contain, no-upscale, alpha-on-white, invalid image")
if __name__ == "__main__":
main()
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Exercise a queued upload across API/broker restarts and duplicate delivery."""
import hashlib
from pathlib import Path
import subprocess
import time
from urllib.parse import quote
from client import Client, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
def compose(*args):
command = [
"docker", "compose", "--project-directory", str(ROOT),
"--env-file", str(ROOT / ".env"), *args,
]
subprocess.run(
command,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=120,
)
def republish_completed_job(attachment_id):
source = r"""
import sys
from datetime import timezone
import psycopg
from app import database_conninfo
from queueing import publish_event
with psycopg.connect(database_conninfo()) as conn:
job = conn.execute(
"SELECT id, attachment_id, pipeline_version, attempt, created_at "
"FROM image_jobs WHERE attachment_id = %s",
(sys.argv[1],),
).fetchone()
if job is None:
raise SystemExit("job not found")
created_at = job[4].astimezone(timezone.utc)
publish_event({
"schema_version": 1,
"job_id": str(job[0]),
"type": "attachment.process.v1",
"attachment_id": str(job[1]),
"pipeline_version": job[2],
"attempt": job[3],
"created_at": created_at.isoformat(timespec="microseconds").replace("+00:00", "Z"),
})
"""
command = [
"docker", "compose", "--project-directory", str(ROOT),
"--env-file", str(ROOT / ".env"), "run", "--rm", "--no-deps",
"api", "python", "-c", source, attachment_id,
]
subprocess.run(
command,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=30,
)
def main():
args = arguments("Verify queued job recovery and idempotent redelivery")
client = Client(args.base_url, args.ca_file, timeout=10)
alice, bob, _, chat = client.bootstrap()
content = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
upload_path = (
"/api/v1/chats/" + chat["id"]
+ "/attachments?filename=" + quote("sample.png", safe="")
)
compose("stop", "worker")
try:
uploaded = client.call(
"POST",
upload_path,
202,
actor=alice,
raw=content,
headers={"Content-Type": "image/png"},
schema="Attachment",
)["json"]
check(uploaded["status"] == "queued", "stopped worker upload was not queued")
client.call(
"GET",
"/api/v1/attachments/" + uploaded["id"] + "/content",
409,
actor=bob,
)
linked = client.message(
alice, chat, "", attachments=[uploaded["id"]]
)["json"]
check(linked["attachment_ids"] == [uploaded["id"]],
"queued attachment could not be linked to a message")
compose("restart", "db", "s3", "broker")
compose("up", "-d", "--wait", "db", "s3", "broker")
compose("run", "--rm", "s3-init")
compose("restart", "api")
compose("up", "-d", "--wait", "--scale", "api=2", "api", "lb")
compose("start", "worker")
ready = client.wait_ready(alice, uploaded, wait_seconds=60)
check(ready["status"] == "ready", "queued work did not recover to ready")
original = client.call(
"GET",
"/api/v1/attachments/" + uploaded["id"] + "/content",
actor=bob,
)
check(original["bytes"] == content, "recovered original bytes changed")
thumbnail = client.call(
"GET",
"/api/v1/attachments/" + uploaded["id"] + "/content?variant=thumbnail",
actor=bob,
)
variant = ready["variants"][0]
check(
hashlib.sha256(thumbnail["bytes"]).hexdigest() == variant["sha256"],
"thumbnail changed after recovery",
)
republish_completed_job(uploaded["id"])
time.sleep(1)
after_duplicate = client.call(
"GET",
"/api/v1/attachments/" + uploaded["id"],
actor=bob,
schema="Attachment",
)["json"]
check(after_duplicate["status"] == "ready",
"duplicate delivery changed a completed attachment state")
check(len(after_duplicate["variants"]) == 1,
"duplicate delivery created duplicate variants")
print("PASS: queued upload survived API/DB/S3/broker restart; duplicate was idempotent")
finally:
compose("up", "-d", "--scale", "api=2", "api", "worker", "lb")
if __name__ == "__main__":
run(main)
+466
View File
@@ -0,0 +1,466 @@
#!/usr/bin/env python3
"""Durable RabbitMQ consumer for image attachment processing."""
import hashlib
import io
import json
import logging
import os
import re
import signal
import threading
import time
import warnings
import uuid
from datetime import datetime
from opentelemetry import trace
from opentelemetry.propagate import extract
import observability as telemetry
from service_secrets import load_service_secrets
import pika
from PIL import Image, ImageOps, UnidentifiedImageError
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
import psycopg
from psycopg_pool import ConnectionPool, PoolTimeout
from botocore.exceptions import BotoCoreError, ClientError
from app import (
MAX_IMAGE_PIXELS,
MAX_UPLOAD_BYTES,
create_s3_client,
database_conninfo,
)
from queueing import (
JOB_QUEUE,
BrokerUnavailable,
connection_parameters,
declare_topology,
publish_pending_job,
)
LOG = logging.getLogger("attachment-worker")
STOP_REQUESTED = threading.Event()
POOL = None
S3_CLIENT = None
S3_BUCKET = None
class InvalidImage(Exception):
pass
def parse_event(raw):
try:
event = json.loads(raw.decode("utf-8"))
except (UnicodeError, ValueError):
raise ValueError("invalid job JSON") from None
required = {
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at",
}
optional = {"traceparent", "tracestate"}
if not isinstance(event, dict) or not required.issubset(event) or set(event) - required - optional:
raise ValueError("invalid job fields")
if (not isinstance(event["schema_version"], int)
or isinstance(event["schema_version"], bool)
or event["schema_version"] != 1
or event["type"] != "attachment.process.v1"
or not isinstance(event["pipeline_version"], int)
or isinstance(event["pipeline_version"], bool)
or event["pipeline_version"] != 1
or not isinstance(event["attempt"], int)
or isinstance(event["attempt"], bool)
or event["attempt"] < 1
or not isinstance(event["created_at"], str)):
raise ValueError("invalid job metadata")
try:
created_at = datetime.fromisoformat(event["created_at"].replace("Z", "+00:00"))
if created_at.tzinfo is None:
raise ValueError("created_at must include a timezone")
except ValueError:
raise ValueError("invalid job timestamp") from None
if "traceparent" in event and (
not isinstance(event["traceparent"], str)
or not re.fullmatch(
r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}",
event["traceparent"],
)
):
raise ValueError("invalid traceparent")
if "tracestate" in event and (
not isinstance(event["tracestate"], str) or len(event["tracestate"]) > 512
):
raise ValueError("invalid tracestate")
try:
event["job_id"] = uuid.UUID(event["job_id"])
event["attachment_id"] = uuid.UUID(event["attachment_id"])
except (ValueError, TypeError, AttributeError):
raise ValueError("invalid job identifier") from None
return event
def thumbnail_jpeg(data, content_type):
expected_format = {"image/png": "PNG", "image/jpeg": "JPEG"}.get(content_type)
if expected_format is None:
raise InvalidImage("unsupported source type")
try:
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(io.BytesIO(data)) as source:
if source.format != expected_format:
raise InvalidImage("source format mismatch")
if source.width * source.height > MAX_IMAGE_PIXELS:
raise InvalidImage("source image exceeds pixel limit")
source.load()
image = ImageOps.exif_transpose(source)
width, height = image.size
scale = min(256 / width, 256 / height, 1.0)
target_size = (max(1, int(width * scale)), max(1, int(height * scale)))
if image.mode in ("RGBA", "LA") or "transparency" in image.info:
rgba = image.convert("RGBA")
rgb = Image.new("RGB", rgba.size, "white")
rgb.paste(rgba, mask=rgba.getchannel("A"))
else:
rgb = image.convert("RGB")
if target_size != rgb.size:
rgb = rgb.resize(target_size, Image.Resampling.LANCZOS)
output = io.BytesIO()
rgb.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue(), target_size[0], target_size[1]
except InvalidImage:
raise
except (Image.DecompressionBombError, Image.DecompressionBombWarning,
OSError, SyntaxError, UnidentifiedImageError, ValueError):
raise InvalidImage("image decoding failed") from None
def fail_job(conn, job_id, attachment_id, error_code):
conn.execute(
"""UPDATE image_jobs
SET status = 'failed', last_error_code = %s, updated_at = now()
WHERE id = %s""",
(error_code, job_id),
)
conn.execute(
"""UPDATE attachments
SET status = 'failed', error_code = %s, updated_at = now()
WHERE id = %s""",
(error_code, attachment_id),
)
conn.commit()
def process_locked_job(conn, event):
job = conn.execute(
"""SELECT j.id, j.attachment_id, j.pipeline_version, j.attempt,
j.max_attempts, j.status AS job_status, j.created_at,
a.content_type, a.size_bytes, a.sha256, a.object_key, a.staging_key
FROM image_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.id = %s AND j.attachment_id = %s""",
(event["job_id"], event["attachment_id"]),
).fetchone()
if job is None or job["job_status"] in ("ready", "failed"):
conn.commit()
return "ack"
if event["attempt"] < job["attempt"]:
conn.commit()
publish_pending_job(POOL, job["id"])
return "ack"
if event["attempt"] != job["attempt"]:
LOG.warning("job attempt mismatch job_id=%s", job["id"])
conn.commit()
return "ack"
conn.execute(
"""UPDATE image_jobs SET status = 'processing', updated_at = now()
WHERE id = %s""",
(job["id"],),
)
conn.execute(
"""UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = now()
WHERE id = %s""",
(job["attachment_id"],),
)
conn.commit()
if not job["staging_key"]:
raise InvalidImage("staging object missing")
response = S3_CLIENT.get_object(Bucket=S3_BUCKET, Key=job["staging_key"])
with response["Body"] as body:
original = body.read(MAX_UPLOAD_BYTES + 1)
if (len(original) != job["size_bytes"] or len(original) > MAX_UPLOAD_BYTES
or hashlib.sha256(original).hexdigest() != job["sha256"]):
raise InvalidImage("staging integrity check failed")
thumbnail, width, height = thumbnail_jpeg(original, job["content_type"])
thumbnail_sha256 = hashlib.sha256(thumbnail).hexdigest()
thumbnail_key = (
"attachments/" + str(job["attachment_id"]) + "/variants/thumbnail.jpg"
)
S3_CLIENT.put_object(
Bucket=S3_BUCKET,
Key=job["object_key"],
Body=original,
ContentType=job["content_type"],
Metadata={"sha256": job["sha256"]},
)
S3_CLIENT.put_object(
Bucket=S3_BUCKET,
Key=thumbnail_key,
Body=thumbnail,
ContentType="image/jpeg",
Metadata={"sha256": thumbnail_sha256},
)
variants = [{
"name": "thumbnail",
"content_type": "image/jpeg",
"size_bytes": len(thumbnail),
"width": width,
"height": height,
"sha256": thumbnail_sha256,
}]
conn.execute(
"""UPDATE attachments
SET status = 'ready', variants = %s, error_code = NULL, updated_at = now()
WHERE id = %s""",
(Jsonb(variants), job["attachment_id"]),
)
conn.execute(
"""UPDATE image_jobs SET status = 'ready', last_error_code = NULL, updated_at = now()
WHERE id = %s""",
(job["id"],),
)
conn.commit()
try:
S3_CLIENT.delete_object(Bucket=S3_BUCKET, Key=job["staging_key"])
except (BotoCoreError, ClientError) as error:
LOG.warning(
"staging cleanup deferred attachment_id=%s error_type=%s",
job["attachment_id"],
type(error).__name__,
)
return "ack"
def process_job(event):
with POOL.connection() as conn:
lock_key = str(event["job_id"])
conn.execute(
"SELECT pg_advisory_lock(hashtextextended(%s, 0))",
(lock_key,),
)
conn.commit()
try:
try:
return process_locked_job(conn, event)
except BrokerUnavailable:
conn.rollback()
raise
except InvalidImage:
conn.rollback()
row = conn.execute(
"""SELECT attachment_id FROM image_jobs WHERE id = %s""",
(event["job_id"],),
).fetchone()
if row is not None:
fail_job(conn, event["job_id"], row["attachment_id"], "invalid_image")
else:
conn.commit()
return "ack"
except Exception as error:
conn.rollback()
LOG.warning(
"job processing failed job_id=%s error_type=%s",
event["job_id"],
type(error).__name__,
)
row = conn.execute(
"""SELECT j.attachment_id, j.attempt, j.max_attempts, j.status
FROM image_jobs j WHERE j.id = %s""",
(event["job_id"],),
).fetchone()
if row is None or row["status"] in ("ready", "failed"):
conn.commit()
return "ack"
if event["attempt"] < row["attempt"]:
conn.commit()
publish_pending_job(POOL, event["job_id"])
return "ack"
if row["attempt"] >= row["max_attempts"]:
fail_job(
conn,
event["job_id"],
row["attachment_id"],
"retry_exhausted",
)
return "ack"
next_attempt = row["attempt"] + 1
conn.execute(
"""UPDATE image_jobs
SET status = 'queued', attempt = %s,
last_error_code = 'processing_failed', updated_at = now()
WHERE id = %s""",
(next_attempt, event["job_id"]),
)
conn.execute(
"""UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = %s""",
(row["attachment_id"],),
)
conn.commit()
publish_pending_job(POOL, event["job_id"])
return "ack"
finally:
conn.rollback()
try:
conn.execute(
"SELECT pg_advisory_unlock(hashtextextended(%s, 0))",
(lock_key,),
)
conn.commit()
except psycopg.Error:
LOG.warning("failed to release job lock job_id=%s", event["job_id"])
def on_message(channel, method, _properties, body):
try:
event = parse_event(body)
except ValueError as error:
LOG.warning("invalid broker message error=%s", str(error))
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
return
carrier = {}
if "traceparent" in event:
carrier["traceparent"] = event["traceparent"]
if "tracestate" in event:
carrier["tracestate"] = event["tracestate"]
context = extract(carrier)
started = time.monotonic()
outcome = "success"
if telemetry.TRACER is not None:
with telemetry.TRACER.start_as_current_span(
"process attachment",
context=context,
kind=trace.SpanKind.CONSUMER,
attributes={
"messaging.system": "rabbitmq",
"messaging.destination.name": JOB_QUEUE,
"messaging.operation.name": "process",
"attachment.job_id": str(event["job_id"]),
"attachment.pipeline_version": event["pipeline_version"],
},
) as span:
try:
process_job(event)
except (BrokerUnavailable, psycopg.Error, PoolTimeout,
BotoCoreError, ClientError, OSError) as error:
outcome = "deferred"
span.set_status(trace.Status(trace.StatusCode.ERROR))
LOG.warning(
"job deferred job_id=%s error_type=%s",
event["job_id"],
type(error).__name__,
)
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
else:
span.set_status(trace.Status(trace.StatusCode.OK))
channel.basic_ack(delivery_tag=method.delivery_tag)
else:
try:
process_job(event)
except (BrokerUnavailable, psycopg.Error, PoolTimeout,
BotoCoreError, ClientError, OSError):
outcome = "deferred"
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
else:
channel.basic_ack(delivery_tag=method.delivery_tag)
duration = time.monotonic() - started
if telemetry.JOBS_PROCESSED is not None:
telemetry.JOBS_PROCESSED.add(
1,
{"job_type": "attachment.process.v1", "outcome": outcome},
)
if telemetry.JOB_DURATION is not None:
telemetry.JOB_DURATION.record(
duration,
{"job_type": "attachment.process.v1", "outcome": outcome},
)
def run_worker():
global POOL, S3_CLIENT, S3_BUCKET
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
try:
load_service_secrets("worker")
except Exception as error:
raise SystemExit("OpenBao service authentication failed") from error
telemetry.setup_observability(
os.environ.get("OTEL_SERVICE_NAME", "messenger-worker")
)
if not 1 <= int(os.environ.get("WORKER_PREFETCH", "1")) <= 8:
raise SystemExit("WORKER_PREFETCH must be between 1 and 8")
max_connections = int(os.environ.get("DB_POOL_MAX_SIZE", "5"))
if not 2 <= max_connections <= 100:
raise SystemExit("DB_POOL_MAX_SIZE must be between 2 and 100 for the worker")
S3_CLIENT, S3_BUCKET = create_s3_client()
POOL = ConnectionPool(
conninfo=database_conninfo(),
min_size=1,
max_size=max_connections,
timeout=5,
kwargs={"row_factory": dict_row},
open=False,
)
POOL.open(wait=True, timeout=15)
with POOL.connection() as conn:
conn.execute("SELECT 1")
def request_shutdown(_signum, _frame):
STOP_REQUESTED.set()
signal.signal(signal.SIGTERM, request_shutdown)
signal.signal(signal.SIGINT, request_shutdown)
try:
while not STOP_REQUESTED.is_set():
connection = None
try:
connection = pika.BlockingConnection(connection_parameters())
channel = connection.channel()
declare_topology(channel)
channel.basic_qos(
prefetch_count=int(os.environ.get("WORKER_PREFETCH", "1"))
)
channel.basic_consume(
queue=JOB_QUEUE,
on_message_callback=on_message,
auto_ack=False,
)
LOG.info("worker consuming durable attachment queue")
while connection.is_open and not STOP_REQUESTED.is_set():
connection.process_data_events(time_limit=1)
except (pika.exceptions.AMQPError, OSError, TimeoutError) as error:
LOG.warning("broker connection interrupted error_type=%s", type(error).__name__)
finally:
if connection is not None and connection.is_open:
connection.close()
if not STOP_REQUESTED.is_set():
STOP_REQUESTED.wait(2)
finally:
POOL.close()
LOG.info("worker stopped")
if __name__ == "__main__":
run_worker()